2 * Copyright (c) 2009 Joerg Sonnenberger <joerg@NetBSD.org>
3 * Copyright (c) 2007-2008 Dag-Erling Smørgrav
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
9 * 1. Redistributions of source code must retain the above copyright
10 * notice, this list of conditions and the following disclaimer
11 * in this position and unchanged.
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.
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
17 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
18 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
19 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
20 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
21 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
22 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
23 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
24 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
25 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30 * This file would be much shorter if we didn't care about command-line
31 * compatibility with Info-ZIP's UnZip, which requires us to duplicate
32 * parts of libarchive in order to gain more detailed control of its
33 * behaviour for the purpose of implementing the -n, -o, -L and -a
37 #include <sys/queue.h>
51 #include <archive_entry.h>
53 /* command-line options */
54 static int a_opt; /* convert EOL */
55 static int C_opt; /* match case-insensitively */
56 static int c_opt; /* extract to stdout */
57 static const char *d_arg; /* directory */
58 static int f_opt; /* update existing files only */
59 static int j_opt; /* junk directories */
60 static int L_opt; /* lowercase names */
61 static int n_opt; /* never overwrite */
62 static int o_opt; /* always overwrite */
63 static int p_opt; /* extract to stdout, quiet */
64 static int q_opt; /* quiet */
65 static int t_opt; /* test */
66 static int u_opt; /* update */
67 static int v_opt; /* verbose/list */
68 static int Z1_opt; /* zipinfo mode list files only */
70 /* time when unzip started */
74 static int unzip_debug;
77 static int zipinfo_mode;
82 /* convenience macro */
83 /* XXX should differentiate between ARCHIVE_{WARN,FAIL,RETRY} */
87 if (acret != ARCHIVE_OK) \
88 errorx("%s", archive_error_string(a)); \
92 * Indicates that last info() did not end with EOL. This helps error() et
93 * al. avoid printing an error message on the same line as an incomplete
94 * informational message.
98 /* fatal error message + errno */
100 error(const char *fmt, ...)
105 fprintf(stdout, "\n");
107 fprintf(stderr, "unzip: ");
109 vfprintf(stderr, fmt, ap);
111 fprintf(stderr, ": %s\n", strerror(errno));
115 /* fatal error message, no errno */
117 errorx(const char *fmt, ...)
122 fprintf(stdout, "\n");
124 fprintf(stderr, "unzip: ");
126 vfprintf(stderr, fmt, ap);
128 fprintf(stderr, "\n");
133 /* non-fatal error message + errno */
135 warning(const char *fmt, ...)
140 fprintf(stdout, "\n");
142 fprintf(stderr, "unzip: ");
144 vfprintf(stderr, fmt, ap);
146 fprintf(stderr, ": %s\n", strerror(errno));
150 /* non-fatal error message, no errno */
152 warningx(const char *fmt, ...)
157 fprintf(stdout, "\n");
159 fprintf(stderr, "unzip: ");
161 vfprintf(stderr, fmt, ap);
163 fprintf(stderr, "\n");
166 /* informational message (if not -q) */
168 info(const char *fmt, ...)
172 if (q_opt && !unzip_debug)
175 vfprintf(stdout, fmt, ap);
182 noeol = fmt[strlen(fmt) - 1] != '\n';
185 /* debug message (if unzip_debug) */
187 debug(const char *fmt, ...)
194 vfprintf(stderr, fmt, ap);
201 noeol = fmt[strlen(fmt) - 1] != '\n';
204 /* duplicate a path name, possibly converting to lower case */
206 pathdup(const char *path)
212 while (len && path[len - 1] == '/')
214 if ((str = malloc(len + 1)) == NULL) {
219 for (i = 0; i < len; ++i)
220 str[i] = tolower((unsigned char)path[i]);
222 memcpy(str, path, len);
229 /* concatenate two path names */
231 pathcat(const char *prefix, const char *path)
236 prelen = prefix ? strlen(prefix) + 1 : 0;
237 len = strlen(path) + 1;
238 if ((str = malloc(prelen + len)) == NULL) {
243 memcpy(str, prefix, prelen); /* includes zero */
244 str[prelen - 1] = '/'; /* splat zero */
246 memcpy(str + prelen, path, len); /* includes zero */
252 * Pattern lists for include / exclude processing
255 STAILQ_ENTRY(pattern) link;
259 STAILQ_HEAD(pattern_list, pattern);
260 static struct pattern_list include = STAILQ_HEAD_INITIALIZER(include);
261 static struct pattern_list exclude = STAILQ_HEAD_INITIALIZER(exclude);
264 * Add an entry to a pattern list
267 add_pattern(struct pattern_list *list, const char *pattern)
269 struct pattern *entry;
272 debug("adding pattern '%s'\n", pattern);
273 len = strlen(pattern);
274 if ((entry = malloc(sizeof *entry + len + 1)) == NULL) {
278 memcpy(entry->pattern, pattern, len + 1);
279 STAILQ_INSERT_TAIL(list, entry, link);
283 * Match a string against a list of patterns
286 match_pattern(struct pattern_list *list, const char *str)
288 struct pattern *entry;
290 STAILQ_FOREACH(entry, list, link) {
291 if (fnmatch(entry->pattern, str, C_opt ? FNM_CASEFOLD : 0) == 0)
298 * Verify that a given pathname is in the include list and not in the
302 accept_pathname(const char *pathname)
305 if (!STAILQ_EMPTY(&include) && !match_pattern(&include, pathname))
307 if (!STAILQ_EMPTY(&exclude) && match_pattern(&exclude, pathname))
313 * Create the specified directory with the specified mode, taking certain
314 * precautions on they way.
317 make_dir(const char *path, int mode)
321 if (lstat(path, &sb) == 0) {
322 if (S_ISDIR(sb.st_mode))
325 * Normally, we should either ask the user about removing
326 * the non-directory of the same name as a directory we
327 * wish to create, or respect the -n or -o command-line
328 * options. However, this may lead to a later failure or
329 * even compromise (if this non-directory happens to be a
330 * symlink to somewhere unsafe), so we don't.
334 * Don't check unlink() result; failure will cause mkdir()
335 * to fail later, which we will catch.
339 if (mkdir(path, mode) != 0 && errno != EEXIST)
340 error("mkdir('%s')", path);
344 * Ensure that all directories leading up to (but not including) the
345 * specified path exist.
347 * XXX inefficient + modifies the file in-place
350 make_parent(char *path)
355 sep = strrchr(path, '/');
356 if (sep == NULL || sep == path)
359 if (lstat(path, &sb) == 0) {
360 if (S_ISDIR(sb.st_mode)) {
371 for (sep = path; (sep = strchr(sep, '/')) != NULL; sep++) {
372 /* root in case of absolute d_arg */
376 make_dir(path, 0755);
383 * Extract a directory.
386 extract_dir(struct archive *a, struct archive_entry *e, const char *path)
390 mode = archive_entry_mode(e) & 0777;
395 * Some zipfiles contain directories with weird permissions such
396 * as 0644 or 0444. This can cause strange issues such as being
397 * unable to extract files into the directory we just created, or
398 * the user being unable to remove the directory later without
399 * first manually changing its permissions. Therefore, we whack
400 * the permissions into shape, assuming that the user wants full
401 * access and that anyone who gets read access also gets execute
410 info("d %s\n", path);
411 make_dir(path, mode);
412 ac(archive_read_data_skip(a));
415 static unsigned char buffer[8192];
416 static char spinner[] = { '|', '/', '-', '\\' };
419 handle_existing_file(char **path)
427 "replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ",
429 if (fgets(buf, sizeof(buf), stdin) == NULL) {
431 printf("NULL\n(EOF or read error, "
432 "treating as \"[N]one\"...)\n");
451 printf("New name: ");
456 len = getdelim(path, &alen, '\n', stdin);
457 if ((*path)[len - 1] == '\n')
458 (*path)[len - 1] = '\0';
467 * Extract a regular file.
470 extract_file(struct archive *a, struct archive_entry *e, char **path)
475 struct timeval tv[2];
476 int cr, fd, text, warn, check;
478 unsigned char *p, *q, *end;
480 mode = archive_entry_mode(e) & 0777;
483 mtime = archive_entry_mtime(e);
485 /* look for existing file of same name */
487 if (lstat(*path, &sb) == 0) {
488 if (u_opt || f_opt) {
489 /* check if up-to-date */
490 if (S_ISREG(sb.st_mode) && sb.st_mtime >= mtime)
497 /* do not overwrite */
500 check = handle_existing_file(path);
504 return; /* do not overwrite */
511 if ((fd = open(*path, O_RDWR|O_CREAT|O_TRUNC, mode)) < 0)
512 error("open('%s')", *path);
514 /* loop over file contents and write to disk */
515 info(" extracting: %s", *path);
519 for (int n = 0; ; n++) {
520 if (tty && (n % 4) == 0)
521 info(" %c\b\b", spinner[(n / 4) % sizeof spinner]);
523 len = archive_read_data(a, buffer, sizeof buffer);
528 /* left over CR from previous buffer */
530 if (len == 0 || buffer[0] != '\n')
531 if (write(fd, "\r", 1) != 1)
532 error("write('%s')", *path);
542 * Detect whether this is a text file. The correct way to
543 * do this is to check the least significant bit of the
544 * "internal file attributes" field of the corresponding
545 * file header in the central directory, but libarchive
546 * does not read the central directory, so we have to
547 * guess by looking for non-ASCII characters in the
548 * buffer. Hopefully we won't guess wrong. If we do
549 * guess wrong, we print a warning message later.
551 if (a_opt && n == 0) {
552 for (p = buffer; p < end; ++p) {
553 if (!isascii((unsigned char)*p)) {
561 if (!a_opt || !text) {
562 if (write(fd, buffer, len) != len)
563 error("write('%s')", *path);
567 /* hard case: convert \r\n to \n (sigh...) */
568 for (p = buffer; p < end; p = q + 1) {
569 for (q = p; q < end; q++) {
570 if (!warn && !isascii(*q)) {
571 warningx("%s may be corrupted due"
572 " to weak text file detection"
573 " heuristic", *path);
585 if (write(fd, p, q - p) != q - p)
586 error("write('%s')", *path);
595 /* set access and modification time */
598 tv[1].tv_sec = mtime;
600 if (futimes(fd, tv) != 0)
601 error("utimes('%s')", *path);
603 error("close('%s')", *path);
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.
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.
622 extract(struct archive *a, struct archive_entry *e)
624 char *pathname, *realpathname;
628 pathname = pathdup(archive_entry_pathname(e));
629 filetype = archive_entry_filetype(e);
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));
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));
649 /* skip directories in -j case */
650 if (S_ISDIR(filetype) && j_opt) {
651 ac(archive_read_data_skip(a));
656 /* apply include / exclude patterns */
657 if (!accept_pathname(pathname)) {
658 ac(archive_read_data_skip(a));
663 /* apply -j and -d */
665 for (p = q = pathname; *p; ++p)
668 realpathname = pathcat(d_arg, q);
670 realpathname = pathcat(d_arg, pathname);
673 /* ensure that parent directory exists */
674 make_parent(realpathname);
676 if (S_ISDIR(filetype))
677 extract_dir(a, e, realpathname);
679 extract_file(a, e, &realpathname);
686 extract_stdout(struct archive *a, struct archive_entry *e)
692 unsigned char *p, *q, *end;
694 pathname = pathdup(archive_entry_pathname(e));
695 filetype = archive_entry_filetype(e);
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));
705 /* skip directories in -j case */
706 if (S_ISDIR(filetype)) {
707 ac(archive_read_data_skip(a));
712 /* apply include / exclude patterns */
713 if (!accept_pathname(pathname)) {
714 ac(archive_read_data_skip(a));
720 info("x %s\n", pathname);
725 for (int n = 0; ; n++) {
726 len = archive_read_data(a, buffer, sizeof buffer);
731 /* left over CR from previous buffer */
733 if (len == 0 || buffer[0] != '\n') {
734 if (fwrite("\r", 1, 1, stderr) != 1)
735 error("write('%s')", pathname);
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.
755 if (a_opt && n == 0) {
756 for (p = buffer; p < end; ++p) {
757 if (!isascii((unsigned char)*p)) {
765 if (!a_opt || !text) {
766 if (fwrite(buffer, 1, len, stdout) != (size_t)len)
767 error("write('%s')", pathname);
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);
789 if (fwrite(p, 1, q - p, stdout) != (size_t)(q - p))
790 error("write('%s')", pathname);
798 * Print the name of an entry to stdout.
801 list(struct archive *a, struct archive_entry *e)
806 mtime = archive_entry_mtime(e);
807 strftime(buf, sizeof(buf), "%m-%d-%g %R", localtime(&mtime));
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),
820 archive_entry_pathname(e));
824 printf("%s\n",archive_entry_pathname(e));
826 ac(archive_read_data_skip(a));
830 * Extract to memory to check CRC
833 test(struct archive *a, struct archive_entry *e)
839 if (S_ISDIR(archive_entry_filetype(e)))
842 info(" testing: %s\t", archive_entry_pathname(e));
843 while ((len = archive_read_data(a, buffer, sizeof buffer)) > 0)
846 info(" %s\n", archive_error_string(a));
852 /* shouldn't be necessary, but it doesn't hurt */
853 ac(archive_read_data_skip(a));
860 * Main loop: open the zipfile, iterate over its contents and decide what
861 * to do with each entry.
864 unzip(const char *fn)
867 struct archive_entry *e;
869 uintmax_t total_size, file_count, error_count;
871 if ((a = archive_read_new()) == NULL)
872 error("archive_read_new failed");
874 ac(archive_read_support_format_zip(a));
875 ac(archive_read_open_filename(a, fn, 8192));
878 if (!p_opt && !q_opt)
879 printf("Archive: %s\n", fn);
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");
893 ret = archive_read_next_header(a, &e);
894 if (ret == ARCHIVE_EOF)
899 error_count += test(a, e);
902 else if (p_opt || c_opt)
903 extract_stdout(a, e);
911 total_size += archive_entry_size(e);
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" : "");
928 ac(archive_read_close(a));
929 (void)archive_read_finish(a);
932 if (error_count > 0) {
933 errorx("%d checksum error(s) found.", error_count);
936 printf("No errors detected in compressed data of %s.\n",
946 fprintf(stderr, "usage: unzip [-aCcfjLlnopqtuvZ1] [-d dir] [-x pattern] zipfile\n");
951 getopts(int argc, char *argv[])
955 optreset = optind = 1;
956 while ((opt = getopt(argc, argv, "aCcd:fjLlnopqtuvx:Z1")) != -1)
1009 add_pattern(&exclude, optarg);
1022 main(int argc, char *argv[])
1024 const char *zipfile;
1027 if (isatty(STDOUT_FILENO))
1030 if (getenv("UNZIP_DEBUG") != NULL)
1032 for (int i = 0; i < argc; ++i)
1033 debug("%s%c", argv[i], (i < argc - 1) ? ' ' : '\n');
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.
1041 nopts = getopts(argc, argv);
1044 * When more of the zipinfo mode options are implemented, this
1045 * will need to change.
1047 if (zipinfo_mode && !Z1_opt) {
1048 printf("Zipinfo mode needs additional options\n");
1054 zipfile = argv[nopts++];
1056 if (strcmp(zipfile, "-") == 0)
1057 zipfile = NULL; /* STDIN */
1059 while (nopts < argc && *argv[nopts] != '-')
1060 add_pattern(&include, argv[nopts++]);
1062 nopts--; /* fake argv[0] */
1063 nopts += getopts(argc - nopts, argv + nopts);
1065 if (n_opt + o_opt + u_opt > 1)
1066 errorx("-n, -o and -u are contradictory");