]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/unzip/unzip.c
Update llvm, clang and lldb to 3.7.0 release.
[FreeBSD/FreeBSD.git] / usr.bin / unzip / unzip.c
1 /*-
2  * Copyright (c) 2009 Joerg Sonnenberger <joerg@NetBSD.org>
3  * Copyright (c) 2007-2008 Dag-Erling Smørgrav
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
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.
15  *
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
26  * SUCH DAMAGE.
27  *
28  * $FreeBSD$
29  *
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
34  * options.
35  */
36
37 #include <sys/queue.h>
38 #include <sys/stat.h>
39
40 #include <ctype.h>
41 #include <errno.h>
42 #include <fcntl.h>
43 #include <fnmatch.h>
44 #include <stdarg.h>
45 #include <stdio.h>
46 #include <stdlib.h>
47 #include <string.h>
48 #include <unistd.h>
49
50 #include <archive.h>
51 #include <archive_entry.h>
52
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 */
69
70 /* debug flag */
71 static int               unzip_debug;
72
73 /* zipinfo mode */
74 static int               zipinfo_mode;
75
76 /* running on tty? */
77 static int               tty;
78
79 /* convenience macro */
80 /* XXX should differentiate between ARCHIVE_{WARN,FAIL,RETRY} */
81 #define ac(call)                                                \
82         do {                                                    \
83                 int acret = (call);                             \
84                 if (acret != ARCHIVE_OK)                        \
85                         errorx("%s", archive_error_string(a));  \
86         } while (0)
87
88 /*
89  * Indicates that last info() did not end with EOL.  This helps error() et
90  * al. avoid printing an error message on the same line as an incomplete
91  * informational message.
92  */
93 static int noeol;
94
95 /* fatal error message + errno */
96 static void
97 error(const char *fmt, ...)
98 {
99         va_list ap;
100
101         if (noeol)
102                 fprintf(stdout, "\n");
103         fflush(stdout);
104         fprintf(stderr, "unzip: ");
105         va_start(ap, fmt);
106         vfprintf(stderr, fmt, ap);
107         va_end(ap);
108         fprintf(stderr, ": %s\n", strerror(errno));
109         exit(1);
110 }
111
112 /* fatal error message, no errno */
113 static void
114 errorx(const char *fmt, ...)
115 {
116         va_list ap;
117
118         if (noeol)
119                 fprintf(stdout, "\n");
120         fflush(stdout);
121         fprintf(stderr, "unzip: ");
122         va_start(ap, fmt);
123         vfprintf(stderr, fmt, ap);
124         va_end(ap);
125         fprintf(stderr, "\n");
126         exit(1);
127 }
128
129 #if 0
130 /* non-fatal error message + errno */
131 static void
132 warning(const char *fmt, ...)
133 {
134         va_list ap;
135
136         if (noeol)
137                 fprintf(stdout, "\n");
138         fflush(stdout);
139         fprintf(stderr, "unzip: ");
140         va_start(ap, fmt);
141         vfprintf(stderr, fmt, ap);
142         va_end(ap);
143         fprintf(stderr, ": %s\n", strerror(errno));
144 }
145 #endif
146
147 /* non-fatal error message, no errno */
148 static void
149 warningx(const char *fmt, ...)
150 {
151         va_list ap;
152
153         if (noeol)
154                 fprintf(stdout, "\n");
155         fflush(stdout);
156         fprintf(stderr, "unzip: ");
157         va_start(ap, fmt);
158         vfprintf(stderr, fmt, ap);
159         va_end(ap);
160         fprintf(stderr, "\n");
161 }
162
163 /* informational message (if not -q) */
164 static void
165 info(const char *fmt, ...)
166 {
167         va_list ap;
168
169         if (q_opt && !unzip_debug)
170                 return;
171         va_start(ap, fmt);
172         vfprintf(stdout, fmt, ap);
173         va_end(ap);
174         fflush(stdout);
175
176         if (*fmt == '\0')
177                 noeol = 1;
178         else
179                 noeol = fmt[strlen(fmt) - 1] != '\n';
180 }
181
182 /* debug message (if unzip_debug) */
183 static void
184 debug(const char *fmt, ...)
185 {
186         va_list ap;
187
188         if (!unzip_debug)
189                 return;
190         va_start(ap, fmt);
191         vfprintf(stderr, fmt, ap);
192         va_end(ap);
193         fflush(stderr);
194
195         if (*fmt == '\0')
196                 noeol = 1;
197         else
198                 noeol = fmt[strlen(fmt) - 1] != '\n';
199 }
200
201 /* duplicate a path name, possibly converting to lower case */
202 static char *
203 pathdup(const char *path)
204 {
205         char *str;
206         size_t i, len;
207
208         len = strlen(path);
209         while (len && path[len - 1] == '/')
210                 len--;
211         if ((str = malloc(len + 1)) == NULL) {
212                 errno = ENOMEM;
213                 error("malloc()");
214         }
215         if (L_opt) {
216                 for (i = 0; i < len; ++i)
217                         str[i] = tolower((unsigned char)path[i]);
218         } else {
219                 memcpy(str, path, len);
220         }
221         str[len] = '\0';
222
223         return (str);
224 }
225
226 /* concatenate two path names */
227 static char *
228 pathcat(const char *prefix, const char *path)
229 {
230         char *str;
231         size_t prelen, len;
232
233         prelen = prefix ? strlen(prefix) + 1 : 0;
234         len = strlen(path) + 1;
235         if ((str = malloc(prelen + len)) == NULL) {
236                 errno = ENOMEM;
237                 error("malloc()");
238         }
239         if (prefix) {
240                 memcpy(str, prefix, prelen);    /* includes zero */
241                 str[prelen - 1] = '/';          /* splat zero */
242         }
243         memcpy(str + prelen, path, len);        /* includes zero */
244
245         return (str);
246 }
247
248 /*
249  * Pattern lists for include / exclude processing
250  */
251 struct pattern {
252         STAILQ_ENTRY(pattern) link;
253         char pattern[];
254 };
255
256 STAILQ_HEAD(pattern_list, pattern);
257 static struct pattern_list include = STAILQ_HEAD_INITIALIZER(include);
258 static struct pattern_list exclude = STAILQ_HEAD_INITIALIZER(exclude);
259
260 /*
261  * Add an entry to a pattern list
262  */
263 static void
264 add_pattern(struct pattern_list *list, const char *pattern)
265 {
266         struct pattern *entry;
267         size_t len;
268
269         debug("adding pattern '%s'\n", pattern);
270         len = strlen(pattern);
271         if ((entry = malloc(sizeof *entry + len + 1)) == NULL) {
272                 errno = ENOMEM;
273                 error("malloc()");
274         }
275         memcpy(entry->pattern, pattern, len + 1);
276         STAILQ_INSERT_TAIL(list, entry, link);
277 }
278
279 /*
280  * Match a string against a list of patterns
281  */
282 static int
283 match_pattern(struct pattern_list *list, const char *str)
284 {
285         struct pattern *entry;
286
287         STAILQ_FOREACH(entry, list, link) {
288                 if (fnmatch(entry->pattern, str, C_opt ? FNM_CASEFOLD : 0) == 0)
289                         return (1);
290         }
291         return (0);
292 }
293
294 /*
295  * Verify that a given pathname is in the include list and not in the
296  * exclude list.
297  */
298 static int
299 accept_pathname(const char *pathname)
300 {
301
302         if (!STAILQ_EMPTY(&include) && !match_pattern(&include, pathname))
303                 return (0);
304         if (!STAILQ_EMPTY(&exclude) && match_pattern(&exclude, pathname))
305                 return (0);
306         return (1);
307 }
308
309 /*
310  * Create the specified directory with the specified mode, taking certain
311  * precautions on they way.
312  */
313 static void
314 make_dir(const char *path, int mode)
315 {
316         struct stat sb;
317
318         if (lstat(path, &sb) == 0) {
319                 if (S_ISDIR(sb.st_mode))
320                         return;
321                 /*
322                  * Normally, we should either ask the user about removing
323                  * 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  */
346 static void
347 make_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  */
382 static void
383 extract_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
412 static unsigned char buffer[8192];
413 static char spinner[] = { '|', '/', '-', '\\' };
414
415 static int
416 handle_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  */
466 static void
467 extract_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 */
484 recheck:
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  */
621 static void
622 extract(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
685 static void
686 extract_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  */
800 static void
801 list(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  */
832 static int
833 test(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  */
863 static void
864 unzip(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
942 static void
943 usage(void)
944 {
945
946         fprintf(stderr, "usage: unzip [-aCcfjLlnopqtuvZ1] [-d dir] [-x pattern] zipfile\n");
947         exit(1);
948 }
949
950 static int
951 getopts(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
1021 int
1022 main(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 }