blob: a2615359a1be66b2fe1daf3ddd9ff964ab3a1d67 [file] [log] [blame]
Elliott Hughes55fd2932017-05-28 22:59:04 -07001/*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include <errno.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070018#include <fcntl.h>
Elliott Hughes5f8b3092019-04-08 12:39:20 -070019#include <fnmatch.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070020#include <getopt.h>
21#include <inttypes.h>
Elliott Hughesf1b255a2019-11-04 19:27:33 -080022#include <libgen.h>
Elliott Hughesbcd81062019-11-03 08:30:33 -080023#include <stdarg.h>
Elliott Hughes55fd2932017-05-28 22:59:04 -070024#include <stdio.h>
25#include <stdlib.h>
26#include <sys/stat.h>
27#include <sys/types.h>
28#include <time.h>
29#include <unistd.h>
30
31#include <set>
32#include <string>
33
34#include <android-base/file.h>
35#include <android-base/strings.h>
36#include <ziparchive/zip_archive.h>
37
Elliott Hughesd5095252019-10-28 21:35:52 -070038using android::base::EndsWith;
39using android::base::StartsWith;
40
Elliott Hughes55fd2932017-05-28 22:59:04 -070041enum OverwriteMode {
42 kAlways,
43 kNever,
44 kPrompt,
45};
46
Elliott Hughesd5095252019-10-28 21:35:52 -070047enum Role {
48 kUnzip,
49 kZipinfo,
50};
51
52static Role role;
Elliott Hughes55fd2932017-05-28 22:59:04 -070053static OverwriteMode overwrite_mode = kPrompt;
Elliott Hughes26724132019-10-25 09:57:58 -070054static bool flag_1 = false;
Elliott Hughesf2761402019-11-15 15:07:00 -080055static std::string flag_d;
Elliott Hughes55fd2932017-05-28 22:59:04 -070056static bool flag_l = false;
57static bool flag_p = false;
58static bool flag_q = false;
59static bool flag_v = false;
Elliott Hughes26724132019-10-25 09:57:58 -070060static bool flag_x = false;
Elliott Hughes55fd2932017-05-28 22:59:04 -070061static const char* archive_name = nullptr;
62static std::set<std::string> includes;
63static std::set<std::string> excludes;
64static uint64_t total_uncompressed_length = 0;
65static uint64_t total_compressed_length = 0;
66static size_t file_count = 0;
67
Elliott Hughesbcd81062019-11-03 08:30:33 -080068static const char* g_progname;
69
70static void die(int error, const char* fmt, ...) {
71 va_list ap;
72
73 va_start(ap, fmt);
74 fprintf(stderr, "%s: ", g_progname);
75 vfprintf(stderr, fmt, ap);
76 if (error != 0) fprintf(stderr, ": %s", strerror(error));
77 fprintf(stderr, "\n");
78 va_end(ap);
79 exit(1);
80}
81
Elliott Hughes5f8b3092019-04-08 12:39:20 -070082static bool ShouldInclude(const std::string& name) {
83 // Explicitly excluded?
84 if (!excludes.empty()) {
85 for (const auto& exclude : excludes) {
86 if (!fnmatch(exclude.c_str(), name.c_str(), 0)) return false;
87 }
88 }
89
90 // Implicitly included?
91 if (includes.empty()) return true;
92
93 // Explicitly included?
94 for (const auto& include : includes) {
95 if (!fnmatch(include.c_str(), name.c_str(), 0)) return true;
96 }
Elliott Hughes55fd2932017-05-28 22:59:04 -070097 return false;
98}
99
100static bool MakeDirectoryHierarchy(const std::string& path) {
101 // stat rather than lstat because a symbolic link to a directory is fine too.
102 struct stat sb;
103 if (stat(path.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode)) return true;
104
105 // Ensure the parent directories exist first.
106 if (!MakeDirectoryHierarchy(android::base::Dirname(path))) return false;
107
108 // Then try to create this directory.
109 return (mkdir(path.c_str(), 0777) != -1);
110}
111
Elliott Hughes00875972019-11-11 16:50:55 -0800112static float CompressionRatio(int64_t uncompressed, int64_t compressed) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700113 if (uncompressed == 0) return 0;
Nick Desaulniers4e7507f2019-11-13 13:01:48 -0800114 return static_cast<float>(100LL * (uncompressed - compressed)) /
115 static_cast<float>(uncompressed);
Elliott Hughes55fd2932017-05-28 22:59:04 -0700116}
117
Elliott Hughes26724132019-10-25 09:57:58 -0700118static void MaybeShowHeader(ZipArchiveHandle zah) {
Elliott Hughesd5095252019-10-28 21:35:52 -0700119 if (role == kUnzip) {
Elliott Hughes26724132019-10-25 09:57:58 -0700120 // unzip has three formats.
121 if (!flag_q) printf("Archive: %s\n", archive_name);
122 if (flag_v) {
123 printf(
124 " Length Method Size Cmpr Date Time CRC-32 Name\n"
125 "-------- ------ ------- ---- ---------- ----- -------- ----\n");
126 } else if (flag_l) {
127 printf(
128 " Length Date Time Name\n"
129 "--------- ---------- ----- ----\n");
130 }
131 } else {
132 // zipinfo.
133 if (!flag_1 && includes.empty() && excludes.empty()) {
134 ZipArchiveInfo info{GetArchiveInfo(zah)};
135 printf("Archive: %s\n", archive_name);
Tianjie Xu69ee4b72020-03-11 11:59:10 -0700136 printf("Zip file size: %" PRId64 " bytes, number of entries: %" PRIu64 "\n",
137 info.archive_size, info.entry_count);
Elliott Hughes26724132019-10-25 09:57:58 -0700138 }
Elliott Hughes55fd2932017-05-28 22:59:04 -0700139 }
140}
141
142static void MaybeShowFooter() {
Elliott Hughesd5095252019-10-28 21:35:52 -0700143 if (role == kUnzip) {
Elliott Hughes26724132019-10-25 09:57:58 -0700144 if (flag_v) {
145 printf(
146 "-------- ------- --- -------\n"
Elliott Hughes00875972019-11-11 16:50:55 -0800147 "%8" PRId64 " %8" PRId64 " %3.0f%% %zu file%s\n",
Elliott Hughes26724132019-10-25 09:57:58 -0700148 total_uncompressed_length, total_compressed_length,
149 CompressionRatio(total_uncompressed_length, total_compressed_length), file_count,
150 (file_count == 1) ? "" : "s");
151 } else if (flag_l) {
152 printf(
153 "--------- -------\n"
154 "%9" PRId64 " %zu file%s\n",
155 total_uncompressed_length, file_count, (file_count == 1) ? "" : "s");
156 }
157 } else {
158 if (!flag_1 && includes.empty() && excludes.empty()) {
Elliott Hughes00875972019-11-11 16:50:55 -0800159 printf("%zu files, %" PRId64 " bytes uncompressed, %" PRId64 " bytes compressed: %.1f%%\n",
Elliott Hughes26724132019-10-25 09:57:58 -0700160 file_count, total_uncompressed_length, total_compressed_length,
161 CompressionRatio(total_uncompressed_length, total_compressed_length));
162 }
Elliott Hughes55fd2932017-05-28 22:59:04 -0700163 }
164}
165
166static bool PromptOverwrite(const std::string& dst) {
167 // TODO: [r]ename not implemented because it doesn't seem useful.
168 printf("replace %s? [y]es, [n]o, [A]ll, [N]one: ", dst.c_str());
169 fflush(stdout);
170 while (true) {
171 char* line = nullptr;
172 size_t n;
173 if (getline(&line, &n, stdin) == -1) {
Elliott Hughesbcd81062019-11-03 08:30:33 -0800174 die(0, "(EOF/read error; assuming [N]one...)");
Elliott Hughes55fd2932017-05-28 22:59:04 -0700175 overwrite_mode = kNever;
176 return false;
177 }
178 if (n == 0) continue;
179 char cmd = line[0];
180 free(line);
181 switch (cmd) {
182 case 'y':
183 return true;
184 case 'n':
185 return false;
186 case 'A':
187 overwrite_mode = kAlways;
188 return true;
189 case 'N':
190 overwrite_mode = kNever;
191 return false;
192 }
193 }
194}
195
Tianjie85c5d232020-04-01 23:08:34 -0700196static void ExtractToPipe(ZipArchiveHandle zah, const ZipEntry64& entry, const std::string& name) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700197 // We need to extract to memory because ExtractEntryToFile insists on
198 // being able to seek and truncate, and you can't do that with stdout.
Tianjie85c5d232020-04-01 23:08:34 -0700199 if (entry.uncompressed_length > SIZE_MAX) {
200 die(0, "entry size %" PRIu64 " is too large to extract.", entry.uncompressed_length);
201 }
202 auto uncompressed_length = static_cast<size_t>(entry.uncompressed_length);
203 uint8_t* buffer = new uint8_t[uncompressed_length];
204 int err = ExtractToMemory(zah, &entry, buffer, uncompressed_length);
Elliott Hughes55fd2932017-05-28 22:59:04 -0700205 if (err < 0) {
Elliott Hughesbcd81062019-11-03 08:30:33 -0800206 die(0, "failed to extract %s: %s", name.c_str(), ErrorCodeString(err));
Elliott Hughes55fd2932017-05-28 22:59:04 -0700207 }
Tianjie85c5d232020-04-01 23:08:34 -0700208 if (!android::base::WriteFully(1, buffer, uncompressed_length)) {
Elliott Hughesbcd81062019-11-03 08:30:33 -0800209 die(errno, "failed to write %s to stdout", name.c_str());
Elliott Hughes55fd2932017-05-28 22:59:04 -0700210 }
211 delete[] buffer;
212}
213
Tianjie85c5d232020-04-01 23:08:34 -0700214static void ExtractOne(ZipArchiveHandle zah, const ZipEntry64& entry, const std::string& name) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700215 // Bad filename?
Elliott Hughesd5095252019-10-28 21:35:52 -0700216 if (StartsWith(name, "/") || StartsWith(name, "../") || name.find("/../") != std::string::npos) {
Elliott Hughesbcd81062019-11-03 08:30:33 -0800217 die(0, "bad filename %s", name.c_str());
Elliott Hughes55fd2932017-05-28 22:59:04 -0700218 }
219
220 // Where are we actually extracting to (for human-readable output)?
Elliott Hughesf2761402019-11-15 15:07:00 -0800221 // flag_d is the empty string if -d wasn't used, or has a trailing '/'
222 // otherwise.
223 std::string dst = flag_d + name;
Elliott Hughes55fd2932017-05-28 22:59:04 -0700224
225 // Ensure the directory hierarchy exists.
226 if (!MakeDirectoryHierarchy(android::base::Dirname(name))) {
Elliott Hughesbcd81062019-11-03 08:30:33 -0800227 die(errno, "couldn't create directory hierarchy for %s", dst.c_str());
Elliott Hughes55fd2932017-05-28 22:59:04 -0700228 }
229
230 // An entry in a zip file can just be a directory itself.
Elliott Hughesd5095252019-10-28 21:35:52 -0700231 if (EndsWith(name, "/")) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700232 if (mkdir(name.c_str(), entry.unix_mode) == -1) {
233 // If the directory already exists, that's fine.
234 if (errno == EEXIST) {
235 struct stat sb;
236 if (stat(name.c_str(), &sb) != -1 && S_ISDIR(sb.st_mode)) return;
237 }
Elliott Hughesbcd81062019-11-03 08:30:33 -0800238 die(errno, "couldn't extract directory %s", dst.c_str());
Elliott Hughes55fd2932017-05-28 22:59:04 -0700239 }
240 return;
241 }
242
243 // Create the file.
244 int fd = open(name.c_str(), O_CREAT | O_WRONLY | O_CLOEXEC | O_EXCL, entry.unix_mode);
245 if (fd == -1 && errno == EEXIST) {
246 if (overwrite_mode == kNever) return;
247 if (overwrite_mode == kPrompt && !PromptOverwrite(dst)) return;
248 // Either overwrite_mode is kAlways or the user consented to this specific case.
249 fd = open(name.c_str(), O_WRONLY | O_CREAT | O_CLOEXEC | O_TRUNC, entry.unix_mode);
250 }
Elliott Hughesbcd81062019-11-03 08:30:33 -0800251 if (fd == -1) die(errno, "couldn't create file %s", dst.c_str());
Elliott Hughes55fd2932017-05-28 22:59:04 -0700252
253 // Actually extract into the file.
254 if (!flag_q) printf(" inflating: %s\n", dst.c_str());
255 int err = ExtractEntryToFile(zah, &entry, fd);
Elliott Hughesbcd81062019-11-03 08:30:33 -0800256 if (err < 0) die(0, "failed to extract %s: %s", dst.c_str(), ErrorCodeString(err));
Elliott Hughes55fd2932017-05-28 22:59:04 -0700257 close(fd);
258}
259
Tianjie85c5d232020-04-01 23:08:34 -0700260static void ListOne(const ZipEntry64& entry, const std::string& name) {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700261 tm t = entry.GetModificationTime();
262 char time[32];
263 snprintf(time, sizeof(time), "%04d-%02d-%02d %02d:%02d", t.tm_year + 1900, t.tm_mon + 1,
264 t.tm_mday, t.tm_hour, t.tm_min);
265 if (flag_v) {
Elliott Hughes6f591352020-04-17 16:01:16 -0700266 printf("%8" PRIu64 " %s %8" PRIu64 " %3.0f%% %s %08x %s\n", entry.uncompressed_length,
Elliott Hughes55fd2932017-05-28 22:59:04 -0700267 (entry.method == kCompressStored) ? "Stored" : "Defl:N", entry.compressed_length,
268 CompressionRatio(entry.uncompressed_length, entry.compressed_length), time, entry.crc32,
269 name.c_str());
270 } else {
Elliott Hughes6f591352020-04-17 16:01:16 -0700271 printf("%9" PRIu64 " %s %s\n", entry.uncompressed_length, time, name.c_str());
Elliott Hughes55fd2932017-05-28 22:59:04 -0700272 }
273}
274
Tianjie85c5d232020-04-01 23:08:34 -0700275static void InfoOne(const ZipEntry64& entry, const std::string& name) {
Elliott Hughes26724132019-10-25 09:57:58 -0700276 if (flag_1) {
277 // "android-ndk-r19b/sources/android/NOTICE"
278 printf("%s\n", name.c_str());
279 return;
280 }
281
282 int version = entry.version_made_by & 0xff;
283 int os = (entry.version_made_by >> 8) & 0xff;
284
Elliott Hughesd5095252019-10-28 21:35:52 -0700285 // TODO: Support suid/sgid? Non-Unix/non-FAT host file system attributes?
286 const char* src_fs = "???";
287 char mode[] = "??? ";
288 if (os == 0) {
289 src_fs = "fat";
290 // https://docs.microsoft.com/en-us/windows/win32/fileio/file-attribute-constants
291 int attrs = entry.external_file_attributes & 0xff;
292 mode[0] = (attrs & 0x10) ? 'd' : '-';
293 mode[1] = 'r';
294 mode[2] = (attrs & 0x01) ? '-' : 'w';
295 // The man page also mentions ".btm", but that seems to be obsolete?
296 mode[3] = EndsWith(name, ".exe") || EndsWith(name, ".com") || EndsWith(name, ".bat") ||
297 EndsWith(name, ".cmd")
298 ? 'x'
299 : '-';
300 mode[4] = (attrs & 0x20) ? 'a' : '-';
301 mode[5] = (attrs & 0x02) ? 'h' : '-';
302 mode[6] = (attrs & 0x04) ? 's' : '-';
303 } else if (os == 3) {
304 src_fs = "unx";
Elliott Hughes26724132019-10-25 09:57:58 -0700305 mode[0] = S_ISDIR(entry.unix_mode) ? 'd' : (S_ISREG(entry.unix_mode) ? '-' : '?');
306 mode[1] = entry.unix_mode & S_IRUSR ? 'r' : '-';
307 mode[2] = entry.unix_mode & S_IWUSR ? 'w' : '-';
308 mode[3] = entry.unix_mode & S_IXUSR ? 'x' : '-';
309 mode[4] = entry.unix_mode & S_IRGRP ? 'r' : '-';
310 mode[5] = entry.unix_mode & S_IWGRP ? 'w' : '-';
311 mode[6] = entry.unix_mode & S_IXGRP ? 'x' : '-';
312 mode[7] = entry.unix_mode & S_IROTH ? 'r' : '-';
313 mode[8] = entry.unix_mode & S_IWOTH ? 'w' : '-';
314 mode[9] = entry.unix_mode & S_IXOTH ? 'x' : '-';
315 }
316
Elliott Hughesd5095252019-10-28 21:35:52 -0700317 char method[5] = "stor";
318 if (entry.method == kCompressDeflated) {
319 snprintf(method, sizeof(method), "def%c", "NXFS"[(entry.gpbf >> 1) & 0x3]);
320 }
321
Elliott Hughes26724132019-10-25 09:57:58 -0700322 // TODO: zipinfo (unlike unzip) sometimes uses time zone?
323 // TODO: this uses 4-digit years because we're not barbarians unless interoperability forces it.
324 tm t = entry.GetModificationTime();
325 char time[32];
326 snprintf(time, sizeof(time), "%04d-%02d-%02d %02d:%02d", t.tm_year + 1900, t.tm_mon + 1,
327 t.tm_mday, t.tm_hour, t.tm_min);
328
329 // "-rw-r--r-- 3.0 unx 577 t- defX 19-Feb-12 16:09 android-ndk-r19b/sources/android/NOTICE"
Tianjie85c5d232020-04-01 23:08:34 -0700330 printf("%s %2d.%d %s %8" PRIu64 " %c%c %s %s %s\n", mode, version / 10, version % 10, src_fs,
Elliott Hughesd5095252019-10-28 21:35:52 -0700331 entry.uncompressed_length, entry.is_text ? 't' : 'b',
332 entry.has_data_descriptor ? 'X' : 'x', method, time, name.c_str());
Elliott Hughes26724132019-10-25 09:57:58 -0700333}
334
Tianjie85c5d232020-04-01 23:08:34 -0700335static void ProcessOne(ZipArchiveHandle zah, const ZipEntry64& entry, const std::string& name) {
Elliott Hughesd5095252019-10-28 21:35:52 -0700336 if (role == kUnzip) {
Elliott Hughes26724132019-10-25 09:57:58 -0700337 if (flag_l || flag_v) {
338 // -l or -lv or -lq or -v.
339 ListOne(entry, name);
Elliott Hughes55fd2932017-05-28 22:59:04 -0700340 } else {
Elliott Hughes26724132019-10-25 09:57:58 -0700341 // Actually extract.
342 if (flag_p) {
343 ExtractToPipe(zah, entry, name);
344 } else {
345 ExtractOne(zah, entry, name);
346 }
Elliott Hughes55fd2932017-05-28 22:59:04 -0700347 }
Elliott Hughes26724132019-10-25 09:57:58 -0700348 } else {
349 // zipinfo or zipinfo -1.
350 InfoOne(entry, name);
Elliott Hughes55fd2932017-05-28 22:59:04 -0700351 }
352 total_uncompressed_length += entry.uncompressed_length;
353 total_compressed_length += entry.compressed_length;
354 ++file_count;
355}
356
357static void ProcessAll(ZipArchiveHandle zah) {
Elliott Hughes26724132019-10-25 09:57:58 -0700358 MaybeShowHeader(zah);
Elliott Hughes55fd2932017-05-28 22:59:04 -0700359
360 // libziparchive iteration order doesn't match the central directory.
361 // We could sort, but that would cost extra and wouldn't match either.
362 void* cookie;
Elliott Hughesa22ac0f2019-05-08 10:44:06 -0700363 int err = StartIteration(zah, &cookie);
Elliott Hughes55fd2932017-05-28 22:59:04 -0700364 if (err != 0) {
Elliott Hughesbcd81062019-11-03 08:30:33 -0800365 die(0, "couldn't iterate %s: %s", archive_name, ErrorCodeString(err));
Elliott Hughes55fd2932017-05-28 22:59:04 -0700366 }
367
Tianjie85c5d232020-04-01 23:08:34 -0700368 ZipEntry64 entry;
Elliott Hughese06a8082019-05-22 18:56:41 -0700369 std::string name;
370 while ((err = Next(cookie, &entry, &name)) >= 0) {
Elliott Hughes5f8b3092019-04-08 12:39:20 -0700371 if (ShouldInclude(name)) ProcessOne(zah, entry, name);
Elliott Hughes55fd2932017-05-28 22:59:04 -0700372 }
373
Elliott Hughesbcd81062019-11-03 08:30:33 -0800374 if (err < -1) die(0, "failed iterating %s: %s", archive_name, ErrorCodeString(err));
Elliott Hughes55fd2932017-05-28 22:59:04 -0700375 EndIteration(cookie);
376
377 MaybeShowFooter();
378}
379
380static void ShowHelp(bool full) {
Elliott Hughesd5095252019-10-28 21:35:52 -0700381 if (role == kUnzip) {
Elliott Hughes26724132019-10-25 09:57:58 -0700382 fprintf(full ? stdout : stderr, "usage: unzip [-d DIR] [-lnopqv] ZIP [FILE...] [-x FILE...]\n");
383 if (!full) exit(EXIT_FAILURE);
Elliott Hughes55fd2932017-05-28 22:59:04 -0700384
Elliott Hughes26724132019-10-25 09:57:58 -0700385 printf(
386 "\n"
387 "Extract FILEs from ZIP archive. Default is all files. Both the include and\n"
388 "exclude (-x) lists use shell glob patterns.\n"
389 "\n"
390 "-d DIR Extract into DIR\n"
391 "-l List contents (-lq excludes archive name, -lv is verbose)\n"
392 "-n Never overwrite files (default: prompt)\n"
393 "-o Always overwrite files\n"
394 "-p Pipe to stdout\n"
395 "-q Quiet\n"
396 "-v List contents verbosely\n"
397 "-x FILE Exclude files\n");
398 } else {
399 fprintf(full ? stdout : stderr, "usage: zipinfo [-1] ZIP [FILE...] [-x FILE...]\n");
400 if (!full) exit(EXIT_FAILURE);
401
402 printf(
403 "\n"
404 "Show information about FILEs from ZIP archive. Default is all files.\n"
405 "Both the include and exclude (-x) lists use shell glob patterns.\n"
406 "\n"
407 "-1 Show filenames only, one per line\n"
408 "-x FILE Exclude files\n");
409 }
Elliott Hughes55fd2932017-05-28 22:59:04 -0700410 exit(EXIT_SUCCESS);
411}
412
Elliott Hughes26724132019-10-25 09:57:58 -0700413static void HandleCommonOption(int opt) {
414 switch (opt) {
415 case 'h':
416 ShowHelp(true);
417 break;
418 case 'x':
419 flag_x = true;
420 break;
421 case 1:
422 // -x swallows all following arguments, so we use '-' in the getopt
423 // string and collect files here.
424 if (!archive_name) {
425 archive_name = optarg;
426 } else if (flag_x) {
427 excludes.insert(optarg);
428 } else {
429 includes.insert(optarg);
430 }
431 break;
432 default:
433 ShowHelp(false);
434 break;
435 }
436}
437
Elliott Hughes55fd2932017-05-28 22:59:04 -0700438int main(int argc, char* argv[]) {
Elliott Hughesd5095252019-10-28 21:35:52 -0700439 // Who am I, and what am I doing?
Elliott Hughesbcd81062019-11-03 08:30:33 -0800440 g_progname = basename(argv[0]);
441 if (!strcmp(g_progname, "ziptool") && argc > 1) return main(argc - 1, argv + 1);
442 if (!strcmp(g_progname, "unzip")) {
Elliott Hughesd5095252019-10-28 21:35:52 -0700443 role = kUnzip;
Elliott Hughesbcd81062019-11-03 08:30:33 -0800444 } else if (!strcmp(g_progname, "zipinfo")) {
Elliott Hughesd5095252019-10-28 21:35:52 -0700445 role = kZipinfo;
446 } else {
Elliott Hughesbcd81062019-11-03 08:30:33 -0800447 die(0, "run as ziptool with unzip or zipinfo as the first argument, or symlink");
Elliott Hughesd5095252019-10-28 21:35:52 -0700448 }
449
450 static const struct option opts[] = {
Elliott Hughes55fd2932017-05-28 22:59:04 -0700451 {"help", no_argument, 0, 'h'},
Elliott Hughes2ab5a702019-11-16 11:18:50 -0800452 {},
Elliott Hughes55fd2932017-05-28 22:59:04 -0700453 };
Elliott Hughes26724132019-10-25 09:57:58 -0700454
Elliott Hughesd5095252019-10-28 21:35:52 -0700455 if (role == kUnzip) {
Elliott Hughesd3aee662019-10-29 20:47:16 -0700456 // `unzip -Z` is "zipinfo mode", so in that case just restart...
457 if (argc > 1 && !strcmp(argv[1], "-Z")) {
458 argv[1] = const_cast<char*>("zipinfo");
459 return main(argc - 1, argv + 1);
460 }
461
Elliott Hughes26724132019-10-25 09:57:58 -0700462 int opt;
463 while ((opt = getopt_long(argc, argv, "-d:hlnopqvx", opts, nullptr)) != -1) {
464 switch (opt) {
465 case 'd':
466 flag_d = optarg;
Elliott Hughesf2761402019-11-15 15:07:00 -0800467 if (!EndsWith(flag_d, "/")) flag_d += '/';
Elliott Hughes26724132019-10-25 09:57:58 -0700468 break;
469 case 'l':
470 flag_l = true;
471 break;
472 case 'n':
473 overwrite_mode = kNever;
474 break;
475 case 'o':
476 overwrite_mode = kAlways;
477 break;
478 case 'p':
479 flag_p = flag_q = true;
480 break;
481 case 'q':
482 flag_q = true;
483 break;
484 case 'v':
485 flag_v = true;
486 break;
487 default:
488 HandleCommonOption(opt);
489 break;
490 }
491 }
492 } else {
493 int opt;
494 while ((opt = getopt_long(argc, argv, "-1hx", opts, nullptr)) != -1) {
495 switch (opt) {
496 case '1':
497 flag_1 = true;
498 break;
499 default:
500 HandleCommonOption(opt);
501 break;
502 }
Elliott Hughes55fd2932017-05-28 22:59:04 -0700503 }
504 }
505
Elliott Hughesbcd81062019-11-03 08:30:33 -0800506 if (!archive_name) die(0, "missing archive filename");
Elliott Hughes55fd2932017-05-28 22:59:04 -0700507
508 // We can't support "-" to unzip from stdin because libziparchive relies on mmap.
509 ZipArchiveHandle zah;
510 int32_t err;
511 if ((err = OpenArchive(archive_name, &zah)) != 0) {
Elliott Hughesbcd81062019-11-03 08:30:33 -0800512 die(0, "couldn't open %s: %s", archive_name, ErrorCodeString(err));
Elliott Hughes55fd2932017-05-28 22:59:04 -0700513 }
514
515 // Implement -d by changing into that directory.
Elliott Hughesf2761402019-11-15 15:07:00 -0800516 // We'll create implicit directories based on paths in the zip file, and we'll create
517 // the -d directory itself, but we require that *parents* of the -d directory already exists.
518 // This is pretty arbitrary, but it's the behavior of the original unzip.
519 if (!flag_d.empty()) {
520 if (mkdir(flag_d.c_str(), 0777) == -1 && errno != EEXIST) {
521 die(errno, "couldn't created %s", flag_d.c_str());
522 }
523 if (chdir(flag_d.c_str()) == -1) {
524 die(errno, "couldn't chdir to %s", flag_d.c_str());
525 }
526 }
Elliott Hughes55fd2932017-05-28 22:59:04 -0700527
528 ProcessAll(zah);
529
530 CloseArchive(zah);
531 return 0;
532}