unzip.c revision 280117
138889Sjdp/*-
238889Sjdp * Copyright (c) 2009 Joerg Sonnenberger <joerg@NetBSD.org>
3218822Sdim * Copyright (c) 2007-2008 Dag-Erling Sm��rgrav
4218822Sdim * All rights reserved.
5218822Sdim *
6130561Sobrien * Redistribution and use in source and binary forms, with or without
7130561Sobrien * modification, are permitted provided that the following conditions
8130561Sobrien * are met:
938889Sjdp * 1. Redistributions of source code must retain the above copyright
10130561Sobrien *    notice, this list of conditions and the following disclaimer
1138889Sjdp *    in this position and unchanged.
12130561Sobrien * 2. Redistributions in binary form must reproduce the above copyright
13130561Sobrien *    notice, this list of conditions and the following disclaimer in the
14130561Sobrien *    documentation and/or other materials provided with the distribution.
15130561Sobrien *
16130561Sobrien * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17130561Sobrien * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18130561Sobrien * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19130561Sobrien * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20130561Sobrien * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21130561Sobrien * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22130561Sobrien * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23130561Sobrien * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24130561Sobrien * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25130561Sobrien * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
26130561Sobrien * SUCH DAMAGE.
27130561Sobrien *
28130561Sobrien * $FreeBSD: head/usr.bin/unzip/unzip.c 280117 2015-03-15 21:29:20Z jilles $
29130561Sobrien *
30130561Sobrien * This file would be much shorter if we didn't care about command-line
31130561Sobrien * compatibility with Info-ZIP's UnZip, which requires us to duplicate
32130561Sobrien * parts of libarchive in order to gain more detailed control of its
33130561Sobrien * behaviour for the purpose of implementing the -n, -o, -L and -a
34130561Sobrien * options.
35130561Sobrien */
36130561Sobrien
3738889Sjdp#include <sys/queue.h>
3838889Sjdp#include <sys/stat.h>
3938889Sjdp
4038889Sjdp#include <ctype.h>
4138889Sjdp#include <errno.h>
4238889Sjdp#include <fcntl.h>
4338889Sjdp#include <fnmatch.h>
4438889Sjdp#include <stdarg.h>
4538889Sjdp#include <stdio.h>
4638889Sjdp#include <stdlib.h>
4738889Sjdp#include <string.h>
4838889Sjdp#include <unistd.h>
4938889Sjdp
5038889Sjdp#include <archive.h>
5138889Sjdp#include <archive_entry.h>
5238889Sjdp
5338889Sjdp/* command-line options */
5438889Sjdpstatic int		 a_opt;		/* convert EOL */
5538889Sjdpstatic int		 C_opt;		/* match case-insensitively */
5638889Sjdpstatic int		 c_opt;		/* extract to stdout */
5738889Sjdpstatic const char	*d_arg;		/* directory */
5838889Sjdpstatic int		 f_opt;		/* update existing files only */
5938889Sjdpstatic int		 j_opt;		/* junk directories */
6038889Sjdpstatic int		 L_opt;		/* lowercase names */
6138889Sjdpstatic int		 n_opt;		/* never overwrite */
62218822Sdimstatic int		 o_opt;		/* always overwrite */
63218822Sdimstatic int		 p_opt;		/* extract to stdout, quiet */
64218822Sdimstatic int		 q_opt;		/* quiet */
6538889Sjdpstatic int		 t_opt;		/* test */
6638889Sjdpstatic int		 u_opt;		/* update */
67218822Sdimstatic int		 v_opt;		/* verbose/list */
68218822Sdimstatic int		 Z1_opt;	/* zipinfo mode list files only */
69218822Sdim
70218822Sdim/* debug flag */
71218822Sdimstatic int		 unzip_debug;
7238889Sjdp
73218822Sdim/* zipinfo mode */
74218822Sdimstatic int		 zipinfo_mode;
75218822Sdim
76218822Sdim/* running on tty? */
7738889Sjdpstatic int		 tty;
78218822Sdim
79218822Sdim/* convenience macro */
80218822Sdim/* XXX should differentiate between ARCHIVE_{WARN,FAIL,RETRY} */
8138889Sjdp#define ac(call)						\
82218822Sdim	do {							\
83218822Sdim		int acret = (call);				\
84218822Sdim		if (acret != ARCHIVE_OK)			\
85218822Sdim			errorx("%s", archive_error_string(a));	\
86218822Sdim	} while (0)
87218822Sdim
88218822Sdim/*
89218822Sdim * Indicates that last info() did not end with EOL.  This helps error() et
90218822Sdim * al. avoid printing an error message on the same line as an incomplete
91218822Sdim * informational message.
92218822Sdim */
9338889Sjdpstatic int noeol;
94218822Sdim
95218822Sdim/* fatal error message + errno */
96218822Sdimstatic void
9738889Sjdperror(const char *fmt, ...)
98218822Sdim{
99218822Sdim	va_list ap;
100218822Sdim
101218822Sdim	if (noeol)
10238889Sjdp		fprintf(stdout, "\n");
103218822Sdim	fflush(stdout);
104218822Sdim	fprintf(stderr, "unzip: ");
105218822Sdim	va_start(ap, fmt);
10638889Sjdp	vfprintf(stderr, fmt, ap);
107218822Sdim	va_end(ap);
108218822Sdim	fprintf(stderr, ": %s\n", strerror(errno));
109218822Sdim	exit(1);
110218822Sdim}
11138889Sjdp
112218822Sdim/* fatal error message, no errno */
11338889Sjdpstatic void
114218822Sdimerrorx(const char *fmt, ...)
115218822Sdim{
116218822Sdim	va_list ap;
117218822Sdim
11838889Sjdp	if (noeol)
119218822Sdim		fprintf(stdout, "\n");
120218822Sdim	fflush(stdout);
121218822Sdim	fprintf(stderr, "unzip: ");
122218822Sdim	va_start(ap, fmt);
12338889Sjdp	vfprintf(stderr, fmt, ap);
124218822Sdim	va_end(ap);
125218822Sdim	fprintf(stderr, "\n");
126218822Sdim	exit(1);
127130561Sobrien}
128218822Sdim
129218822Sdim#if 0
130218822Sdim/* non-fatal error message + errno */
131218822Sdimstatic void
13238889Sjdpwarning(const char *fmt, ...)
133218822Sdim{
134218822Sdim	va_list ap;
135218822Sdim
13638889Sjdp	if (noeol)
137218822Sdim		fprintf(stdout, "\n");
138130561Sobrien	fflush(stdout);
139218822Sdim	fprintf(stderr, "unzip: ");
140218822Sdim	va_start(ap, fmt);
141218822Sdim	vfprintf(stderr, fmt, ap);
142218822Sdim	va_end(ap);
143218822Sdim	fprintf(stderr, ": %s\n", strerror(errno));
144218822Sdim}
145218822Sdim#endif
146218822Sdim
147218822Sdim/* non-fatal error message, no errno */
148218822Sdimstatic void
149218822Sdimwarningx(const char *fmt, ...)
150218822Sdim{
151218822Sdim	va_list ap;
152218822Sdim
153218822Sdim	if (noeol)
154218822Sdim		fprintf(stdout, "\n");
155218822Sdim	fflush(stdout);
15638889Sjdp	fprintf(stderr, "unzip: ");
157218822Sdim	va_start(ap, fmt);
158218822Sdim	vfprintf(stderr, fmt, ap);
159218822Sdim	va_end(ap);
160218822Sdim	fprintf(stderr, "\n");
161218822Sdim}
162218822Sdim
163218822Sdim/* informational message (if not -q) */
164218822Sdimstatic void
16538889Sjdpinfo(const char *fmt, ...)
16638889Sjdp{
167218822Sdim	va_list ap;
168218822Sdim
169218822Sdim	if (q_opt && !unzip_debug)
170218822Sdim		return;
171218822Sdim	va_start(ap, fmt);
172218822Sdim	vfprintf(stdout, fmt, ap);
17338889Sjdp	va_end(ap);
174218822Sdim	fflush(stdout);
175218822Sdim
176218822Sdim	if (*fmt == '\0')
17738889Sjdp		noeol = 1;
178218822Sdim	else
179218822Sdim		noeol = fmt[strlen(fmt) - 1] != '\n';
180218822Sdim}
181218822Sdim
182218822Sdim/* debug message (if unzip_debug) */
183218822Sdimstatic void
184218822Sdimdebug(const char *fmt, ...)
185218822Sdim{
186218822Sdim	va_list ap;
187218822Sdim
188218822Sdim	if (!unzip_debug)
189218822Sdim		return;
190218822Sdim	va_start(ap, fmt);
191218822Sdim	vfprintf(stderr, fmt, ap);
19238889Sjdp	va_end(ap);
193218822Sdim	fflush(stderr);
194218822Sdim
195218822Sdim	if (*fmt == '\0')
196218822Sdim		noeol = 1;
19738889Sjdp	else
198218822Sdim		noeol = fmt[strlen(fmt) - 1] != '\n';
199218822Sdim}
200218822Sdim
201218822Sdim/* duplicate a path name, possibly converting to lower case */
202218822Sdimstatic char *
20338889Sjdppathdup(const char *path)
204218822Sdim{
205218822Sdim	char *str;
206218822Sdim	size_t i, len;
207218822Sdim
208218822Sdim	len = strlen(path);
209218822Sdim	while (len && path[len - 1] == '/')
210218822Sdim		len--;
211218822Sdim	if ((str = malloc(len + 1)) == NULL) {
212218822Sdim		errno = ENOMEM;
213218822Sdim		error("malloc()");
21438889Sjdp	}
215218822Sdim	if (L_opt) {
216218822Sdim		for (i = 0; i < len; ++i)
21738889Sjdp			str[i] = tolower((unsigned char)path[i]);
218218822Sdim	} else {
21938889Sjdp		memcpy(str, path, len);
220218822Sdim	}
221218822Sdim	str[len] = '\0';
222218822Sdim
223218822Sdim	return (str);
224218822Sdim}
22538889Sjdp
226218822Sdim/* concatenate two path names */
227218822Sdimstatic char *
228218822Sdimpathcat(const char *prefix, const char *path)
229218822Sdim{
230218822Sdim	char *str;
231218822Sdim	size_t prelen, len;
23238889Sjdp
233218822Sdim	prelen = prefix ? strlen(prefix) + 1 : 0;
23438889Sjdp	len = strlen(path) + 1;
235218822Sdim	if ((str = malloc(prelen + len)) == NULL) {
236218822Sdim		errno = ENOMEM;
237218822Sdim		error("malloc()");
238218822Sdim	}
239218822Sdim	if (prefix) {
240218822Sdim		memcpy(str, prefix, prelen);	/* includes zero */
241218822Sdim		str[prelen - 1] = '/';		/* splat zero */
242218822Sdim	}
243218822Sdim	memcpy(str + prelen, path, len);	/* includes zero */
244218822Sdim
245218822Sdim	return (str);
246218822Sdim}
247218822Sdim
24838889Sjdp/*
249218822Sdim * Pattern lists for include / exclude processing
250218822Sdim */
251218822Sdimstruct pattern {
252218822Sdim	STAILQ_ENTRY(pattern) link;
253218822Sdim	char pattern[];
254218822Sdim};
25538889Sjdp
256218822SdimSTAILQ_HEAD(pattern_list, pattern);
257218822Sdimstatic struct pattern_list include = STAILQ_HEAD_INITIALIZER(include);
25838889Sjdpstatic struct pattern_list exclude = STAILQ_HEAD_INITIALIZER(exclude);
259218822Sdim
260218822Sdim/*
261218822Sdim * Add an entry to a pattern list
26238889Sjdp */
263218822Sdimstatic void
264218822Sdimadd_pattern(struct pattern_list *list, const char *pattern)
265218822Sdim{
26638889Sjdp	struct pattern *entry;
267218822Sdim	size_t len;
268218822Sdim
269130561Sobrien	debug("adding pattern '%s'\n", pattern);
270218822Sdim	len = strlen(pattern);
271218822Sdim	if ((entry = malloc(sizeof *entry + len + 1)) == NULL) {
272218822Sdim		errno = ENOMEM;
273218822Sdim		error("malloc()");
274218822Sdim	}
275218822Sdim	memcpy(entry->pattern, pattern, len + 1);
276218822Sdim	STAILQ_INSERT_TAIL(list, entry, link);
277218822Sdim}
278218822Sdim
279218822Sdim/*
280130561Sobrien * Match a string against a list of patterns
281218822Sdim */
282218822Sdimstatic int
283218822Sdimmatch_pattern(struct pattern_list *list, const char *str)
284218822Sdim{
285218822Sdim	struct pattern *entry;
286218822Sdim
28738889Sjdp	STAILQ_FOREACH(entry, list, link) {
288218822Sdim		if (fnmatch(entry->pattern, str, C_opt ? FNM_CASEFOLD : 0) == 0)
289218822Sdim			return (1);
290218822Sdim	}
291218822Sdim	return (0);
292218822Sdim}
293218822Sdim
294218822Sdim/*
295218822Sdim * Verify that a given pathname is in the include list and not in the
296218822Sdim * exclude list.
297218822Sdim */
298218822Sdimstatic int
299218822Sdimaccept_pathname(const char *pathname)
300218822Sdim{
301218822Sdim
302218822Sdim	if (!STAILQ_EMPTY(&include) && !match_pattern(&include, pathname))
303218822Sdim		return (0);
304218822Sdim	if (!STAILQ_EMPTY(&exclude) && match_pattern(&exclude, pathname))
30538889Sjdp		return (0);
306218822Sdim	return (1);
307218822Sdim}
308218822Sdim
309218822Sdim/*
310218822Sdim * Create the specified directory with the specified mode, taking certain
311218822Sdim * precautions on they way.
31238889Sjdp */
313130561Sobrienstatic void
314130561Sobrienmake_dir(const char *path, int mode)
315218822Sdim{
316130561Sobrien	struct stat sb;
317218822Sdim
318218822Sdim	if (lstat(path, &sb) == 0) {
319218822Sdim		if (S_ISDIR(sb.st_mode))
320218822Sdim			return;
321218822Sdim		/*
322218822Sdim		 * Normally, we should either ask the user about removing
323218822Sdim		 * the non-directory of the same name as a directory we
324		 * wish to create, or respect the -n or -o command-line
325		 * options.  However, this may lead to a later failure or
326		 * even compromise (if this non-directory happens to be a
327		 * symlink to somewhere unsafe), so we don't.
328		 */
329
330		/*
331		 * Don't check unlink() result; failure will cause mkdir()
332		 * to fail later, which we will catch.
333		 */
334		(void)unlink(path);
335	}
336	if (mkdir(path, mode) != 0 && errno != EEXIST)
337		error("mkdir('%s')", path);
338}
339
340/*
341 * Ensure that all directories leading up to (but not including) the
342 * specified path exist.
343 *
344 * XXX inefficient + modifies the file in-place
345 */
346static void
347make_parent(char *path)
348{
349	struct stat sb;
350	char *sep;
351
352	sep = strrchr(path, '/');
353	if (sep == NULL || sep == path)
354		return;
355	*sep = '\0';
356	if (lstat(path, &sb) == 0) {
357		if (S_ISDIR(sb.st_mode)) {
358			*sep = '/';
359			return;
360		}
361		unlink(path);
362	}
363	make_parent(path);
364	mkdir(path, 0755);
365	*sep = '/';
366
367#if 0
368	for (sep = path; (sep = strchr(sep, '/')) != NULL; sep++) {
369		/* root in case of absolute d_arg */
370		if (sep == path)
371			continue;
372		*sep = '\0';
373		make_dir(path, 0755);
374		*sep = '/';
375	}
376#endif
377}
378
379/*
380 * Extract a directory.
381 */
382static void
383extract_dir(struct archive *a, struct archive_entry *e, const char *path)
384{
385	int mode;
386
387	mode = archive_entry_mode(e) & 0777;
388	if (mode == 0)
389		mode = 0755;
390
391	/*
392	 * Some zipfiles contain directories with weird permissions such
393	 * as 0644 or 0444.  This can cause strange issues such as being
394	 * unable to extract files into the directory we just created, or
395	 * the user being unable to remove the directory later without
396	 * first manually changing its permissions.  Therefore, we whack
397	 * the permissions into shape, assuming that the user wants full
398	 * access and that anyone who gets read access also gets execute
399	 * access.
400	 */
401	mode |= 0700;
402	if (mode & 0040)
403		mode |= 0010;
404	if (mode & 0004)
405		mode |= 0001;
406
407	info("d %s\n", path);
408	make_dir(path, mode);
409	ac(archive_read_data_skip(a));
410}
411
412static unsigned char buffer[8192];
413static char spinner[] = { '|', '/', '-', '\\' };
414
415static int
416handle_existing_file(char **path)
417{
418	size_t alen;
419	ssize_t len;
420	char buf[4];
421
422	for (;;) {
423		fprintf(stderr,
424		    "replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ",
425		    *path);
426		if (fgets(buf, sizeof(buf), stdin) == NULL) {
427			clearerr(stdin);
428			printf("NULL\n(EOF or read error, "
429			    "treating as \"[N]one\"...)\n");
430			n_opt = 1;
431			return -1;
432		}
433		switch (*buf) {
434		case 'A':
435			o_opt = 1;
436			/* FALLTHROUGH */
437		case 'y':
438		case 'Y':
439			(void)unlink(*path);
440			return 1;
441		case 'N':
442			n_opt = 1;
443			/* FALLTHROUGH */
444		case 'n':
445			return -1;
446		case 'r':
447		case 'R':
448			printf("New name: ");
449			fflush(stdout);
450			free(*path);
451			*path = NULL;
452			alen = 0;
453			len = getdelim(path, &alen, '\n', stdin);
454			if ((*path)[len - 1] == '\n')
455				(*path)[len - 1] = '\0';
456			return 0;
457		default:
458			break;
459		}
460	}
461}
462
463/*
464 * Extract a regular file.
465 */
466static void
467extract_file(struct archive *a, struct archive_entry *e, char **path)
468{
469	int mode;
470	struct timespec mtime;
471	struct stat sb;
472	struct timespec ts[2];
473	int cr, fd, text, warn, check;
474	ssize_t len;
475	unsigned char *p, *q, *end;
476
477	mode = archive_entry_mode(e) & 0777;
478	if (mode == 0)
479		mode = 0644;
480	mtime.tv_sec = archive_entry_mtime(e);
481	mtime.tv_nsec = archive_entry_mtime_nsec(e);
482
483	/* look for existing file of same name */
484recheck:
485	if (lstat(*path, &sb) == 0) {
486		if (u_opt || f_opt) {
487			/* check if up-to-date */
488			if (S_ISREG(sb.st_mode) &&
489			    (sb.st_mtim.tv_sec > mtime.tv_sec ||
490			    (sb.st_mtim.tv_sec == mtime.tv_sec &&
491			    sb.st_mtim.tv_nsec >= mtime.tv_nsec)))
492				return;
493			(void)unlink(*path);
494		} else if (o_opt) {
495			/* overwrite */
496			(void)unlink(*path);
497		} else if (n_opt) {
498			/* do not overwrite */
499			return;
500		} else {
501			check = handle_existing_file(path);
502			if (check == 0)
503				goto recheck;
504			if (check == -1)
505				return; /* do not overwrite */
506		}
507	} else {
508		if (f_opt)
509			return;
510	}
511
512	if ((fd = open(*path, O_RDWR|O_CREAT|O_TRUNC, mode)) < 0)
513		error("open('%s')", *path);
514
515	/* loop over file contents and write to disk */
516	info(" extracting: %s", *path);
517	text = a_opt;
518	warn = 0;
519	cr = 0;
520	for (int n = 0; ; n++) {
521		if (tty && (n % 4) == 0)
522			info(" %c\b\b", spinner[(n / 4) % sizeof spinner]);
523
524		len = archive_read_data(a, buffer, sizeof buffer);
525
526		if (len < 0)
527			ac(len);
528
529		/* left over CR from previous buffer */
530		if (a_opt && cr) {
531			if (len == 0 || buffer[0] != '\n')
532				if (write(fd, "\r", 1) != 1)
533					error("write('%s')", *path);
534			cr = 0;
535		}
536
537		/* EOF */
538		if (len == 0)
539			break;
540		end = buffer + len;
541
542		/*
543		 * Detect whether this is a text file.  The correct way to
544		 * do this is to check the least significant bit of the
545		 * "internal file attributes" field of the corresponding
546		 * file header in the central directory, but libarchive
547		 * does not read the central directory, so we have to
548		 * guess by looking for non-ASCII characters in the
549		 * buffer.  Hopefully we won't guess wrong.  If we do
550		 * guess wrong, we print a warning message later.
551		 */
552		if (a_opt && n == 0) {
553			for (p = buffer; p < end; ++p) {
554				if (!isascii((unsigned char)*p)) {
555					text = 0;
556					break;
557				}
558			}
559		}
560
561		/* simple case */
562		if (!a_opt || !text) {
563			if (write(fd, buffer, len) != len)
564				error("write('%s')", *path);
565			continue;
566		}
567
568		/* hard case: convert \r\n to \n (sigh...) */
569		for (p = buffer; p < end; p = q + 1) {
570			for (q = p; q < end; q++) {
571				if (!warn && !isascii(*q)) {
572					warningx("%s may be corrupted due"
573					    " to weak text file detection"
574					    " heuristic", *path);
575					warn = 1;
576				}
577				if (q[0] != '\r')
578					continue;
579				if (&q[1] == end) {
580					cr = 1;
581					break;
582				}
583				if (q[1] == '\n')
584					break;
585			}
586			if (write(fd, p, q - p) != q - p)
587				error("write('%s')", *path);
588		}
589	}
590	if (tty)
591		info("  \b\b");
592	if (text)
593		info(" (text)");
594	info("\n");
595
596	/* set access and modification time */
597	ts[0].tv_sec = 0;
598	ts[0].tv_nsec = UTIME_NOW;
599	ts[1] = mtime;
600	if (futimens(fd, ts) != 0)
601		error("futimens('%s')", *path);
602	if (close(fd) != 0)
603		error("close('%s')", *path);
604}
605
606/*
607 * Extract a zipfile entry: first perform some sanity checks to ensure
608 * that it is either a directory or a regular file and that the path is
609 * not absolute and does not try to break out of the current directory;
610 * then call either extract_dir() or extract_file() as appropriate.
611 *
612 * This is complicated a bit by the various ways in which we need to
613 * manipulate the path name.  Case conversion (if requested by the -L
614 * option) happens first, but the include / exclude patterns are applied
615 * to the full converted path name, before the directory part of the path
616 * is removed in accordance with the -j option.  Sanity checks are
617 * intentionally done earlier than they need to be, so the user will get a
618 * warning about insecure paths even for files or directories which
619 * wouldn't be extracted anyway.
620 */
621static void
622extract(struct archive *a, struct archive_entry *e)
623{
624	char *pathname, *realpathname;
625	mode_t filetype;
626	char *p, *q;
627
628	pathname = pathdup(archive_entry_pathname(e));
629	filetype = archive_entry_filetype(e);
630
631	/* sanity checks */
632	if (pathname[0] == '/' ||
633	    strncmp(pathname, "../", 3) == 0 ||
634	    strstr(pathname, "/../") != NULL) {
635		warningx("skipping insecure entry '%s'", pathname);
636		ac(archive_read_data_skip(a));
637		free(pathname);
638		return;
639	}
640
641	/* I don't think this can happen in a zipfile.. */
642	if (!S_ISDIR(filetype) && !S_ISREG(filetype)) {
643		warningx("skipping non-regular entry '%s'", pathname);
644		ac(archive_read_data_skip(a));
645		free(pathname);
646		return;
647	}
648
649	/* skip directories in -j case */
650	if (S_ISDIR(filetype) && j_opt) {
651		ac(archive_read_data_skip(a));
652		free(pathname);
653		return;
654	}
655
656	/* apply include / exclude patterns */
657	if (!accept_pathname(pathname)) {
658		ac(archive_read_data_skip(a));
659		free(pathname);
660		return;
661	}
662
663	/* apply -j and -d */
664	if (j_opt) {
665		for (p = q = pathname; *p; ++p)
666			if (*p == '/')
667				q = p + 1;
668		realpathname = pathcat(d_arg, q);
669	} else {
670		realpathname = pathcat(d_arg, pathname);
671	}
672
673	/* ensure that parent directory exists */
674	make_parent(realpathname);
675
676	if (S_ISDIR(filetype))
677		extract_dir(a, e, realpathname);
678	else
679		extract_file(a, e, &realpathname);
680
681	free(realpathname);
682	free(pathname);
683}
684
685static void
686extract_stdout(struct archive *a, struct archive_entry *e)
687{
688	char *pathname;
689	mode_t filetype;
690	int cr, text, warn;
691	ssize_t len;
692	unsigned char *p, *q, *end;
693
694	pathname = pathdup(archive_entry_pathname(e));
695	filetype = archive_entry_filetype(e);
696
697	/* I don't think this can happen in a zipfile.. */
698	if (!S_ISDIR(filetype) && !S_ISREG(filetype)) {
699		warningx("skipping non-regular entry '%s'", pathname);
700		ac(archive_read_data_skip(a));
701		free(pathname);
702		return;
703	}
704
705	/* skip directories in -j case */
706	if (S_ISDIR(filetype)) {
707		ac(archive_read_data_skip(a));
708		free(pathname);
709		return;
710	}
711
712	/* apply include / exclude patterns */
713	if (!accept_pathname(pathname)) {
714		ac(archive_read_data_skip(a));
715		free(pathname);
716		return;
717	}
718
719	if (c_opt)
720		info("x %s\n", pathname);
721
722	text = a_opt;
723	warn = 0;
724	cr = 0;
725	for (int n = 0; ; n++) {
726		len = archive_read_data(a, buffer, sizeof buffer);
727
728		if (len < 0)
729			ac(len);
730
731		/* left over CR from previous buffer */
732		if (a_opt && cr) {
733			if (len == 0 || buffer[0] != '\n') {
734				if (fwrite("\r", 1, 1, stderr) != 1)
735					error("write('%s')", pathname);
736			}
737			cr = 0;
738		}
739
740		/* EOF */
741		if (len == 0)
742			break;
743		end = buffer + len;
744
745		/*
746		 * Detect whether this is a text file.  The correct way to
747		 * do this is to check the least significant bit of the
748		 * "internal file attributes" field of the corresponding
749		 * file header in the central directory, but libarchive
750		 * does not read the central directory, so we have to
751		 * guess by looking for non-ASCII characters in the
752		 * buffer.  Hopefully we won't guess wrong.  If we do
753		 * guess wrong, we print a warning message later.
754		 */
755		if (a_opt && n == 0) {
756			for (p = buffer; p < end; ++p) {
757				if (!isascii((unsigned char)*p)) {
758					text = 0;
759					break;
760				}
761			}
762		}
763
764		/* simple case */
765		if (!a_opt || !text) {
766			if (fwrite(buffer, 1, len, stdout) != (size_t)len)
767				error("write('%s')", pathname);
768			continue;
769		}
770
771		/* hard case: convert \r\n to \n (sigh...) */
772		for (p = buffer; p < end; p = q + 1) {
773			for (q = p; q < end; q++) {
774				if (!warn && !isascii(*q)) {
775					warningx("%s may be corrupted due"
776					    " to weak text file detection"
777					    " heuristic", pathname);
778					warn = 1;
779				}
780				if (q[0] != '\r')
781					continue;
782				if (&q[1] == end) {
783					cr = 1;
784					break;
785				}
786				if (q[1] == '\n')
787					break;
788			}
789			if (fwrite(p, 1, q - p, stdout) != (size_t)(q - p))
790				error("write('%s')", pathname);
791		}
792	}
793
794	free(pathname);
795}
796
797/*
798 * Print the name of an entry to stdout.
799 */
800static void
801list(struct archive *a, struct archive_entry *e)
802{
803	char buf[20];
804	time_t mtime;
805
806	mtime = archive_entry_mtime(e);
807	strftime(buf, sizeof(buf), "%m-%d-%g %R", localtime(&mtime));
808
809	if (!zipinfo_mode) {
810		if (v_opt == 1) {
811			printf(" %8ju  %s   %s\n",
812			    (uintmax_t)archive_entry_size(e),
813			    buf, archive_entry_pathname(e));
814		} else if (v_opt == 2) {
815			printf("%8ju  Stored  %7ju   0%%  %s  %08x  %s\n",
816			    (uintmax_t)archive_entry_size(e),
817			    (uintmax_t)archive_entry_size(e),
818			    buf,
819			    0U,
820			    archive_entry_pathname(e));
821		}
822	} else {
823		if (Z1_opt)
824			printf("%s\n",archive_entry_pathname(e));
825	}
826	ac(archive_read_data_skip(a));
827}
828
829/*
830 * Extract to memory to check CRC
831 */
832static int
833test(struct archive *a, struct archive_entry *e)
834{
835	ssize_t len;
836	int error_count;
837
838	error_count = 0;
839	if (S_ISDIR(archive_entry_filetype(e)))
840		return 0;
841
842	info("    testing: %s\t", archive_entry_pathname(e));
843	while ((len = archive_read_data(a, buffer, sizeof buffer)) > 0)
844		/* nothing */;
845	if (len < 0) {
846		info(" %s\n", archive_error_string(a));
847		++error_count;
848	} else {
849		info(" OK\n");
850	}
851
852	/* shouldn't be necessary, but it doesn't hurt */
853	ac(archive_read_data_skip(a));
854
855	return error_count;
856}
857
858
859/*
860 * Main loop: open the zipfile, iterate over its contents and decide what
861 * to do with each entry.
862 */
863static void
864unzip(const char *fn)
865{
866	struct archive *a;
867	struct archive_entry *e;
868	int ret;
869	uintmax_t total_size, file_count, error_count;
870
871	if ((a = archive_read_new()) == NULL)
872		error("archive_read_new failed");
873
874	ac(archive_read_support_format_zip(a));
875	ac(archive_read_open_filename(a, fn, 8192));
876
877	if (!zipinfo_mode) {
878		if (!p_opt && !q_opt)
879			printf("Archive:  %s\n", fn);
880		if (v_opt == 1) {
881			printf("  Length     Date   Time    Name\n");
882			printf(" --------    ----   ----    ----\n");
883		} else if (v_opt == 2) {
884			printf(" Length   Method    Size  Ratio   Date   Time   CRC-32    Name\n");
885			printf("--------  ------  ------- -----   ----   ----   ------    ----\n");
886		}
887	}
888
889	total_size = 0;
890	file_count = 0;
891	error_count = 0;
892	for (;;) {
893		ret = archive_read_next_header(a, &e);
894		if (ret == ARCHIVE_EOF)
895			break;
896		ac(ret);
897		if (!zipinfo_mode) {
898			if (t_opt)
899				error_count += test(a, e);
900			else if (v_opt)
901				list(a, e);
902			else if (p_opt || c_opt)
903				extract_stdout(a, e);
904			else
905				extract(a, e);
906		} else {
907			if (Z1_opt)
908				list(a, e);
909		}
910
911		total_size += archive_entry_size(e);
912		++file_count;
913	}
914
915	if (zipinfo_mode) {
916		if (v_opt == 1) {
917			printf(" --------                   -------\n");
918			printf(" %8ju                   %ju file%s\n",
919			    total_size, file_count, file_count != 1 ? "s" : "");
920		} else if (v_opt == 2) {
921			printf("--------          -------  ---                            -------\n");
922			printf("%8ju          %7ju   0%%                            %ju file%s\n",
923			    total_size, total_size, file_count,
924			    file_count != 1 ? "s" : "");
925		}
926	}
927
928	ac(archive_read_close(a));
929	(void)archive_read_free(a);
930
931	if (t_opt) {
932		if (error_count > 0) {
933			errorx("%d checksum error(s) found.", error_count);
934		}
935		else {
936			printf("No errors detected in compressed data of %s.\n",
937			       fn);
938		}
939	}
940}
941
942static void
943usage(void)
944{
945
946	fprintf(stderr, "usage: unzip [-aCcfjLlnopqtuvZ1] [-d dir] [-x pattern] zipfile\n");
947	exit(1);
948}
949
950static int
951getopts(int argc, char *argv[])
952{
953	int opt;
954
955	optreset = optind = 1;
956	while ((opt = getopt(argc, argv, "aCcd:fjLlnopqtuvx:Z1")) != -1)
957		switch (opt) {
958		case '1':
959			Z1_opt = 1;
960			break;
961		case 'a':
962			a_opt = 1;
963			break;
964		case 'C':
965			C_opt = 1;
966			break;
967		case 'c':
968			c_opt = 1;
969			break;
970		case 'd':
971			d_arg = optarg;
972			break;
973		case 'f':
974			f_opt = 1;
975			break;
976		case 'j':
977			j_opt = 1;
978			break;
979		case 'L':
980			L_opt = 1;
981			break;
982		case 'l':
983			if (v_opt == 0)
984				v_opt = 1;
985			break;
986		case 'n':
987			n_opt = 1;
988			break;
989		case 'o':
990			o_opt = 1;
991			q_opt = 1;
992			break;
993		case 'p':
994			p_opt = 1;
995			break;
996		case 'q':
997			q_opt = 1;
998			break;
999		case 't':
1000			t_opt = 1;
1001			break;
1002		case 'u':
1003			u_opt = 1;
1004			break;
1005		case 'v':
1006			v_opt = 2;
1007			break;
1008		case 'x':
1009			add_pattern(&exclude, optarg);
1010			break;
1011		case 'Z':
1012			zipinfo_mode = 1;
1013			break;
1014		default:
1015			usage();
1016		}
1017
1018	return (optind);
1019}
1020
1021int
1022main(int argc, char *argv[])
1023{
1024	const char *zipfile;
1025	int nopts;
1026
1027	if (isatty(STDOUT_FILENO))
1028		tty = 1;
1029
1030	if (getenv("UNZIP_DEBUG") != NULL)
1031		unzip_debug = 1;
1032	for (int i = 0; i < argc; ++i)
1033		debug("%s%c", argv[i], (i < argc - 1) ? ' ' : '\n');
1034
1035	/*
1036	 * Info-ZIP's unzip(1) expects certain options to come before the
1037	 * zipfile name, and others to come after - though it does not
1038	 * enforce this.  For simplicity, we accept *all* options both
1039	 * before and after the zipfile name.
1040	 */
1041	nopts = getopts(argc, argv);
1042
1043	/*
1044	 * When more of the zipinfo mode options are implemented, this
1045	 * will need to change.
1046	 */
1047	if (zipinfo_mode && !Z1_opt) {
1048		printf("Zipinfo mode needs additional options\n");
1049		exit(1);
1050	}
1051
1052	if (argc <= nopts)
1053		usage();
1054	zipfile = argv[nopts++];
1055
1056	if (strcmp(zipfile, "-") == 0)
1057		zipfile = NULL; /* STDIN */
1058
1059	while (nopts < argc && *argv[nopts] != '-')
1060		add_pattern(&include, argv[nopts++]);
1061
1062	nopts--; /* fake argv[0] */
1063	nopts += getopts(argc - nopts, argv + nopts);
1064
1065	if (n_opt + o_opt + u_opt > 1)
1066		errorx("-n, -o and -u are contradictory");
1067
1068	unzip(zipfile);
1069
1070	exit(0);
1071}
1072