unzip.c 29 KB

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