xref: /freebsd/contrib/libarchive/unzip/bsdunzip.c (revision 185becb1e1bd2657c156f78aeb52edac05ba5fb5)
1 /*-
2  * SPDX-License-Identifier: BSD-2-Clause
3  *
4  * Copyright (c) 2009, 2010 Joerg Sonnenberger <joerg@NetBSD.org>
5  * Copyright (c) 2007-2008 Dag-Erling Smørgrav
6  * All rights reserved.
7  */
8 
9 #include "bsdunzip_platform.h"
10 
11 #include "la_queue.h"
12 #include "lafe_fnmatch.h"
13 #include "lafe_getline.h"
14 #ifdef HAVE_SYS_STAT_H
15 #include <sys/stat.h>
16 #endif
17 
18 #ifdef HAVE_CTYPE_H
19 #include <ctype.h>
20 #endif
21 #ifdef HAVE_ERRNO_H
22 #include <errno.h>
23 #endif
24 #ifdef HAVE_FCNTL_H
25 #include <fcntl.h>
26 #endif
27 #ifdef HAVE_FNMATCH_H
28 #include <fnmatch.h>
29 #endif
30 #ifdef HAVE_LOCALE_H
31 #include <locale.h>
32 #endif
33 #ifdef HAVE_SIGNAL_H
34 #include <signal.h>
35 #endif
36 #ifdef HAVE_STDARG_H
37 #include <stdarg.h>
38 #endif
39 #include <stdio.h>
40 #ifdef HAVE_STDLIB_H
41 #include <stdlib.h>
42 #endif
43 #ifdef HAVE_STRING_H
44 #include <string.h>
45 #endif
46 #ifdef HAVE_UNISTD_H
47 #include <unistd.h>
48 #endif
49 #if ((!defined(HAVE_UTIMENSAT) && defined(HAVE_LUTIMES)) || \
50     (!defined(HAVE_FUTIMENS) && defined(HAVE_FUTIMES)))
51 #ifdef HAVE_SYS_TIME_H
52 #include <sys/time.h>
53 #endif
54 #endif
55 
56 #include "bsdunzip.h"
57 #include "passphrase.h"
58 #include "lafe_err.h"
59 
60 /* command-line options */
61 static int		 a_opt;		/* convert EOL */
62 static int		 C_opt;		/* match case-insensitively */
63 static int		 c_opt;		/* extract to stdout */
64 static const char	*d_arg;		/* directory */
65 static int		 f_opt;		/* update existing files only */
66 static const char	*O_arg;		/* encoding */
67 static int		 j_opt;		/* junk directories */
68 static int		 L_opt;		/* lowercase names */
69 static int		 n_opt;		/* never overwrite */
70 static int		 o_opt;		/* always overwrite */
71 static int		 p_opt;		/* extract to stdout, quiet */
72 static const char	*P_arg;		/* passphrase */
73 static int		 q_opt;		/* quiet */
74 static int		 t_opt;		/* test */
75 static int		 u_opt;		/* update */
76 static int		 v_opt;		/* verbose/list */
77 static const char	*y_str = "";	/* 4 digit year */
78 static int		 Z1_opt;	/* zipinfo mode list files only */
79 static int		 version_opt;	/* version string */
80 
81 /* debug flag */
82 static int		 unzip_debug;
83 
84 /* zipinfo mode */
85 static int		 zipinfo_mode;
86 
87 /* running on tty? */
88 static int		 tty;
89 
90 /* processing exclude list */
91 static int		 unzip_exclude_mode = 0;
92 
93 int bsdunzip_optind;
94 
95 /* convenience macro */
96 /* XXX should differentiate between ARCHIVE_{WARN,FAIL,RETRY} */
97 #define ac(call)						\
98 	do {							\
99 		int acret = (call);				\
100 		if (acret != ARCHIVE_OK)			\
101 			errorx("%s", archive_error_string(a));	\
102 	} while (0)
103 
104 /*
105  * Indicates that last info() did not end with EOL.  This helps error() et
106  * al. avoid printing an error message on the same line as an incomplete
107  * informational message.
108  */
109 static int noeol;
110 
111 /* for an interactive passphrase input */
112 static char *passphrase_buf;
113 
114 /* fatal error message + errno */
115 static void __LA_NORETURN
error(const char * fmt,...)116 error(const char *fmt, ...)
117 {
118 	va_list ap;
119 
120 	if (noeol)
121 		fprintf(stdout, "\n");
122 	fflush(stdout);
123 	fprintf(stderr, "unzip: ");
124 	va_start(ap, fmt);
125 	vfprintf(stderr, fmt, ap);
126 	va_end(ap);
127 	fprintf(stderr, ": %s\n", strerror(errno));
128 	exit(EXIT_FAILURE);
129 }
130 
131 /* fatal error message, no errno */
132 static void __LA_NORETURN
errorx(const char * fmt,...)133 errorx(const char *fmt, ...)
134 {
135 	va_list ap;
136 
137 	if (noeol)
138 		fprintf(stdout, "\n");
139 	fflush(stdout);
140 	fprintf(stderr, "unzip: ");
141 	va_start(ap, fmt);
142 	vfprintf(stderr, fmt, ap);
143 	va_end(ap);
144 	fprintf(stderr, "\n");
145 	exit(EXIT_FAILURE);
146 }
147 
148 #if defined(HAVE_LCHMOD) || defined(HAVE_UTIMENSAT) || defined(HAVE_LUTIMES)
149 /* non-fatal error message + errno */
150 static void
warning(const char * fmt,...)151 warning(const char *fmt, ...)
152 {
153 	va_list ap;
154 
155 	if (noeol)
156 		fprintf(stdout, "\n");
157 	fflush(stdout);
158 	fprintf(stderr, "unzip: ");
159 	va_start(ap, fmt);
160 	vfprintf(stderr, fmt, ap);
161 	va_end(ap);
162 	fprintf(stderr, ": %s\n", strerror(errno));
163 }
164 #endif
165 
166 /* non-fatal error message, no errno */
167 static void
warningx(const char * fmt,...)168 warningx(const char *fmt, ...)
169 {
170 	va_list ap;
171 
172 	if (noeol)
173 		fprintf(stdout, "\n");
174 	fflush(stdout);
175 	fprintf(stderr, "unzip: ");
176 	va_start(ap, fmt);
177 	vfprintf(stderr, fmt, ap);
178 	va_end(ap);
179 	fprintf(stderr, "\n");
180 }
181 
182 /* informational message (if not -q) */
183 static void
info(const char * fmt,...)184 info(const char *fmt, ...)
185 {
186 	va_list ap;
187 
188 	if (q_opt && !unzip_debug)
189 		return;
190 	va_start(ap, fmt);
191 	vfprintf(stdout, fmt, ap);
192 	va_end(ap);
193 	fflush(stdout);
194 
195 	if (*fmt == '\0')
196 		noeol = 1;
197 	else
198 		noeol = fmt[strlen(fmt) - 1] != '\n';
199 }
200 
201 /* debug message (if unzip_debug) */
202 static void
debug(const char * fmt,...)203 debug(const char *fmt, ...)
204 {
205 	va_list ap;
206 
207 	if (!unzip_debug)
208 		return;
209 	va_start(ap, fmt);
210 	vfprintf(stderr, fmt, ap);
211 	va_end(ap);
212 	fflush(stderr);
213 
214 	if (*fmt == '\0')
215 		noeol = 1;
216 	else
217 		noeol = fmt[strlen(fmt) - 1] != '\n';
218 }
219 
220 /* duplicate a path name, possibly converting to lower case */
221 static char *
pathdup(const char * path)222 pathdup(const char *path)
223 {
224 	char *str;
225 	size_t i, len;
226 
227 	if (path == NULL || path[0] == '\0')
228 		return (NULL);
229 
230 	len = strlen(path);
231 	while (len && path[len - 1] == '/')
232 		len--;
233 	if ((str = malloc(len + 1)) == NULL) {
234 		errno = ENOMEM;
235 		error("malloc()");
236 	}
237 	if (L_opt) {
238 		for (i = 0; i < len; ++i)
239 			str[i] = (char)tolower((unsigned char)path[i]);
240 	} else {
241 		memcpy(str, path, len);
242 	}
243 	str[len] = '\0';
244 
245 	return (str);
246 }
247 
248 /* concatenate two path names */
249 static char *
pathcat(const char * prefix,const char * path)250 pathcat(const char *prefix, const char *path)
251 {
252 	char *str;
253 	size_t prelen, len;
254 
255 	prelen = prefix ? strlen(prefix) + 1 : 0;
256 	len = strlen(path) + 1;
257 	if ((str = malloc(prelen + len)) == NULL) {
258 		errno = ENOMEM;
259 		error("malloc()");
260 	}
261 	if (prefix) {
262 		memcpy(str, prefix, prelen);	/* includes zero */
263 		str[prelen - 1] = '/';		/* splat zero */
264 	}
265 	memcpy(str + prelen, path, len);	/* includes zero */
266 
267 	return (str);
268 }
269 
270 /*
271  * Pattern lists for include / exclude processing
272  */
273 struct pattern {
274 	STAILQ_ENTRY(pattern) link;
275 	char pattern[];
276 };
277 
278 STAILQ_HEAD(pattern_list, pattern);
279 static struct pattern_list include = STAILQ_HEAD_INITIALIZER(include);
280 static struct pattern_list exclude = STAILQ_HEAD_INITIALIZER(exclude);
281 
282 /*
283  * Add an entry to a pattern list
284  */
285 static void
add_pattern(struct pattern_list * list,const char * pattern)286 add_pattern(struct pattern_list *list, const char *pattern)
287 {
288 	struct pattern *entry;
289 	size_t len;
290 
291 	debug("adding pattern '%s'\n", pattern);
292 	len = strlen(pattern);
293 	if ((entry = malloc(sizeof *entry + len + 1)) == NULL) {
294 		errno = ENOMEM;
295 		error("malloc()");
296 	}
297 	memcpy(entry->pattern, pattern, len + 1);
298 	STAILQ_INSERT_TAIL(list, entry, link);
299 }
300 
301 /*
302  * Match a string against a list of patterns
303  */
304 static int
match_pattern(struct pattern_list * list,const char * str)305 match_pattern(struct pattern_list *list, const char *str)
306 {
307 	struct pattern *entry;
308 
309 	STAILQ_FOREACH(entry, list, link) {
310 		if (fnmatch(entry->pattern, str, C_opt ? FNM_CASEFOLD : 0) == 0)
311 			return (1);
312 	}
313 	return (0);
314 }
315 
316 /*
317  * Verify that a given pathname is in the include list and not in the
318  * exclude list.
319  */
320 static int
accept_pathname(const char * pathname)321 accept_pathname(const char *pathname)
322 {
323 
324 	if (!STAILQ_EMPTY(&include) && !match_pattern(&include, pathname))
325 		return (0);
326 	if (!STAILQ_EMPTY(&exclude) && match_pattern(&exclude, pathname))
327 		return (0);
328 	return (1);
329 }
330 
331 /* System call to create a directory. */
332 static int
system_mkdir(const char * pathname,int mode)333 system_mkdir(const char *pathname, int mode)
334 {
335 #if defined(_WIN32) && !defined(__CYGWIN__)
336 	(void)mode; /* UNUSED */
337 	return _mkdir(pathname);
338 #else
339 	return mkdir(pathname, mode);
340 #endif
341 }
342 
343 static void
system_unlink(const char * pathname)344 system_unlink(const char *pathname) {
345 #if defined(_WIN32) && !defined(__CYGWIN__)
346 	if (unlink(pathname) == -1) {
347 		/* Windows treats directory symbolic links specially. */
348 		rmdir(pathname);
349 	}
350 #else
351 	(void)unlink(pathname);
352 #endif
353 }
354 
355 /*
356  * Create the specified directory with the specified mode, taking certain
357  * precautions on the way.
358  */
359 static void
make_dir(const char * path,int mode)360 make_dir(const char *path, int mode)
361 {
362 	struct stat sb;
363 
364 	if (lstat(path, &sb) == 0) {
365 		if (S_ISDIR(sb.st_mode))
366 			return;
367 		/*
368 		 * Normally, we should either ask the user about removing
369 		 * the non-directory of the same name as a directory we
370 		 * wish to create, or respect the -n or -o command-line
371 		 * options.  However, this may lead to a later failure or
372 		 * even compromise (if this non-directory happens to be a
373 		 * symlink to somewhere unsafe), so we don't.
374 		 */
375 		system_unlink(path);
376 	}
377 	if (system_mkdir(path, (mode_t)mode) != 0 && errno != EEXIST)
378 		error("mkdir('%s')", path);
379 }
380 
381 /*
382  * Ensure that all directories leading up to (but not including) the
383  * specified path exist.
384  *
385  * XXX inefficient + modifies the file in-place
386  */
387 static void
make_parent(char * path)388 make_parent(char *path)
389 {
390 	struct stat sb;
391 	char *sep;
392 
393 	sep = strrchr(path, '/');
394 	if (sep == NULL || sep == path)
395 		return;
396 	*sep = '\0';
397 	if (lstat(path, &sb) == 0) {
398 		if (S_ISDIR(sb.st_mode)) {
399 			*sep = '/';
400 			return;
401 		}
402 		system_unlink(path);
403 	}
404 	make_parent(path);
405 	system_mkdir(path, 0755);
406 	*sep = '/';
407 
408 #if 0
409 	for (sep = path; (sep = strchr(sep, '/')) != NULL; sep++) {
410 		/* root in case of absolute d_arg */
411 		if (sep == path)
412 			continue;
413 		*sep = '\0';
414 		make_dir(path, 0755);
415 		*sep = '/';
416 	}
417 #endif
418 }
419 
420 /*
421  * Extract a directory.
422  */
423 static void
extract_dir(struct archive * a,struct archive_entry * e,const char * path)424 extract_dir(struct archive *a, struct archive_entry *e, const char *path)
425 {
426 	int mode;
427 
428 	/*
429 	 * Dropbox likes to create '/' directory entries, just ignore
430 	 * such junk.
431 	 */
432 	if (*path == '\0')
433 		return;
434 
435 	mode = archive_entry_mode(e) & 0777;
436 	if (mode == 0)
437 		mode = 0755;
438 
439 	/*
440 	 * Some zipfiles contain directories with weird permissions such
441 	 * as 0644 or 0444.  This can cause strange issues such as being
442 	 * unable to extract files into the directory we just created, or
443 	 * the user being unable to remove the directory later without
444 	 * first manually changing its permissions.  Therefore, we whack
445 	 * the permissions into shape, assuming that the user wants full
446 	 * access and that anyone who gets read access also gets execute
447 	 * access.
448 	 */
449 	mode |= 0700;
450 	if (mode & 0040)
451 		mode |= 0010;
452 	if (mode & 0004)
453 		mode |= 0001;
454 
455 	info("   creating: %s/\n", path);
456 	make_dir(path, mode);
457 	ac(archive_read_data_skip(a));
458 }
459 
460 static unsigned char buffer[8192];
461 static char spinner[] = { '|', '/', '-', '\\' };
462 
463 static int
handle_existing_file(char ** path)464 handle_existing_file(char **path)
465 {
466 	size_t alen;
467 	ssize_t len;
468 	char buf[4];
469 
470 	for (;;) {
471 		fprintf(stderr,
472 		    "replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ",
473 		    *path);
474 		if (fgets(buf, sizeof(buf), stdin) == NULL)
475 			goto stdin_err;
476 		switch (*buf) {
477 		case 'A':
478 			o_opt = 1;
479 			/* FALLTHROUGH */
480 		case 'y':
481 		case 'Y':
482 			system_unlink(*path);
483 			return 1;
484 		case 'N':
485 			n_opt = 1;
486 			/* FALLTHROUGH */
487 		case 'n':
488 			return -1;
489 		case 'r':
490 		case 'R':
491 			printf("New name: ");
492 			fflush(stdout);
493 			free(*path);
494 			*path = NULL;
495 			alen = 0;
496 			len = getline(path, &alen, stdin);
497 			if (len < 1)
498 				goto stdin_err;
499 			if ((*path)[len - 1] == '\n')
500 				(*path)[len - 1] = '\0';
501 			return 0;
502 		default:
503 			break;
504 		}
505 	}
506 stdin_err:
507 	clearerr(stdin);
508 	printf("NULL\n(EOF or read error, "
509 		"treating as \"[N]one\"...)\n");
510 	n_opt = 1;
511 	return -1;
512 }
513 
514 /*
515  * Detect binary files by a combination of character white list and
516  * black list. NUL bytes and other control codes without use in text files
517  * result directly in switching the file to binary mode. Otherwise, at least
518  * one white-listed byte has to be found.
519  *
520  * Black-listed: 0..6, 14..25, 28..31
521  * 0xf3ffc07f = 11110011111111111100000001111111b
522  * White-listed: 9..10, 13, >= 32
523  * 0x00002600 = 00000000000000000010011000000000b
524  *
525  * See the proginfo/txtvsbin.txt in the zip sources for a detailed discussion.
526  */
527 #define BYTE_IS_BINARY(x)	((x) < 32 && (0xf3ffc07fU & (1U << (x))))
528 #define	BYTE_IS_TEXT(x)		((x) >= 32 || (0x00002600U & (1U << (x))))
529 
530 static int
check_binary(const unsigned char * buf,size_t len)531 check_binary(const unsigned char *buf, size_t len)
532 {
533 	int rv;
534 	for (rv = 1; len--; ++buf) {
535 		if (BYTE_IS_BINARY(*buf))
536 			return 1;
537 		if (BYTE_IS_TEXT(*buf))
538 			rv = 0;
539 	}
540 
541 	return rv;
542 }
543 
544 /*
545  * Extract to a file descriptor
546  */
547 static int
extract2fd(struct archive * a,char * pathname,int fd)548 extract2fd(struct archive *a, char *pathname, int fd)
549 {
550 	int cr, text, warn;
551 	ssize_t len;
552 	unsigned char *p, *q, *end;
553 
554 	text = a_opt;
555 	warn = 0;
556 	cr = 0;
557 
558 	/* loop over file contents and write to fd */
559 	for (int n = 0; ; n++) {
560 		if (fd != STDOUT_FILENO)
561 			if (tty && (n % 4) == 0)
562 				info(" %c\b\b", spinner[(n / 4) % sizeof spinner]);
563 
564 		len = archive_read_data(a, buffer, sizeof buffer);
565 
566 		if (len < 0)
567 			ac(len);
568 
569 		/* left over CR from previous buffer */
570 		if (a_opt && cr) {
571 			if (len == 0 || buffer[0] != '\n')
572 				if (write(fd, "\r", 1) != 1)
573 					error("write('%s')", pathname);
574 			cr = 0;
575 		}
576 
577 		/* EOF */
578 		if (len == 0)
579 			break;
580 		end = buffer + len;
581 
582 		/*
583 		 * Detect whether this is a text file.  The correct way to
584 		 * do this is to check the least significant bit of the
585 		 * "internal file attributes" field of the corresponding
586 		 * file header in the central directory, but libarchive
587 		 * does not provide access to this field, so we have to
588 		 * guess by looking for non-ASCII characters in the
589 		 * buffer.  Hopefully we won't guess wrong.  If we do
590 		 * guess wrong, we print a warning message later.
591 		 */
592 		if (a_opt && n == 0) {
593 			if (check_binary(buffer, len))
594 				text = 0;
595 		}
596 
597 		/* simple case */
598 		if (!a_opt || !text) {
599 			if (write(fd, buffer, len) != len)
600 				error("write('%s')", pathname);
601 			continue;
602 		}
603 
604 		/* hard case: convert \r\n to \n (sigh...) */
605 		for (p = buffer; p < end; p = q + 1) {
606 			for (q = p; q < end; q++) {
607 				if (!warn && BYTE_IS_BINARY(*q)) {
608 					warningx("%s may be corrupted due"
609 					    " to weak text file detection"
610 					    " heuristic", pathname);
611 					warn = 1;
612 				}
613 				if (q[0] != '\r')
614 					continue;
615 				if (&q[1] == end) {
616 					cr = 1;
617 					break;
618 				}
619 				if (q[1] == '\n')
620 					break;
621 			}
622 			if (write(fd, p, q - p) != q - p)
623 				error("write('%s')", pathname);
624 		}
625 	}
626 
627 	return text;
628 }
629 
630 /*
631  * Extract a regular file.
632  */
633 static void
extract_file(struct archive * a,struct archive_entry * e,char ** path)634 extract_file(struct archive *a, struct archive_entry *e, char **path)
635 {
636 	int mode;
637 	struct timespec mtime;
638 	struct stat sb;
639 	int fd, check, text;
640 	const char *linkname;
641 #if defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMENS)
642 	struct timespec ts[2];
643 #endif
644 #if ((!defined(HAVE_UTIMENSAT) && defined(HAVE_LUTIMES)) || \
645     (!defined(HAVE_FUTIMENS) && defined(HAVE_FUTIMES)))
646 	struct timeval times[2];
647 #endif
648 
649 	mode = archive_entry_mode(e) & 0777;
650 	if (mode == 0)
651 		mode = 0644;
652 	mtime.tv_sec = archive_entry_mtime(e);
653 	mtime.tv_nsec = archive_entry_mtime_nsec(e);
654 
655 	/* look for existing file of same name */
656 recheck:
657 	if (lstat(*path, &sb) == 0) {
658 		if (u_opt || f_opt) {
659 			/* check if up-to-date */
660 			if (S_ISREG(sb.st_mode) && (
661 #if HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC
662 			    sb.st_mtimespec.tv_sec > mtime.tv_sec ||
663 			    (sb.st_mtimespec.tv_sec == mtime.tv_sec &&
664 			    sb.st_mtimespec.tv_nsec >= mtime.tv_nsec)
665 #elif HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC
666 			    sb.st_mtim.tv_sec > mtime.tv_sec ||
667 			    (sb.st_mtim.tv_sec == mtime.tv_sec &&
668 			    sb.st_mtim.tv_nsec >= mtime.tv_nsec)
669 #elif HAVE_STRUCT_STAT_ST_MTIME_N
670 			    sb.st_mtime > mtime.tv_sec ||
671 			    (sb.st_mtime == mtime.tv_sec &&
672 			    sb.st_mtime_n >= mtime.tv_nsec)
673 #elif HAVE_STRUCT_STAT_ST_MTIME_USEC
674 			    sb.st_mtime > mtime.tv_sec ||
675 			    (sb.st_mtime == mtime.tv_sec &&
676 			    sb.st_mtime_usec >= mtime.tv_nsec / 1000)
677 #else
678 			    sb.st_mtime > mtime.tv_sec
679 #endif
680 			    ))
681 				return;
682 			system_unlink(*path);
683 		} else if (o_opt) {
684 			/* overwrite */
685 			system_unlink(*path);
686 		} else if (n_opt) {
687 			/* do not overwrite */
688 			return;
689 		} else {
690 			check = handle_existing_file(path);
691 			if (check == 0)
692 				goto recheck;
693 			if (check == -1)
694 				return; /* do not overwrite */
695 		}
696 	} else {
697 		if (f_opt)
698 			return;
699 	}
700 
701 #if defined(HAVE_UTIMENSAT) || defined(HAVE_FUTIMENS)
702 	ts[0].tv_sec = 0;
703 	ts[0].tv_nsec = UTIME_NOW;
704 	ts[1] = mtime;
705 #endif
706 #if ((!defined(HAVE_UTIMENSAT) && defined(HAVE_LUTIMES)) || \
707     (!defined(HAVE_FUTIMENS) && defined(HAVE_FUTIMES)))
708 	times[0].tv_sec = 0;
709 	times[0].tv_usec = -1;
710 	times[1].tv_sec = mtime.tv_sec;
711 	times[1].tv_usec = mtime.tv_nsec / 1000;
712 #endif
713 
714 	/* process symlinks */
715 	linkname = archive_entry_symlink(e);
716 	if (linkname != NULL) {
717 		if (symlink(linkname, *path) != 0)
718 			error("symlink('%s')", *path);
719 		info(" extracting: %s -> %s\n", *path, linkname);
720 #ifdef HAVE_LCHMOD
721 		if (lchmod(*path, (mode_t)mode) != 0)
722 			warning("Cannot set mode for '%s'", *path);
723 #endif
724 		/* set access and modification time */
725 #if defined(HAVE_UTIMENSAT)
726 		if (utimensat(AT_FDCWD, *path, ts, AT_SYMLINK_NOFOLLOW) != 0)
727 			warning("utimensat('%s')", *path);
728 #elif defined(HAVE_LUTIMES)
729 		gettimeofday(&times[0], NULL);
730 		if (lutimes(*path, times) != 0)
731 			warning("lutimes('%s')", *path);
732 #endif
733 		return;
734 	}
735 
736 	if ((fd = open(*path, O_RDWR|O_CREAT|O_TRUNC, mode)) < 0)
737 		error("open('%s')", *path);
738 
739 	info(" extracting: %s", *path);
740 
741 	text = extract2fd(a, *path, fd);
742 
743 	if (tty)
744 		info("  \b\b");
745 	if (text)
746 		info(" (text)");
747 	info("\n");
748 
749 	/* set access and modification time */
750 #if defined(HAVE_FUTIMENS)
751 	if (futimens(fd, ts) != 0)
752 		error("futimens('%s')", *path);
753 #elif defined(HAVE_FUTIMES)
754 	gettimeofday(&times[0], NULL);
755 	if (futimes(fd, times) != 0)
756 		error("futimes('%s')", *path);
757 #endif
758 	if (close(fd) != 0)
759 		error("close('%s')", *path);
760 }
761 
762 static int
pathname_is_insecure(const char * pathname)763 pathname_is_insecure(const char* pathname)
764 {
765 	size_t len = strlen(pathname);
766 	return (pathname[0] == '/' ||
767 	    strcmp(pathname, "..") == 0 ||
768 	    strncmp(pathname, "../", 3) == 0 ||
769 	    strstr(pathname, "/../") != NULL ||
770 	    (len >= 3 && strcmp(pathname + len - 3, "/..") == 0));
771 }
772 
773 /*
774  * Extract a zipfile entry: first perform some sanity checks to ensure
775  * that it is either a directory or a regular file and that the path is
776  * not absolute and does not try to break out of the current directory;
777  * then call either extract_dir() or extract_file() as appropriate.
778  *
779  * This is complicated a bit by the various ways in which we need to
780  * manipulate the path name.  Case conversion (if requested by the -L
781  * option) happens first, but the include / exclude patterns are applied
782  * to the full converted path name, before the directory part of the path
783  * is removed in accordance with the -j option.  Sanity checks are
784  * intentionally done earlier than they need to be, so the user will get a
785  * warning about insecure paths even for files or directories which
786  * wouldn't be extracted anyway.
787  */
788 static void
extract(struct archive * a,struct archive_entry * e)789 extract(struct archive *a, struct archive_entry *e)
790 {
791 	char *pathname, *realpathname;
792 	const char *linktarget;
793 	mode_t filetype;
794 	char *p, *q;
795 
796 	if ((pathname = pathdup(archive_entry_pathname(e))) == NULL) {
797 		warningx("skipping empty or unreadable filename entry");
798 		ac(archive_read_data_skip(a));
799 		return;
800 	}
801 	filetype = archive_entry_filetype(e);
802 
803 	/* sanity checks */
804 	if (pathname_is_insecure(pathname)) {
805 		warningx("skipping insecure entry '%s'", pathname);
806 		ac(archive_read_data_skip(a));
807 		free(pathname);
808 		return;
809 	}
810 
811 	if (S_ISLNK(filetype) &&
812 	    ((linktarget = archive_entry_symlink(e)) != NULL) &&
813 	    pathname_is_insecure(linktarget)) {
814 		warningx("skipping insecure symlink '%s' to '%s'", pathname, linktarget);
815 		ac(archive_read_data_skip(a));
816 		free(pathname);
817 		return;
818 	}
819 
820 	/* I don't think this can happen in a zipfile.. */
821 	if (!S_ISDIR(filetype) && !S_ISREG(filetype) && !S_ISLNK(filetype)) {
822 		warningx("skipping non-regular entry '%s'", pathname);
823 		ac(archive_read_data_skip(a));
824 		free(pathname);
825 		return;
826 	}
827 
828 	/* skip directories in -j case */
829 	if (S_ISDIR(filetype) && j_opt) {
830 		ac(archive_read_data_skip(a));
831 		free(pathname);
832 		return;
833 	}
834 
835 	/* apply include / exclude patterns */
836 	if (!accept_pathname(pathname)) {
837 		ac(archive_read_data_skip(a));
838 		free(pathname);
839 		return;
840 	}
841 
842 	/* apply -j and -d */
843 	if (j_opt) {
844 		for (p = q = pathname; *p; ++p)
845 			if (*p == '/')
846 				q = p + 1;
847 		realpathname = pathcat(d_arg, q);
848 	} else {
849 		realpathname = pathcat(d_arg, pathname);
850 	}
851 
852 	/* ensure that parent directory exists */
853 	make_parent(realpathname);
854 
855 	if (S_ISDIR(filetype))
856 		extract_dir(a, e, realpathname);
857 	else
858 		extract_file(a, e, &realpathname);
859 
860 	free(realpathname);
861 	free(pathname);
862 }
863 
864 static void
extract_stdout(struct archive * a,struct archive_entry * e)865 extract_stdout(struct archive *a, struct archive_entry *e)
866 {
867 	char *pathname;
868 	mode_t filetype;
869 
870 	if ((pathname = pathdup(archive_entry_pathname(e))) == NULL) {
871 		warningx("skipping empty or unreadable filename entry");
872 		ac(archive_read_data_skip(a));
873 		return;
874 	}
875 	filetype = archive_entry_filetype(e);
876 
877 	/* I don't think this can happen in a zipfile.. */
878 	if (!S_ISDIR(filetype) && !S_ISREG(filetype) && !S_ISLNK(filetype)) {
879 		warningx("skipping non-regular entry '%s'", pathname);
880 		ac(archive_read_data_skip(a));
881 		free(pathname);
882 		return;
883 	}
884 
885 	/* skip directories in -j case */
886 	if (S_ISDIR(filetype)) {
887 		ac(archive_read_data_skip(a));
888 		free(pathname);
889 		return;
890 	}
891 
892 	/* apply include / exclude patterns */
893 	if (!accept_pathname(pathname)) {
894 		ac(archive_read_data_skip(a));
895 		free(pathname);
896 		return;
897 	}
898 
899 	if (c_opt)
900 		info("x %s\n", pathname);
901 
902 	(void)extract2fd(a, pathname, STDOUT_FILENO);
903 
904 	free(pathname);
905 }
906 
907 /*
908  * Print the name of an entry to stdout.
909  */
910 static void
list(struct archive * a,struct archive_entry * e)911 list(struct archive *a, struct archive_entry *e)
912 {
913 	char buf[20];
914 	time_t mtime;
915 	struct tm *tm;
916 	const char *pathname;
917 
918 	mtime = archive_entry_mtime(e);
919 	tm = localtime(&mtime);
920 	if (*y_str)
921 		strftime(buf, sizeof(buf), "%m-%d-%Y %H:%M", tm);
922 	else
923 		strftime(buf, sizeof(buf), "%m-%d-%y %H:%M", tm);
924 
925 	pathname = archive_entry_pathname(e);
926 	if (!pathname)
927 		pathname = "";
928 	if (!zipinfo_mode) {
929 		if (v_opt == 1) {
930 			printf(" %8ju  %s   %s\n",
931 			    (uintmax_t)archive_entry_size(e),
932 			    buf, pathname);
933 		} else if (v_opt == 2) {
934 			printf("%8ju  Stored  %7ju   0%%  %s  %08x  %s\n",
935 			    (uintmax_t)archive_entry_size(e),
936 			    (uintmax_t)archive_entry_size(e),
937 			    buf,
938 			    0U,
939 			    pathname);
940 		}
941 	} else {
942 		if (Z1_opt)
943 			printf("%s\n", pathname);
944 	}
945 	ac(archive_read_data_skip(a));
946 }
947 
948 /*
949  * Extract to memory to check CRC
950  */
951 static int
test(struct archive * a,struct archive_entry * e)952 test(struct archive *a, struct archive_entry *e)
953 {
954 	ssize_t len;
955 	int error_count;
956 
957 	error_count = 0;
958 	if (S_ISDIR(archive_entry_filetype(e)))
959 		return 0;
960 
961 	info("    testing: %s\t", archive_entry_pathname(e));
962 	while ((len = archive_read_data(a, buffer, sizeof buffer)) > 0)
963 		/* nothing */;
964 	if (len < 0) {
965 		info(" %s\n", archive_error_string(a));
966 		++error_count;
967 	} else {
968 		info(" OK\n");
969 	}
970 
971 	/* shouldn't be necessary, but it doesn't hurt */
972 	ac(archive_read_data_skip(a));
973 
974 	return error_count;
975 }
976 
977 /*
978  * Callback function for reading passphrase.
979  * Originally from cpio.c and passphrase.c, libarchive.
980  */
981 #define PPBUFF_SIZE 1024
982 static const char *
passphrase_callback(struct archive * a,void * _client_data)983 passphrase_callback(struct archive *a, void *_client_data)
984 {
985 	char *p;
986 
987 	(void)a; /* UNUSED */
988 	(void)_client_data; /* UNUSED */
989 
990 	if (passphrase_buf == NULL) {
991 		passphrase_buf = malloc(PPBUFF_SIZE);
992 		if (passphrase_buf == NULL) {
993 			errno = ENOMEM;
994 			error("malloc()");
995 		}
996 	}
997 
998 	p = lafe_readpassphrase("\nEnter password: ", passphrase_buf,
999 		PPBUFF_SIZE);
1000 
1001 	if (p == NULL && errno != EINTR)
1002 		error("Error reading password");
1003 
1004 	return p;
1005 }
1006 
1007 /*
1008  * Main loop: open the zipfile, iterate over its contents and decide what
1009  * to do with each entry.
1010  */
1011 static void
unzip(const char * fn)1012 unzip(const char *fn)
1013 {
1014 	struct archive *a;
1015 	struct archive_entry *e;
1016 	int ret;
1017 	uintmax_t total_size, file_count, error_count;
1018 
1019 	if ((a = archive_read_new()) == NULL)
1020 		error("archive_read_new failed");
1021 
1022 	ac(archive_read_support_format_zip(a));
1023 
1024 	if (O_arg)
1025 		ac(archive_read_set_format_option(a, "zip", "hdrcharset", O_arg));
1026 
1027 	if (P_arg)
1028 		archive_read_add_passphrase(a, P_arg);
1029 	else
1030 		archive_read_set_passphrase_callback(a, NULL,
1031 			&passphrase_callback);
1032 
1033 	ac(archive_read_open_filename(a, fn, 8192));
1034 
1035 	if (!zipinfo_mode) {
1036 		if (!p_opt && !q_opt)
1037 			printf("Archive:  %s\n", fn);
1038 		if (v_opt == 1) {
1039 			printf("  Length     %sDate   Time    Name\n", y_str);
1040 			printf(" --------    %s----   ----    ----\n", y_str);
1041 		} else if (v_opt == 2) {
1042 			printf(" Length   Method    Size  Ratio   %sDate   Time   CRC-32    Name\n", y_str);
1043 			printf("--------  ------  ------- -----   %s----   ----   ------    ----\n", y_str);
1044 		}
1045 	}
1046 
1047 	total_size = 0;
1048 	file_count = 0;
1049 	error_count = 0;
1050 	for (;;) {
1051 		ret = archive_read_next_header(a, &e);
1052 		if (ret == ARCHIVE_EOF)
1053 			break;
1054 		ac(ret);
1055 		if (!zipinfo_mode) {
1056 			if (t_opt)
1057 				error_count += test(a, e);
1058 			else if (v_opt)
1059 				list(a, e);
1060 			else if (p_opt || c_opt)
1061 				extract_stdout(a, e);
1062 			else
1063 				extract(a, e);
1064 		} else {
1065 			if (Z1_opt)
1066 				list(a, e);
1067 		}
1068 
1069 		total_size += archive_entry_size(e);
1070 		++file_count;
1071 	}
1072 
1073 	if (zipinfo_mode) {
1074 		if (v_opt == 1) {
1075 			printf(" --------                   %s-------\n", y_str);
1076 			printf(" %8ju                   %s%ju file%s\n",
1077 			    total_size, y_str, file_count, file_count != 1 ? "s" : "");
1078 		} else if (v_opt == 2) {
1079 			printf("--------          -------  ---                            %s-------\n", y_str);
1080 			printf("%8ju          %7ju   0%%                            %s%ju file%s\n",
1081 			    total_size, total_size, y_str, file_count,
1082 			    file_count != 1 ? "s" : "");
1083 		}
1084 	}
1085 
1086 	ac(archive_read_free(a));
1087 
1088 	if (passphrase_buf != NULL) {
1089 		memset(passphrase_buf, 0, PPBUFF_SIZE);
1090 		free(passphrase_buf);
1091 	}
1092 
1093 	if (t_opt) {
1094 		if (error_count > 0) {
1095 			errorx("%ju checksum error(s) found.", error_count);
1096 		}
1097 		else {
1098 			printf("No errors detected in compressed data of %s.\n",
1099 			       fn);
1100 		}
1101 	}
1102 }
1103 
1104 static void
usage(void)1105 usage(void)
1106 {
1107 
1108 	fprintf(stderr,
1109 "Usage: unzip [-aCcfjLlnopqtuvyZ1] [{-O|-I} encoding] [-d dir] [-x pattern] [-P password] zipfile\n"
1110 "             [member ...]\n");
1111 	exit(EXIT_FAILURE);
1112 }
1113 
1114 static void
version(void)1115 version(void)
1116 {
1117         printf("bsdunzip %s - %s \n",
1118             BSDUNZIP_VERSION_STRING,
1119             archive_version_details());
1120         exit(0);
1121 }
1122 
1123 static int
getopts(int argc,char * argv[])1124 getopts(int argc, char *argv[])
1125 {
1126 	struct bsdunzip *bsdunzip, bsdunzip_storage;
1127 	int opt;
1128 	bsdunzip_optind = 1;
1129 
1130 	bsdunzip = &bsdunzip_storage;
1131 	memset(bsdunzip, 0, sizeof(*bsdunzip));
1132 
1133         bsdunzip->argv = argv;
1134         bsdunzip->argc = argc;
1135 
1136 	while ((opt = bsdunzip_getopt(bsdunzip)) != -1) {
1137 		unzip_exclude_mode = 0;
1138 		switch (opt) {
1139 		case 'a':
1140 			a_opt = 1;
1141 			break;
1142 		case 'C':
1143 			C_opt = 1;
1144 			break;
1145 		case 'c':
1146 			c_opt = 1;
1147 			break;
1148 		case 'd':
1149 			d_arg = bsdunzip->argument;
1150 			break;
1151 		case 'f':
1152 			f_opt = 1;
1153 			break;
1154 		case 'I':
1155 		case 'O':
1156 			O_arg = bsdunzip->argument;
1157 			break;
1158 		case 'j':
1159 			j_opt = 1;
1160 			break;
1161 		case 'L':
1162 			L_opt = 1;
1163 			break;
1164 		case 'l':
1165 			if (v_opt == 0)
1166 				v_opt = 1;
1167 			break;
1168 		case 'n':
1169 			n_opt = 1;
1170 			break;
1171 		case 'o':
1172 			o_opt = 1;
1173 			q_opt = 1;
1174 			break;
1175 		case 'p':
1176 			p_opt = 1;
1177 			break;
1178 		case 'P':
1179 			P_arg = bsdunzip->argument;
1180 			break;
1181 		case 'q':
1182 			q_opt = 1;
1183 			break;
1184 		case 't':
1185 			t_opt = 1;
1186 			break;
1187 		case 'u':
1188 			u_opt = 1;
1189 			break;
1190 		case 'v':
1191 			v_opt = 2;
1192 			break;
1193 		case 'x':
1194 			add_pattern(&exclude, bsdunzip->argument);
1195 			unzip_exclude_mode = 1;
1196 			break;
1197 		case 'y':
1198 			y_str = "  ";
1199 			break;
1200 		case 'Z':
1201 			zipinfo_mode = 1;
1202 			if (bsdunzip->argument != NULL &&
1203 			    strcmp(bsdunzip->argument, "1") == 0) {
1204 				Z1_opt = 1;
1205 			}
1206 			break;
1207 		case OPTION_VERSION:
1208 			version_opt = 1;
1209 			break;
1210 		case OPTION_NONE:
1211 			break;
1212 		default:
1213 			usage();
1214 		}
1215 		if (opt == OPTION_NONE)
1216 			break;
1217 	}
1218 	return (bsdunzip_optind);
1219 }
1220 
1221 int
main(int argc,char * argv[])1222 main(int argc, char *argv[])
1223 {
1224 	const char *zipfile;
1225 	int nopts;
1226 
1227 #if defined(HAVE_SIGACTION) && defined(SIGCHLD)
1228 	{ /* Do not ignore SIGCHLD. */
1229 		struct sigaction sa;
1230 		sa.sa_handler = SIG_DFL;
1231 		sigemptyset(&sa.sa_mask);
1232 		sa.sa_flags = 0;
1233 		sigaction(SIGCHLD, &sa, NULL);
1234 	}
1235 #endif
1236 
1237 	lafe_setprogname(*argv, "bsdunzip");
1238 
1239 #if HAVE_SETLOCALE
1240 	if (setlocale(LC_ALL, "") == NULL)
1241 		lafe_warnc(0, "Failed to set default locale");
1242 #endif
1243 
1244 	if (isatty(STDOUT_FILENO))
1245 		tty = 1;
1246 
1247 	if (getenv("UNZIP_DEBUG") != NULL)
1248 		unzip_debug = 1;
1249 	for (int i = 0; i < argc; ++i)
1250 		debug("%s%c", argv[i], (i < argc - 1) ? ' ' : '\n');
1251 
1252 #ifdef __GLIBC__
1253 	/* Prevent GNU getopt(3) from rearranging options. */
1254 	setenv("POSIXLY_CORRECT", "", 1);
1255 #endif
1256 	/*
1257 	 * Info-ZIP's unzip(1) expects certain options to come before the
1258 	 * zipfile name, and others to come after - though it does not
1259 	 * enforce this.  For simplicity, we accept *all* options both
1260 	 * before and after the zipfile name.
1261 	 */
1262 	nopts = getopts(argc, argv);
1263 
1264 	if (version_opt == 1)
1265 		version();
1266 
1267 	/*
1268 	 * When more of the zipinfo mode options are implemented, this
1269 	 * will need to change.
1270 	 */
1271 	if (zipinfo_mode && !Z1_opt) {
1272 		printf("Zipinfo mode needs additional options\n");
1273 		exit(EXIT_FAILURE);
1274 	}
1275 
1276 	if (argc <= nopts)
1277 		usage();
1278 	zipfile = argv[nopts++];
1279 
1280 	if (strcmp(zipfile, "-") == 0)
1281 		zipfile = NULL; /* STDIN */
1282 
1283 	unzip_exclude_mode = 0;
1284 
1285 	while (nopts < argc && *argv[nopts] != '-')
1286 		add_pattern(&include, argv[nopts++]);
1287 
1288 	nopts--; /* fake argv[0] */
1289 	nopts += getopts(argc - nopts, argv + nopts);
1290 
1291 	/*
1292 	 * For compatibility with Info-ZIP's unzip(1) we need to treat
1293 	 * non-option arguments following an -x after the zipfile as
1294 	 * exclude list members.
1295 	 */
1296 	if (unzip_exclude_mode) {
1297 		while (nopts < argc && *argv[nopts] != '-')
1298 			add_pattern(&exclude, argv[nopts++]);
1299 		nopts--; /* fake argv[0] */
1300 		nopts += getopts(argc - nopts, argv + nopts);
1301 	}
1302 
1303 	/* There may be residual arguments if we encountered -- */
1304 	while (nopts < argc)
1305 		add_pattern(&include, argv[nopts++]);
1306 
1307 	if (n_opt + o_opt + u_opt > 1)
1308 		errorx("-n, -o and -u are contradictory");
1309 
1310 	unzip(zipfile);
1311 
1312 	exit(EXIT_SUCCESS);
1313 }
1314