unzip.c 27 KB

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