unzip.c 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini unzip implementation for busybox
  4. *
  5. * Copyright (C) 2004 by Ed Clark
  6. *
  7. * Loosely based on original busybox unzip applet by Laurence Anderson.
  8. * All options and features should work in this version.
  9. *
  10. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  11. */
  12. /* For reference see
  13. * http://www.pkware.com/company/standards/appnote/
  14. * http://www.info-zip.org/pub/infozip/doc/appnote-iz-latest.zip
  15. *
  16. * TODO
  17. * Zip64 + other methods
  18. */
  19. //config:config UNZIP
  20. //config: bool "unzip"
  21. //config: default y
  22. //config: help
  23. //config: unzip will list or extract files from a ZIP archive,
  24. //config: commonly found on DOS/WIN systems. The default behavior
  25. //config: (with no options) is to extract the archive into the
  26. //config: current directory. Use the `-d' option to extract to a
  27. //config: directory of your choice.
  28. //applet:IF_UNZIP(APPLET(unzip, BB_DIR_USR_BIN, BB_SUID_DROP))
  29. //kbuild:lib-$(CONFIG_UNZIP) += unzip.o
  30. //usage:#define unzip_trivial_usage
  31. //usage: "[-lnopq] FILE[.zip] [FILE]... [-x FILE...] [-d DIR]"
  32. //usage:#define unzip_full_usage "\n\n"
  33. //usage: "Extract FILEs from ZIP archive\n"
  34. //usage: "\n -l List contents (with -q for short form)"
  35. //usage: "\n -n Never overwrite files (default: ask)"
  36. //usage: "\n -o Overwrite"
  37. //usage: "\n -p Print to stdout"
  38. //usage: "\n -q Quiet"
  39. //usage: "\n -x FILE Exclude FILEs"
  40. //usage: "\n -d DIR Extract into DIR"
  41. #include "libbb.h"
  42. #include "bb_archive.h"
  43. #if 0
  44. # define dbg(...) bb_error_msg(__VA_ARGS__)
  45. #else
  46. # define dbg(...) ((void)0)
  47. #endif
  48. enum {
  49. #if BB_BIG_ENDIAN
  50. ZIP_FILEHEADER_MAGIC = 0x504b0304,
  51. ZIP_CDF_MAGIC = 0x504b0102, /* central directory's file header */
  52. ZIP_CDE_MAGIC = 0x504b0506, /* "end of central directory" record */
  53. ZIP_DD_MAGIC = 0x504b0708,
  54. #else
  55. ZIP_FILEHEADER_MAGIC = 0x04034b50,
  56. ZIP_CDF_MAGIC = 0x02014b50,
  57. ZIP_CDE_MAGIC = 0x06054b50,
  58. ZIP_DD_MAGIC = 0x08074b50,
  59. #endif
  60. };
  61. #define ZIP_HEADER_LEN 26
  62. typedef union {
  63. uint8_t raw[ZIP_HEADER_LEN];
  64. struct {
  65. uint16_t version; /* 0-1 */
  66. uint16_t zip_flags; /* 2-3 */
  67. uint16_t method; /* 4-5 */
  68. uint16_t modtime; /* 6-7 */
  69. uint16_t moddate; /* 8-9 */
  70. uint32_t crc32 PACKED; /* 10-13 */
  71. uint32_t cmpsize PACKED; /* 14-17 */
  72. uint32_t ucmpsize PACKED; /* 18-21 */
  73. uint16_t filename_len; /* 22-23 */
  74. uint16_t extra_len; /* 24-25 */
  75. } formatted PACKED;
  76. } zip_header_t; /* PACKED - gcc 4.2.1 doesn't like it (spews warning) */
  77. /* Check the offset of the last element, not the length. This leniency
  78. * allows for poor packing, whereby the overall struct may be too long,
  79. * even though the elements are all in the right place.
  80. */
  81. struct BUG_zip_header_must_be_26_bytes {
  82. char BUG_zip_header_must_be_26_bytes[
  83. offsetof(zip_header_t, formatted.extra_len) + 2
  84. == ZIP_HEADER_LEN ? 1 : -1];
  85. };
  86. #define FIX_ENDIANNESS_ZIP(zip_header) do { \
  87. (zip_header).formatted.version = SWAP_LE16((zip_header).formatted.version ); \
  88. (zip_header).formatted.method = SWAP_LE16((zip_header).formatted.method ); \
  89. (zip_header).formatted.modtime = SWAP_LE16((zip_header).formatted.modtime ); \
  90. (zip_header).formatted.moddate = SWAP_LE16((zip_header).formatted.moddate ); \
  91. (zip_header).formatted.crc32 = SWAP_LE32((zip_header).formatted.crc32 ); \
  92. (zip_header).formatted.cmpsize = SWAP_LE32((zip_header).formatted.cmpsize ); \
  93. (zip_header).formatted.ucmpsize = SWAP_LE32((zip_header).formatted.ucmpsize ); \
  94. (zip_header).formatted.filename_len = SWAP_LE16((zip_header).formatted.filename_len); \
  95. (zip_header).formatted.extra_len = SWAP_LE16((zip_header).formatted.extra_len ); \
  96. } while (0)
  97. #define CDF_HEADER_LEN 42
  98. typedef union {
  99. uint8_t raw[CDF_HEADER_LEN];
  100. struct {
  101. /* uint32_t signature; 50 4b 01 02 */
  102. uint16_t version_made_by; /* 0-1 */
  103. uint16_t version_needed; /* 2-3 */
  104. uint16_t cdf_flags; /* 4-5 */
  105. uint16_t method; /* 6-7 */
  106. uint16_t mtime; /* 8-9 */
  107. uint16_t mdate; /* 10-11 */
  108. uint32_t crc32; /* 12-15 */
  109. uint32_t cmpsize; /* 16-19 */
  110. uint32_t ucmpsize; /* 20-23 */
  111. uint16_t file_name_length; /* 24-25 */
  112. uint16_t extra_field_length; /* 26-27 */
  113. uint16_t file_comment_length; /* 28-29 */
  114. uint16_t disk_number_start; /* 30-31 */
  115. uint16_t internal_file_attributes; /* 32-33 */
  116. uint32_t external_file_attributes PACKED; /* 34-37 */
  117. uint32_t relative_offset_of_local_header PACKED; /* 38-41 */
  118. } formatted PACKED;
  119. } cdf_header_t;
  120. struct BUG_cdf_header_must_be_42_bytes {
  121. char BUG_cdf_header_must_be_42_bytes[
  122. offsetof(cdf_header_t, formatted.relative_offset_of_local_header) + 4
  123. == CDF_HEADER_LEN ? 1 : -1];
  124. };
  125. #define FIX_ENDIANNESS_CDF(cdf_header) do { \
  126. (cdf_header).formatted.crc32 = SWAP_LE32((cdf_header).formatted.crc32 ); \
  127. (cdf_header).formatted.cmpsize = SWAP_LE32((cdf_header).formatted.cmpsize ); \
  128. (cdf_header).formatted.ucmpsize = SWAP_LE32((cdf_header).formatted.ucmpsize ); \
  129. (cdf_header).formatted.file_name_length = SWAP_LE16((cdf_header).formatted.file_name_length); \
  130. (cdf_header).formatted.extra_field_length = SWAP_LE16((cdf_header).formatted.extra_field_length); \
  131. (cdf_header).formatted.file_comment_length = SWAP_LE16((cdf_header).formatted.file_comment_length); \
  132. IF_DESKTOP( \
  133. (cdf_header).formatted.version_made_by = SWAP_LE16((cdf_header).formatted.version_made_by); \
  134. (cdf_header).formatted.external_file_attributes = SWAP_LE32((cdf_header).formatted.external_file_attributes); \
  135. ) \
  136. } while (0)
  137. #define CDE_HEADER_LEN 16
  138. typedef union {
  139. uint8_t raw[CDE_HEADER_LEN];
  140. struct {
  141. /* uint32_t signature; 50 4b 05 06 */
  142. uint16_t this_disk_no;
  143. uint16_t disk_with_cdf_no;
  144. uint16_t cdf_entries_on_this_disk;
  145. uint16_t cdf_entries_total;
  146. uint32_t cdf_size;
  147. uint32_t cdf_offset;
  148. /* uint16_t file_comment_length; */
  149. /* .ZIP file comment (variable size) */
  150. } formatted PACKED;
  151. } cde_header_t;
  152. struct BUG_cde_header_must_be_16_bytes {
  153. char BUG_cde_header_must_be_16_bytes[
  154. sizeof(cde_header_t) == CDE_HEADER_LEN ? 1 : -1];
  155. };
  156. #define FIX_ENDIANNESS_CDE(cde_header) do { \
  157. (cde_header).formatted.cdf_offset = SWAP_LE32((cde_header).formatted.cdf_offset); \
  158. } while (0)
  159. enum { zip_fd = 3 };
  160. #if ENABLE_DESKTOP
  161. /* Seen in the wild:
  162. * Self-extracting PRO2K3XP_32.exe contains 19078464 byte zip archive,
  163. * where CDE was nearly 48 kbytes before EOF.
  164. * (Surprisingly, it also apparently has *another* CDE structure
  165. * closer to the end, with bogus cdf_offset).
  166. * To make extraction work, bumped PEEK_FROM_END from 16k to 64k.
  167. */
  168. #define PEEK_FROM_END (64*1024)
  169. /* This value means that we failed to find CDF */
  170. #define BAD_CDF_OFFSET ((uint32_t)0xffffffff)
  171. /* NB: does not preserve file position! */
  172. static uint32_t find_cdf_offset(void)
  173. {
  174. cde_header_t cde_header;
  175. unsigned char *p;
  176. off_t end;
  177. unsigned char *buf = xzalloc(PEEK_FROM_END);
  178. uint32_t found;
  179. end = xlseek(zip_fd, 0, SEEK_END);
  180. end -= PEEK_FROM_END;
  181. if (end < 0)
  182. end = 0;
  183. dbg("Looking for cdf_offset starting from 0x%"OFF_FMT"x", end);
  184. xlseek(zip_fd, end, SEEK_SET);
  185. full_read(zip_fd, buf, PEEK_FROM_END);
  186. found = BAD_CDF_OFFSET;
  187. p = buf;
  188. while (p <= buf + PEEK_FROM_END - CDE_HEADER_LEN - 4) {
  189. if (*p != 'P') {
  190. p++;
  191. continue;
  192. }
  193. if (*++p != 'K')
  194. continue;
  195. if (*++p != 5)
  196. continue;
  197. if (*++p != 6)
  198. continue;
  199. /* we found CDE! */
  200. memcpy(cde_header.raw, p + 1, CDE_HEADER_LEN);
  201. FIX_ENDIANNESS_CDE(cde_header);
  202. /*
  203. * I've seen .ZIP files with seemingly valid CDEs
  204. * where cdf_offset points past EOF - ??
  205. * This check ignores such CDEs:
  206. */
  207. if (cde_header.formatted.cdf_offset < end + (p - buf)) {
  208. found = cde_header.formatted.cdf_offset;
  209. dbg("Possible cdf_offset:0x%x at 0x%"OFF_FMT"x",
  210. (unsigned)found, end + (p-3 - buf));
  211. dbg(" cdf_offset+cdf_size:0x%x",
  212. (unsigned)(found + SWAP_LE32(cde_header.formatted.cdf_size)));
  213. /*
  214. * We do not "break" here because only the last CDE is valid.
  215. * I've seen a .zip archive which contained a .zip file,
  216. * uncompressed, and taking the first CDE was using
  217. * the CDE inside that file!
  218. */
  219. }
  220. }
  221. free(buf);
  222. dbg("Found cdf_offset:0x%x", (unsigned)found);
  223. return found;
  224. };
  225. static uint32_t read_next_cdf(uint32_t cdf_offset, cdf_header_t *cdf_ptr)
  226. {
  227. off_t org;
  228. org = xlseek(zip_fd, 0, SEEK_CUR);
  229. if (!cdf_offset)
  230. cdf_offset = find_cdf_offset();
  231. if (cdf_offset != BAD_CDF_OFFSET) {
  232. dbg("Reading CDF at 0x%x", (unsigned)cdf_offset);
  233. xlseek(zip_fd, cdf_offset + 4, SEEK_SET);
  234. xread(zip_fd, cdf_ptr->raw, CDF_HEADER_LEN);
  235. FIX_ENDIANNESS_CDF(*cdf_ptr);
  236. dbg(" file_name_length:%u extra_field_length:%u file_comment_length:%u",
  237. (unsigned)cdf_ptr->formatted.file_name_length,
  238. (unsigned)cdf_ptr->formatted.extra_field_length,
  239. (unsigned)cdf_ptr->formatted.file_comment_length
  240. );
  241. cdf_offset += 4 + CDF_HEADER_LEN
  242. + cdf_ptr->formatted.file_name_length
  243. + cdf_ptr->formatted.extra_field_length
  244. + cdf_ptr->formatted.file_comment_length;
  245. }
  246. dbg("Returning file position to 0x%"OFF_FMT"x", org);
  247. xlseek(zip_fd, org, SEEK_SET);
  248. return cdf_offset;
  249. };
  250. #endif
  251. static void unzip_skip(off_t skip)
  252. {
  253. if (skip != 0)
  254. if (lseek(zip_fd, skip, SEEK_CUR) == (off_t)-1)
  255. bb_copyfd_exact_size(zip_fd, -1, skip);
  256. }
  257. static void unzip_create_leading_dirs(const char *fn)
  258. {
  259. /* Create all leading directories */
  260. char *name = xstrdup(fn);
  261. if (bb_make_directory(dirname(name), 0777, FILEUTILS_RECUR)) {
  262. xfunc_die(); /* bb_make_directory is noisy */
  263. }
  264. free(name);
  265. }
  266. static void unzip_extract(zip_header_t *zip_header, int dst_fd)
  267. {
  268. if (zip_header->formatted.method == 0) {
  269. /* Method 0 - stored (not compressed) */
  270. off_t size = zip_header->formatted.ucmpsize;
  271. if (size)
  272. bb_copyfd_exact_size(zip_fd, dst_fd, size);
  273. } else {
  274. /* Method 8 - inflate */
  275. transformer_state_t xstate;
  276. init_transformer_state(&xstate);
  277. xstate.bytes_in = zip_header->formatted.cmpsize;
  278. xstate.src_fd = zip_fd;
  279. xstate.dst_fd = dst_fd;
  280. if (inflate_unzip(&xstate) < 0)
  281. bb_error_msg_and_die("inflate error");
  282. /* Validate decompression - crc */
  283. if (zip_header->formatted.crc32 != (xstate.crc32 ^ 0xffffffffL)) {
  284. bb_error_msg_and_die("crc error");
  285. }
  286. /* Validate decompression - size */
  287. if (zip_header->formatted.ucmpsize != xstate.bytes_out) {
  288. /* Don't die. Who knows, maybe len calculation
  289. * was botched somewhere. After all, crc matched! */
  290. bb_error_msg("bad length");
  291. }
  292. }
  293. }
  294. static void my_fgets80(char *buf80)
  295. {
  296. fflush_all();
  297. if (!fgets(buf80, 80, stdin)) {
  298. bb_perror_msg_and_die("can't read standard input");
  299. }
  300. }
  301. int unzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  302. int unzip_main(int argc, char **argv)
  303. {
  304. enum { O_PROMPT, O_NEVER, O_ALWAYS };
  305. zip_header_t zip_header;
  306. smallint quiet = 0;
  307. IF_NOT_DESKTOP(const) smallint verbose = 0;
  308. smallint listing = 0;
  309. smallint overwrite = O_PROMPT;
  310. smallint x_opt_seen;
  311. #if ENABLE_DESKTOP
  312. uint32_t cdf_offset;
  313. #endif
  314. unsigned long total_usize;
  315. unsigned long total_size;
  316. unsigned total_entries;
  317. int dst_fd = -1;
  318. char *src_fn = NULL;
  319. char *dst_fn = NULL;
  320. llist_t *zaccept = NULL;
  321. llist_t *zreject = NULL;
  322. char *base_dir = NULL;
  323. int i, opt;
  324. char key_buf[80]; /* must match size used by my_fgets80 */
  325. struct stat stat_buf;
  326. /* -q, -l and -v: UnZip 5.52 of 28 February 2005, by Info-ZIP:
  327. *
  328. * # /usr/bin/unzip -qq -v decompress_unlzma.i.zip
  329. * 204372 Defl:N 35278 83% 09-06-09 14:23 0d056252 decompress_unlzma.i
  330. * # /usr/bin/unzip -q -v decompress_unlzma.i.zip
  331. * Length Method Size Ratio Date Time CRC-32 Name
  332. * -------- ------ ------- ----- ---- ---- ------ ----
  333. * 204372 Defl:N 35278 83% 09-06-09 14:23 0d056252 decompress_unlzma.i
  334. * -------- ------- --- -------
  335. * 204372 35278 83% 1 file
  336. * # /usr/bin/unzip -v decompress_unlzma.i.zip
  337. * Archive: decompress_unlzma.i.zip
  338. * Length Method Size Ratio Date Time CRC-32 Name
  339. * -------- ------ ------- ----- ---- ---- ------ ----
  340. * 204372 Defl:N 35278 83% 09-06-09 14:23 0d056252 decompress_unlzma.i
  341. * -------- ------- --- -------
  342. * 204372 35278 83% 1 file
  343. * # unzip -v decompress_unlzma.i.zip
  344. * Archive: decompress_unlzma.i.zip
  345. * Length Date Time Name
  346. * -------- ---- ---- ----
  347. * 204372 09-06-09 14:23 decompress_unlzma.i
  348. * -------- -------
  349. * 204372 1 files
  350. * # /usr/bin/unzip -l -qq decompress_unlzma.i.zip
  351. * 204372 09-06-09 14:23 decompress_unlzma.i
  352. * # /usr/bin/unzip -l -q decompress_unlzma.i.zip
  353. * Length Date Time Name
  354. * -------- ---- ---- ----
  355. * 204372 09-06-09 14:23 decompress_unlzma.i
  356. * -------- -------
  357. * 204372 1 file
  358. * # /usr/bin/unzip -l decompress_unlzma.i.zip
  359. * Archive: decompress_unlzma.i.zip
  360. * Length Date Time Name
  361. * -------- ---- ---- ----
  362. * 204372 09-06-09 14:23 decompress_unlzma.i
  363. * -------- -------
  364. * 204372 1 file
  365. */
  366. x_opt_seen = 0;
  367. /* '-' makes getopt return 1 for non-options */
  368. while ((opt = getopt(argc, argv, "-d:lnopqxv")) != -1) {
  369. switch (opt) {
  370. case 'd': /* Extract to base directory */
  371. base_dir = optarg;
  372. break;
  373. case 'l': /* List */
  374. listing = 1;
  375. break;
  376. case 'n': /* Never overwrite existing files */
  377. overwrite = O_NEVER;
  378. break;
  379. case 'o': /* Always overwrite existing files */
  380. overwrite = O_ALWAYS;
  381. break;
  382. case 'p': /* Extract files to stdout and fall through to set verbosity */
  383. dst_fd = STDOUT_FILENO;
  384. case 'q': /* Be quiet */
  385. quiet++;
  386. break;
  387. case 'v': /* Verbose list */
  388. IF_DESKTOP(verbose++;)
  389. listing = 1;
  390. break;
  391. case 'x':
  392. x_opt_seen = 1;
  393. break;
  394. case 1:
  395. if (!src_fn) {
  396. /* The zip file */
  397. /* +5: space for ".zip" and NUL */
  398. src_fn = xmalloc(strlen(optarg) + 5);
  399. strcpy(src_fn, optarg);
  400. } else if (!x_opt_seen) {
  401. /* Include files */
  402. llist_add_to(&zaccept, optarg);
  403. } else {
  404. /* Exclude files */
  405. llist_add_to(&zreject, optarg);
  406. }
  407. break;
  408. default:
  409. bb_show_usage();
  410. }
  411. }
  412. #ifndef __GLIBC__
  413. /*
  414. * This code is needed for non-GNU getopt
  415. * which doesn't understand "-" in option string.
  416. * The -x option won't work properly in this case:
  417. * "unzip a.zip q -x w e" will be interpreted as
  418. * "unzip a.zip q w e -x" = "unzip a.zip q w e"
  419. */
  420. argv += optind;
  421. if (argv[0]) {
  422. /* +5: space for ".zip" and NUL */
  423. src_fn = xmalloc(strlen(argv[0]) + 5);
  424. strcpy(src_fn, argv[0]);
  425. while (*++argv)
  426. llist_add_to(&zaccept, *argv);
  427. }
  428. #endif
  429. if (!src_fn) {
  430. bb_show_usage();
  431. }
  432. /* Open input file */
  433. if (LONE_DASH(src_fn)) {
  434. xdup2(STDIN_FILENO, zip_fd);
  435. /* Cannot use prompt mode since zip data is arriving on STDIN */
  436. if (overwrite == O_PROMPT)
  437. overwrite = O_NEVER;
  438. } else {
  439. static const char extn[][5] ALIGN1 = { ".zip", ".ZIP" };
  440. char *ext = src_fn + strlen(src_fn);
  441. int src_fd;
  442. i = 0;
  443. for (;;) {
  444. src_fd = open(src_fn, O_RDONLY);
  445. if (src_fd >= 0)
  446. break;
  447. if (++i > 2) {
  448. *ext = '\0';
  449. bb_error_msg_and_die("can't open %s[.zip]", src_fn);
  450. }
  451. strcpy(ext, extn[i - 1]);
  452. }
  453. xmove_fd(src_fd, zip_fd);
  454. }
  455. /* Change dir if necessary */
  456. if (base_dir)
  457. xchdir(base_dir);
  458. if (quiet <= 1) { /* not -qq */
  459. if (quiet == 0)
  460. printf("Archive: %s\n", src_fn);
  461. if (listing) {
  462. puts(verbose ?
  463. " Length Method Size Cmpr Date Time CRC-32 Name\n"
  464. "-------- ------ ------- ---- ---------- ----- -------- ----"
  465. :
  466. " Length Date Time Name\n"
  467. "--------- ---------- ----- ----"
  468. );
  469. }
  470. }
  471. /* Example of an archive with one 0-byte long file named 'z'
  472. * created by Zip 2.31 on Unix:
  473. * 0000 [50 4b]03 04 0a 00 00 00 00 00 42 1a b8 3c 00 00 |PK........B..<..|
  474. * sig........ vneed flags compr mtime mdate crc32>
  475. * 0010 00 00 00 00 00 00 00 00 00 00 01 00 15 00 7a 55 |..............zU|
  476. * >..... csize...... usize...... fnlen exlen fn ex>
  477. * 0020 54 09 00 03 cc d3 f9 4b cc d3 f9 4b 55 78 04 00 |T......K...KUx..|
  478. * >tra_field......................................
  479. * 0030 00 00 00 00[50 4b]01 02 17 03 0a 00 00 00 00 00 |....PK..........|
  480. * ........... sig........ vmade vneed flags compr
  481. * 0040 42 1a b8 3c 00 00 00 00 00 00 00 00 00 00 00 00 |B..<............|
  482. * mtime mdate crc32...... csize...... usize......
  483. * 0050 01 00 0d 00 00 00 00 00 00 00 00 00 a4 81 00 00 |................|
  484. * fnlen exlen clen. dnum. iattr eattr...... relofs> (eattr = rw-r--r--)
  485. * 0060 00 00 7a 55 54 05 00 03 cc d3 f9 4b 55 78 00 00 |..zUT......KUx..|
  486. * >..... fn extra_field...........................
  487. * 0070 [50 4b]05 06 00 00 00 00 01 00 01 00 3c 00 00 00 |PK..........<...|
  488. * 0080 34 00 00 00 00 00 |4.....|
  489. */
  490. total_usize = 0;
  491. total_size = 0;
  492. total_entries = 0;
  493. #if ENABLE_DESKTOP
  494. cdf_offset = 0;
  495. #endif
  496. while (1) {
  497. uint32_t magic;
  498. mode_t dir_mode = 0777;
  499. #if ENABLE_DESKTOP
  500. mode_t file_mode = 0666;
  501. #endif
  502. /* Check magic number */
  503. xread(zip_fd, &magic, 4);
  504. /* Central directory? It's at the end, so exit */
  505. if (magic == ZIP_CDF_MAGIC) {
  506. dbg("got ZIP_CDF_MAGIC");
  507. break;
  508. }
  509. #if ENABLE_DESKTOP
  510. /* Data descriptor? It was a streaming file, go on */
  511. if (magic == ZIP_DD_MAGIC) {
  512. dbg("got ZIP_DD_MAGIC");
  513. /* skip over duplicate crc32, cmpsize and ucmpsize */
  514. unzip_skip(3 * 4);
  515. continue;
  516. }
  517. #endif
  518. if (magic != ZIP_FILEHEADER_MAGIC)
  519. bb_error_msg_and_die("invalid zip magic %08X", (int)magic);
  520. dbg("got ZIP_FILEHEADER_MAGIC");
  521. /* Read the file header */
  522. xread(zip_fd, zip_header.raw, ZIP_HEADER_LEN);
  523. FIX_ENDIANNESS_ZIP(zip_header);
  524. if ((zip_header.formatted.method != 0) && (zip_header.formatted.method != 8)) {
  525. bb_error_msg_and_die("unsupported method %d", zip_header.formatted.method);
  526. }
  527. #if !ENABLE_DESKTOP
  528. if (zip_header.formatted.zip_flags & SWAP_LE16(0x0009)) {
  529. bb_error_msg_and_die("zip flags 1 and 8 are not supported");
  530. }
  531. #else
  532. if (zip_header.formatted.zip_flags & SWAP_LE16(0x0001)) {
  533. /* 0x0001 - encrypted */
  534. bb_error_msg_and_die("zip flag 1 (encryption) is not supported");
  535. }
  536. if (cdf_offset != BAD_CDF_OFFSET) {
  537. cdf_header_t cdf_header;
  538. cdf_offset = read_next_cdf(cdf_offset, &cdf_header);
  539. /*
  540. * Note: cdf_offset can become BAD_CDF_OFFSET after the above call.
  541. */
  542. if (zip_header.formatted.zip_flags & SWAP_LE16(0x0008)) {
  543. /* 0x0008 - streaming. [u]cmpsize can be reliably gotten
  544. * only from Central Directory. See unzip_doc.txt
  545. */
  546. zip_header.formatted.crc32 = cdf_header.formatted.crc32;
  547. zip_header.formatted.cmpsize = cdf_header.formatted.cmpsize;
  548. zip_header.formatted.ucmpsize = cdf_header.formatted.ucmpsize;
  549. }
  550. if ((cdf_header.formatted.version_made_by >> 8) == 3) {
  551. /* This archive is created on Unix */
  552. dir_mode = file_mode = (cdf_header.formatted.external_file_attributes >> 16);
  553. }
  554. }
  555. if (cdf_offset == BAD_CDF_OFFSET
  556. && (zip_header.formatted.zip_flags & SWAP_LE16(0x0008))
  557. ) {
  558. /* If it's a streaming zip, we _require_ CDF */
  559. bb_error_msg_and_die("can't find file table");
  560. }
  561. #endif
  562. dbg("File cmpsize:0x%x extra_len:0x%x ucmpsize:0x%x",
  563. (unsigned)zip_header.formatted.cmpsize,
  564. (unsigned)zip_header.formatted.extra_len,
  565. (unsigned)zip_header.formatted.ucmpsize
  566. );
  567. /* Read filename */
  568. free(dst_fn);
  569. dst_fn = xzalloc(zip_header.formatted.filename_len + 1);
  570. xread(zip_fd, dst_fn, zip_header.formatted.filename_len);
  571. /* Skip extra header bytes */
  572. unzip_skip(zip_header.formatted.extra_len);
  573. /* Guard against "/abspath", "/../" and similar attacks */
  574. overlapping_strcpy(dst_fn, strip_unsafe_prefix(dst_fn));
  575. /* Filter zip entries */
  576. if (find_list_entry(zreject, dst_fn)
  577. || (zaccept && !find_list_entry(zaccept, dst_fn))
  578. ) { /* Skip entry */
  579. i = 'n';
  580. } else {
  581. if (listing) {
  582. /* List entry */
  583. char dtbuf[sizeof("mm-dd-yyyy hh:mm")];
  584. sprintf(dtbuf, "%02u-%02u-%04u %02u:%02u",
  585. (zip_header.formatted.moddate >> 5) & 0xf, // mm: 0x01e0
  586. (zip_header.formatted.moddate) & 0x1f, // dd: 0x001f
  587. (zip_header.formatted.moddate >> 9) + 1980, // yy: 0xfe00
  588. (zip_header.formatted.modtime >> 11), // hh: 0xf800
  589. (zip_header.formatted.modtime >> 5) & 0x3f // mm: 0x07e0
  590. // seconds/2 are not shown, encoded in ----------- 0x001f
  591. );
  592. if (!verbose) {
  593. // " Length Date Time Name\n"
  594. // "--------- ---------- ----- ----"
  595. printf( "%9u " "%s " "%s\n",
  596. (unsigned)zip_header.formatted.ucmpsize,
  597. dtbuf,
  598. dst_fn);
  599. } else {
  600. unsigned long percents = zip_header.formatted.ucmpsize - zip_header.formatted.cmpsize;
  601. if ((int32_t)percents < 0)
  602. percents = 0; /* happens if ucmpsize < cmpsize */
  603. percents = percents * 100;
  604. if (zip_header.formatted.ucmpsize)
  605. percents /= zip_header.formatted.ucmpsize;
  606. // " Length Method Size Cmpr Date Time CRC-32 Name\n"
  607. // "-------- ------ ------- ---- ---------- ----- -------- ----"
  608. printf( "%8u %s" "%9u%4u%% " "%s " "%08x " "%s\n",
  609. (unsigned)zip_header.formatted.ucmpsize,
  610. zip_header.formatted.method == 0 ? "Stored" : "Defl:N", /* Defl is method 8 */
  611. /* TODO: show other methods?
  612. * 1 - Shrunk
  613. * 2 - Reduced with compression factor 1
  614. * 3 - Reduced with compression factor 2
  615. * 4 - Reduced with compression factor 3
  616. * 5 - Reduced with compression factor 4
  617. * 6 - Imploded
  618. * 7 - Reserved for Tokenizing compression algorithm
  619. * 9 - Deflate64
  620. * 10 - PKWARE Data Compression Library Imploding
  621. * 11 - Reserved by PKWARE
  622. * 12 - BZIP2
  623. */
  624. (unsigned)zip_header.formatted.cmpsize,
  625. (unsigned)percents,
  626. dtbuf,
  627. zip_header.formatted.crc32,
  628. dst_fn);
  629. total_size += zip_header.formatted.cmpsize;
  630. }
  631. total_usize += zip_header.formatted.ucmpsize;
  632. i = 'n';
  633. } else if (dst_fd == STDOUT_FILENO) {
  634. /* Extracting to STDOUT */
  635. i = -1;
  636. } else if (last_char_is(dst_fn, '/')) {
  637. /* Extract directory */
  638. if (stat(dst_fn, &stat_buf) == -1) {
  639. if (errno != ENOENT) {
  640. bb_perror_msg_and_die("can't stat '%s'", dst_fn);
  641. }
  642. if (!quiet) {
  643. printf(" creating: %s\n", dst_fn);
  644. }
  645. unzip_create_leading_dirs(dst_fn);
  646. if (bb_make_directory(dst_fn, dir_mode, FILEUTILS_IGNORE_CHMOD_ERR)) {
  647. xfunc_die();
  648. }
  649. } else {
  650. if (!S_ISDIR(stat_buf.st_mode)) {
  651. bb_error_msg_and_die("'%s' exists but is not a %s",
  652. dst_fn, "directory");
  653. }
  654. }
  655. i = 'n';
  656. } else {
  657. /* Extract file */
  658. check_file:
  659. if (stat(dst_fn, &stat_buf) == -1) {
  660. /* File does not exist */
  661. if (errno != ENOENT) {
  662. bb_perror_msg_and_die("can't stat '%s'", dst_fn);
  663. }
  664. i = 'y';
  665. } else {
  666. /* File already exists */
  667. if (overwrite == O_NEVER) {
  668. i = 'n';
  669. } else if (S_ISREG(stat_buf.st_mode)) {
  670. /* File is regular file */
  671. if (overwrite == O_ALWAYS) {
  672. i = 'y';
  673. } else {
  674. printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
  675. my_fgets80(key_buf);
  676. i = key_buf[0];
  677. }
  678. } else {
  679. /* File is not regular file */
  680. bb_error_msg_and_die("'%s' exists but is not a %s",
  681. dst_fn, "regular file");
  682. }
  683. }
  684. }
  685. }
  686. switch (i) {
  687. case 'A':
  688. overwrite = O_ALWAYS;
  689. case 'y': /* Open file and fall into unzip */
  690. unzip_create_leading_dirs(dst_fn);
  691. #if ENABLE_DESKTOP
  692. dst_fd = xopen3(dst_fn, O_WRONLY | O_CREAT | O_TRUNC, file_mode);
  693. #else
  694. dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC);
  695. #endif
  696. case -1: /* Unzip */
  697. if (!quiet) {
  698. printf(" inflating: %s\n", dst_fn);
  699. }
  700. unzip_extract(&zip_header, dst_fd);
  701. if (dst_fd != STDOUT_FILENO) {
  702. /* closing STDOUT is potentially bad for future business */
  703. close(dst_fd);
  704. }
  705. break;
  706. case 'N':
  707. overwrite = O_NEVER;
  708. case 'n':
  709. /* Skip entry data */
  710. unzip_skip(zip_header.formatted.cmpsize);
  711. break;
  712. case 'r':
  713. /* Prompt for new name */
  714. printf("new name: ");
  715. my_fgets80(key_buf);
  716. free(dst_fn);
  717. dst_fn = xstrdup(key_buf);
  718. chomp(dst_fn);
  719. goto check_file;
  720. default:
  721. printf("error: invalid response [%c]\n", (char)i);
  722. goto check_file;
  723. }
  724. total_entries++;
  725. }
  726. if (listing && quiet <= 1) {
  727. if (!verbose) {
  728. // " Length Date Time Name\n"
  729. // "--------- ---------- ----- ----"
  730. printf( " --------%21s" "-------\n"
  731. "%9lu%21s" "%u files\n",
  732. "",
  733. total_usize, "", total_entries);
  734. } else {
  735. unsigned long percents = total_usize - total_size;
  736. if ((long)percents < 0)
  737. percents = 0; /* happens if usize < size */
  738. percents = percents * 100;
  739. if (total_usize)
  740. percents /= total_usize;
  741. // " Length Method Size Cmpr Date Time CRC-32 Name\n"
  742. // "-------- ------ ------- ---- ---------- ----- -------- ----"
  743. printf( "-------- ------- ----%28s" "----\n"
  744. "%8lu" "%17lu%4u%%%28s" "%u files\n",
  745. "",
  746. total_usize, total_size, (unsigned)percents, "",
  747. total_entries);
  748. }
  749. }
  750. return 0;
  751. }