2 * Copyright (c) 2007-2008 Dag-Erling Coïdan Smørgrav
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * This file would be much shorter if we didn't care about command-line
30 * compatibility with Info-ZIP's UnZip, which requires us to duplicate
31 * parts of libarchive in order to gain more detailed control of its
32 * behaviour for the purpose of implementing the -n, -o, -L and -a
36 #include <sys/queue.h>
50 #include <archive_entry.h>
52 /* command-line options */
53 static int a_opt; /* convert EOL */
54 static const char *d_arg; /* directory */
55 static int j_opt; /* junk directories */
56 static int L_opt; /* lowercase names */
57 static int l_opt; /* list */
58 static int n_opt; /* never overwrite */
59 static int o_opt; /* always overwrite */
60 static int q_opt; /* quiet */
61 static int u_opt; /* update */
63 /* time when unzip started */
67 static int unzip_debug;
72 /* convenience macro */
73 /* XXX should differentiate between ARCHIVE_{WARN,FAIL,RETRY} */
77 if (acret != ARCHIVE_OK) \
78 errorx("%s", archive_error_string(a)); \
82 * Indicates that last info() did not end with EOL. This helps error() et
83 * al. avoid printing an error message on the same line as an incomplete
84 * informational message.
88 /* fatal error message + errno */
90 error(const char *fmt, ...)
95 fprintf(stdout, "\n");
97 fprintf(stderr, "unzip: ");
99 vfprintf(stderr, fmt, ap);
101 fprintf(stderr, ": %s\n", strerror(errno));
105 /* fatal error message, no errno */
107 errorx(const char *fmt, ...)
112 fprintf(stdout, "\n");
114 fprintf(stderr, "unzip: ");
116 vfprintf(stderr, fmt, ap);
118 fprintf(stderr, "\n");
123 /* non-fatal error message + errno */
125 warning(const char *fmt, ...)
130 fprintf(stdout, "\n");
132 fprintf(stderr, "unzip: ");
134 vfprintf(stderr, fmt, ap);
136 fprintf(stderr, ": %s\n", strerror(errno));
140 /* non-fatal error message, no errno */
142 warningx(const char *fmt, ...)
147 fprintf(stdout, "\n");
149 fprintf(stderr, "unzip: ");
151 vfprintf(stderr, fmt, ap);
153 fprintf(stderr, "\n");
156 /* informational message (if not -q) */
158 info(const char *fmt, ...)
163 if (q_opt && !unzip_debug)
166 vfprintf(stdout, fmt, ap);
170 for (i = 0; fmt[i] != '\0'; ++i)
172 noeol = !(i && fmt[i - 1] == '\n');
175 /* debug message (if unzip_debug) */
177 debug(const char *fmt, ...)
185 vfprintf(stderr, fmt, ap);
189 for (i = 0; fmt[i] != '\0'; ++i)
191 noeol = !(i && fmt[i - 1] == '\n');
194 /* duplicate a path name, possibly converting to lower case */
196 pathdup(const char *path)
202 while (len && path[len - 1] == '/')
204 if ((str = malloc(len + 1)) == NULL) {
208 for (int i = 0; i < len; ++i)
209 str[i] = L_opt ? tolower(path[i]) : path[i];
215 /* concatenate two path names */
217 pathcat(const char *prefix, const char *path)
222 prelen = prefix ? strlen(prefix) + 1 : 0;
223 len = strlen(path) + 1;
224 if ((str = malloc(prelen + len)) == NULL) {
229 memcpy(str, prefix, prelen); /* includes zero */
230 str[prelen - 1] = '/'; /* splat zero */
232 memcpy(str + prelen, path, len); /* includes zero */
238 * Pattern lists for include / exclude processing
241 STAILQ_ENTRY(pattern) link;
245 STAILQ_HEAD(pattern_list, pattern);
246 static struct pattern_list include = STAILQ_HEAD_INITIALIZER(include);
247 static struct pattern_list exclude = STAILQ_HEAD_INITIALIZER(exclude);
250 * Add an entry to a pattern list
253 add_pattern(struct pattern_list *list, const char *pattern)
255 struct pattern *entry;
258 debug("adding pattern '%s'\n", pattern);
259 len = strlen(pattern);
260 if ((entry = malloc(sizeof *entry + len + 1)) == NULL) {
264 memset(&entry->link, 0, sizeof entry->link);
265 memcpy(entry->pattern, pattern, len + 1);
266 STAILQ_INSERT_TAIL(list, entry, link);
270 * Match a string against a list of patterns
273 match_pattern(struct pattern_list *list, const char *str)
275 struct pattern *entry;
277 STAILQ_FOREACH(entry, list, link) {
278 if (fnmatch(entry->pattern, str, 0) == 0)
285 * Verify that a given pathname is in the include list and not in the
289 accept_pathname(const char *pathname)
292 if (!STAILQ_EMPTY(&include) && !match_pattern(&include, pathname))
294 if (!STAILQ_EMPTY(&exclude) && match_pattern(&exclude, pathname))
300 * Create the specified directory with the specified mode, taking certain
301 * precautions on they way.
304 make_dir(const char *path, int mode)
308 if (lstat(path, &sb) == 0) {
309 if (S_ISDIR(sb.st_mode))
312 * Normally, we should either ask the user about removing
313 * the non-directory of the same name as a directory we
314 * wish to create, or respect the -n or -o command-line
315 * options. However, this may lead to a later failure or
316 * even compromise (if this non-directory happens to be a
317 * symlink to somewhere unsafe), so we don't.
321 * Don't check unlink() result; failure will cause mkdir()
322 * to fail later, which we will catch.
326 if (mkdir(path, mode) != 0 && errno != EEXIST)
327 error("mkdir('%s')", path);
331 * Ensure that all directories leading up to (but not including) the
332 * specified path exist.
337 make_parent(char *path)
342 sep = strrchr(path, '/');
343 if (sep == NULL || sep == path)
346 if (lstat(path, &sb) == 0) {
347 if (S_ISDIR(sb.st_mode)) {
358 for (sep = path; (sep = strchr(sep, '/')) != NULL; sep++) {
359 /* root in case of absolute d_arg */
363 make_dir(path, 0755);
370 * Extract a directory.
373 extract_dir(struct archive *a, struct archive_entry *e, const char *path)
377 mode = archive_entry_filetype(e) & 0777;
382 * Some zipfiles contain directories with weird permissions such
383 * as 0644 or 0444. This can cause strange issues such as being
384 * unable to extract files into the directory we just created, or
385 * the user being unable to remove the directory later without
386 * first manually changing its permissions. Therefore, we whack
387 * the permissions into shape, assuming that the user wants full
388 * access and that anyone who gets read access also gets execute
397 info("d %s\n", path);
398 make_dir(path, mode);
399 ac(archive_read_data_skip(a));
402 static unsigned char buffer[8192];
403 static char spinner[] = { '|', '/', '-', '\\' };
406 * Extract a regular file.
409 extract_file(struct archive *a, struct archive_entry *e, const char *path)
414 struct timeval tv[2];
415 int cr, fd, text, warn;
417 unsigned char *p, *q, *end;
419 mode = archive_entry_filetype(e) & 0777;
422 mtime = archive_entry_mtime(e);
424 /* look for existing file of same name */
425 if (lstat(path, &sb) == 0) {
427 /* check if up-to-date */
428 if (S_ISREG(sb.st_mode) && sb.st_mtime > mtime)
435 /* do not overwrite */
439 errorx("not implemented");
443 if ((fd = open(path, O_RDWR|O_CREAT|O_TRUNC, mode)) < 0)
444 error("open('%s')", path);
446 /* loop over file contents and write to disk */
451 for (int n = 0; ; n++) {
452 if (tty && (n % 4) == 0)
453 info(" %c\b\b", spinner[(n / 4) % sizeof spinner]);
455 len = archive_read_data(a, buffer, sizeof buffer);
460 /* left over CR from previous buffer */
462 if (len == 0 || buffer[0] != '\n')
463 if (write(fd, "\r", 1) != 1)
464 error("write('%s')", path);
474 * Detect whether this is a text file. The correct way to
475 * do this is to check the least significant bit of the
476 * "internal file attributes" field of the corresponding
477 * file header in the central directory, but libarchive
478 * does not read the central directory, so we have to
479 * guess by looking for non-ASCII characters in the
480 * buffer. Hopefully we won't guess wrong. If we do
481 * guess wrong, we print a warning message later.
483 if (a_opt && n == 0) {
484 for (p = buffer; p < end; ++p) {
485 if (!isascii((unsigned char)*p)) {
493 if (!a_opt || !text) {
494 if (write(fd, buffer, len) != len)
495 error("write('%s')", path);
499 /* hard case: convert \r\n to \n (sigh...) */
500 for (p = buffer; p < end; p = q + 1) {
501 for (q = p; q < end; q++) {
502 if (!warn && !isascii(*q)) {
503 warningx("%s may be corrupted due"
504 " to weak text file detection"
517 if (write(fd, p, q - p) != q - p)
518 error("write('%s')", path);
527 /* set access and modification time */
530 tv[1].tv_sec = mtime;
532 if (futimes(fd, tv) != 0)
533 error("utimes('%s')", path);
535 error("close('%s')", path);
539 * Extract a zipfile entry: first perform some sanity checks to ensure
540 * that it is either a directory or a regular file and that the path is
541 * not absolute and does not try to break out of the current directory;
542 * then call either extract_dir() or extract_file() as appropriate.
544 * This is complicated a bit by the various ways in which we need to
545 * manipulate the path name. Case conversion (if requested by the -L
546 * option) happens first, but the include / exclude patterns are applied
547 * to the full converted path name, before the directory part of the path
548 * is removed in accordance with the -j option. Sanity checks are
549 * intentionally done earlier than they need to be, so the user will get a
550 * warning about insecure paths even for files or directories which
551 * wouldn't be extracted anyway.
554 extract(struct archive *a, struct archive_entry *e)
556 char *pathname, *realpathname;
560 pathname = pathdup(archive_entry_pathname(e));
561 filetype = archive_entry_filetype(e);
564 if (pathname[0] == '/' ||
565 strncmp(pathname, "../", 3) == 0 ||
566 strstr(pathname, "/../") != NULL) {
567 warningx("skipping insecure entry '%s'", pathname);
568 ac(archive_read_data_skip(a));
573 /* I don't think this can happen in a zipfile.. */
574 if (!S_ISDIR(filetype) && !S_ISREG(filetype)) {
575 warningx("skipping non-regular entry '%s'", pathname);
576 ac(archive_read_data_skip(a));
581 /* skip directories in -j case */
582 if (S_ISDIR(filetype) && j_opt) {
583 ac(archive_read_data_skip(a));
588 /* apply include / exclude patterns */
589 if (!accept_pathname(pathname)) {
590 ac(archive_read_data_skip(a));
595 /* apply -j and -d */
597 for (p = q = pathname; *p; ++p)
600 realpathname = pathcat(d_arg, q);
602 realpathname = pathcat(d_arg, pathname);
605 /* ensure that parent directory exists */
606 make_parent(realpathname);
608 if (S_ISDIR(filetype))
609 extract_dir(a, e, realpathname);
611 extract_file(a, e, realpathname);
618 * Print the name of an entry to stdout.
621 list(struct archive *a, struct archive_entry *e)
624 printf("%s\n", archive_entry_pathname(e));
625 ac(archive_read_data_skip(a));
629 * Main loop: open the zipfile, iterate over its contents and decide what
630 * to do with each entry.
633 unzip(const char *fn)
636 struct archive_entry *e;
639 if ((fd = open(fn, O_RDONLY)) < 0)
642 a = archive_read_new();
643 ac(archive_read_support_format_zip(a));
644 ac(archive_read_open_fd(a, fd, 8192));
647 ret = archive_read_next_header(a, &e);
648 if (ret == ARCHIVE_EOF)
657 ac(archive_read_close(a));
658 (void)archive_read_finish(a);
667 fprintf(stderr, "usage: unzip [-ajLlnoqu] [-d dir] zipfile\n");
672 getopts(int argc, char *argv[])
676 optreset = optind = 1;
677 while ((opt = getopt(argc, argv, "ad:jLlnoqux:")) != -1)
707 add_pattern(&exclude, optarg);
717 main(int argc, char *argv[])
722 if (isatty(STDOUT_FILENO))
725 if (getenv("UNZIP_DEBUG") != NULL)
727 for (int i = 0; i < argc; ++i)
728 debug("%s%c", argv[i], (i < argc - 1) ? ' ' : '\n');
731 * Info-ZIP's unzip(1) expects certain options to come before the
732 * zipfile name, and others to come after - though it does not
733 * enforce this. For simplicity, we accept *all* options both
734 * before and after the zipfile name.
736 nopts = getopts(argc, argv);
740 zipfile = argv[nopts++];
742 while (nopts < argc && *argv[nopts] != '-')
743 add_pattern(&include, argv[nopts++]);
745 nopts--; /* fake argv[0] */
746 nopts += getopts(argc - nopts, argv + nopts);
748 if (n_opt + o_opt + u_opt > 1)
749 errorx("-n, -o and -u are contradictory");