unzip.c 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020
  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. if (bb_make_directory(dirname(name), 0777, FILEUTILS_RECUR)) {
  306. xfunc_die(); /* bb_make_directory is noisy */
  307. }
  308. free(name);
  309. }
  310. #if ENABLE_FEATURE_UNZIP_CDF
  311. static void unzip_extract_symlink(llist_t **symlink_placeholders,
  312. zip_header_t *zip,
  313. const char *dst_fn)
  314. {
  315. char *target;
  316. die_if_bad_fnamesize(zip->fmt.ucmpsize);
  317. if (zip->fmt.method == 0) {
  318. /* Method 0 - stored (not compressed) */
  319. target = xzalloc(zip->fmt.ucmpsize + 1);
  320. xread(zip_fd, target, zip->fmt.ucmpsize);
  321. } else {
  322. #if 1
  323. bb_error_msg_and_die("compressed symlink is not supported");
  324. #else
  325. transformer_state_t xstate;
  326. init_transformer_state(&xstate);
  327. xstate.mem_output_size_max = zip->fmt.ucmpsize;
  328. /* ...unpack... */
  329. if (!xstate.mem_output_buf)
  330. WTF();
  331. target = xstate.mem_output_buf;
  332. target = xrealloc(target, xstate.mem_output_size + 1);
  333. target[xstate.mem_output_size] = '\0';
  334. #endif
  335. }
  336. create_or_remember_symlink(symlink_placeholders,
  337. target,
  338. dst_fn);
  339. free(target);
  340. }
  341. #endif
  342. static void unzip_extract(zip_header_t *zip, int dst_fd)
  343. {
  344. transformer_state_t xstate;
  345. if (zip->fmt.method == 0) {
  346. /* Method 0 - stored (not compressed) */
  347. off_t size = zip->fmt.ucmpsize;
  348. if (size)
  349. bb_copyfd_exact_size(zip_fd, dst_fd, size);
  350. return;
  351. }
  352. init_transformer_state(&xstate);
  353. xstate.bytes_in = zip->fmt.cmpsize;
  354. xstate.src_fd = zip_fd;
  355. xstate.dst_fd = dst_fd;
  356. if (zip->fmt.method == 8) {
  357. /* Method 8 - inflate */
  358. if (inflate_unzip(&xstate) < 0)
  359. bb_error_msg_and_die("inflate error");
  360. /* Validate decompression - crc */
  361. if (zip->fmt.crc32 != (xstate.crc32 ^ 0xffffffffL)) {
  362. bb_error_msg_and_die("crc error");
  363. }
  364. }
  365. #if ENABLE_FEATURE_UNZIP_BZIP2
  366. else if (zip->fmt.method == 12) {
  367. /* Tested. Unpacker reads too much, but we use CDF
  368. * and will seek to the correct beginning of next file.
  369. */
  370. xstate.bytes_out = unpack_bz2_stream(&xstate);
  371. if (xstate.bytes_out < 0)
  372. bb_error_msg_and_die("inflate error");
  373. }
  374. #endif
  375. #if ENABLE_FEATURE_UNZIP_LZMA
  376. else if (zip->fmt.method == 14) {
  377. /* Not tested yet */
  378. xstate.bytes_out = unpack_lzma_stream(&xstate);
  379. if (xstate.bytes_out < 0)
  380. bb_error_msg_and_die("inflate error");
  381. }
  382. #endif
  383. #if ENABLE_FEATURE_UNZIP_XZ
  384. else if (zip->fmt.method == 95) {
  385. /* Not tested yet */
  386. xstate.bytes_out = unpack_xz_stream(&xstate);
  387. if (xstate.bytes_out < 0)
  388. bb_error_msg_and_die("inflate error");
  389. }
  390. #endif
  391. else {
  392. bb_error_msg_and_die("unsupported method %u", zip->fmt.method);
  393. }
  394. /* Validate decompression - size */
  395. if (zip->fmt.ucmpsize != xstate.bytes_out) {
  396. /* Don't die. Who knows, maybe len calculation
  397. * was botched somewhere. After all, crc matched! */
  398. bb_error_msg("bad length");
  399. }
  400. }
  401. static void my_fgets80(char *buf80)
  402. {
  403. fflush_all();
  404. if (!fgets(buf80, 80, stdin)) {
  405. bb_perror_msg_and_die("can't read standard input");
  406. }
  407. }
  408. static int get_lstat_mode(const char *dst_fn)
  409. {
  410. struct stat stat_buf;
  411. if (lstat(dst_fn, &stat_buf) == -1) {
  412. if (errno != ENOENT) {
  413. bb_perror_msg_and_die("can't stat '%s'", dst_fn);
  414. }
  415. /* File does not exist */
  416. return -1;
  417. }
  418. return stat_buf.st_mode;
  419. }
  420. int unzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  421. int unzip_main(int argc, char **argv)
  422. {
  423. enum {
  424. OPT_l = (1 << 0),
  425. OPT_x = (1 << 1),
  426. OPT_j = (1 << 2),
  427. };
  428. unsigned opts;
  429. smallint quiet = 0;
  430. IF_NOT_FEATURE_UNZIP_CDF(const) smallint verbose = 0;
  431. enum { O_PROMPT, O_NEVER, O_ALWAYS };
  432. smallint overwrite = O_PROMPT;
  433. uint32_t cdf_offset;
  434. unsigned long total_usize;
  435. unsigned long total_size;
  436. unsigned total_entries;
  437. int dst_fd = -1;
  438. char *src_fn = NULL;
  439. char *dst_fn = NULL;
  440. llist_t *zaccept = NULL;
  441. llist_t *zreject = NULL;
  442. char *base_dir = NULL;
  443. #if ENABLE_FEATURE_UNZIP_CDF
  444. llist_t *symlink_placeholders = NULL;
  445. #endif
  446. int i;
  447. char key_buf[80]; /* must match size used by my_fgets80 */
  448. /* -q, -l and -v: UnZip 5.52 of 28 February 2005, by Info-ZIP:
  449. *
  450. * # /usr/bin/unzip -qq -v decompress_unlzma.i.zip
  451. * 204372 Defl:N 35278 83% 09-06-09 14:23 0d056252 decompress_unlzma.i
  452. * # /usr/bin/unzip -q -v decompress_unlzma.i.zip
  453. * Length Method Size Ratio Date Time CRC-32 Name
  454. * -------- ------ ------- ----- ---- ---- ------ ----
  455. * 204372 Defl:N 35278 83% 09-06-09 14:23 0d056252 decompress_unlzma.i
  456. * -------- ------- --- -------
  457. * 204372 35278 83% 1 file
  458. * # /usr/bin/unzip -v decompress_unlzma.i.zip
  459. * Archive: decompress_unlzma.i.zip
  460. * Length Method Size Ratio Date Time CRC-32 Name
  461. * -------- ------ ------- ----- ---- ---- ------ ----
  462. * 204372 Defl:N 35278 83% 09-06-09 14:23 0d056252 decompress_unlzma.i
  463. * -------- ------- --- -------
  464. * 204372 35278 83% 1 file
  465. * # unzip -v decompress_unlzma.i.zip
  466. * Archive: decompress_unlzma.i.zip
  467. * Length Date Time Name
  468. * -------- ---- ---- ----
  469. * 204372 09-06-09 14:23 decompress_unlzma.i
  470. * -------- -------
  471. * 204372 1 files
  472. * # /usr/bin/unzip -l -qq decompress_unlzma.i.zip
  473. * 204372 09-06-09 14:23 decompress_unlzma.i
  474. * # /usr/bin/unzip -l -q decompress_unlzma.i.zip
  475. * Length Date Time Name
  476. * -------- ---- ---- ----
  477. * 204372 09-06-09 14:23 decompress_unlzma.i
  478. * -------- -------
  479. * 204372 1 file
  480. * # /usr/bin/unzip -l decompress_unlzma.i.zip
  481. * Archive: decompress_unlzma.i.zip
  482. * Length Date Time Name
  483. * -------- ---- ---- ----
  484. * 204372 09-06-09 14:23 decompress_unlzma.i
  485. * -------- -------
  486. * 204372 1 file
  487. */
  488. opts = 0;
  489. /* '-' makes getopt return 1 for non-options */
  490. while ((i = getopt(argc, argv, "-d:lnopqxjv")) != -1) {
  491. switch (i) {
  492. case 'd': /* Extract to base directory */
  493. base_dir = optarg;
  494. break;
  495. case 'l': /* List */
  496. opts |= OPT_l;
  497. break;
  498. case 'n': /* Never overwrite existing files */
  499. overwrite = O_NEVER;
  500. break;
  501. case 'o': /* Always overwrite existing files */
  502. overwrite = O_ALWAYS;
  503. break;
  504. case 'p': /* Extract files to stdout and fall through to set verbosity */
  505. dst_fd = STDOUT_FILENO;
  506. case 'q': /* Be quiet */
  507. quiet++;
  508. break;
  509. case 'v': /* Verbose list */
  510. IF_FEATURE_UNZIP_CDF(verbose++;)
  511. opts |= OPT_l;
  512. break;
  513. case 'x':
  514. opts |= OPT_x;
  515. break;
  516. case 'j':
  517. opts |= OPT_j;
  518. break;
  519. case 1:
  520. if (!src_fn) {
  521. /* The zip file */
  522. /* +5: space for ".zip" and NUL */
  523. src_fn = xmalloc(strlen(optarg) + 5);
  524. strcpy(src_fn, optarg);
  525. } else if (!(opts & OPT_x)) {
  526. /* Include files */
  527. llist_add_to(&zaccept, optarg);
  528. } else {
  529. /* Exclude files */
  530. llist_add_to(&zreject, optarg);
  531. }
  532. break;
  533. default:
  534. bb_show_usage();
  535. }
  536. }
  537. #ifndef __GLIBC__
  538. /*
  539. * This code is needed for non-GNU getopt
  540. * which doesn't understand "-" in option string.
  541. * The -x option won't work properly in this case:
  542. * "unzip a.zip q -x w e" will be interpreted as
  543. * "unzip a.zip q w e -x" = "unzip a.zip q w e"
  544. */
  545. argv += optind;
  546. if (argv[0]) {
  547. /* +5: space for ".zip" and NUL */
  548. src_fn = xmalloc(strlen(argv[0]) + 5);
  549. strcpy(src_fn, argv[0]);
  550. while (*++argv)
  551. llist_add_to(&zaccept, *argv);
  552. }
  553. #endif
  554. if (!src_fn) {
  555. bb_show_usage();
  556. }
  557. /* Open input file */
  558. if (LONE_DASH(src_fn)) {
  559. xdup2(STDIN_FILENO, zip_fd);
  560. /* Cannot use prompt mode since zip data is arriving on STDIN */
  561. if (overwrite == O_PROMPT)
  562. overwrite = O_NEVER;
  563. } else {
  564. static const char extn[][5] ALIGN1 = { ".zip", ".ZIP" };
  565. char *ext = src_fn + strlen(src_fn);
  566. int src_fd;
  567. i = 0;
  568. for (;;) {
  569. src_fd = open(src_fn, O_RDONLY);
  570. if (src_fd >= 0)
  571. break;
  572. if (++i > 2) {
  573. *ext = '\0';
  574. bb_error_msg_and_die("can't open %s[.zip]", src_fn);
  575. }
  576. strcpy(ext, extn[i - 1]);
  577. }
  578. xmove_fd(src_fd, zip_fd);
  579. }
  580. /* Change dir if necessary */
  581. if (base_dir)
  582. xchdir(base_dir);
  583. if (quiet <= 1) { /* not -qq */
  584. if (quiet == 0)
  585. printf("Archive: %s\n", src_fn);
  586. if (opts & OPT_l) {
  587. puts(verbose ?
  588. " Length Method Size Cmpr Date Time CRC-32 Name\n"
  589. "-------- ------ ------- ---- ---------- ----- -------- ----"
  590. :
  591. " Length Date Time Name\n"
  592. "--------- ---------- ----- ----"
  593. );
  594. }
  595. }
  596. /* Example of an archive with one 0-byte long file named 'z'
  597. * created by Zip 2.31 on Unix:
  598. * 0000 [50 4b]03 04 0a 00 00 00 00 00 42 1a b8 3c 00 00 |PK........B..<..|
  599. * sig........ vneed flags compr mtime mdate crc32>
  600. * 0010 00 00 00 00 00 00 00 00 00 00 01 00 15 00 7a 55 |..............zU|
  601. * >..... csize...... usize...... fnlen exlen fn ex>
  602. * 0020 54 09 00 03 cc d3 f9 4b cc d3 f9 4b 55 78 04 00 |T......K...KUx..|
  603. * >tra_field......................................
  604. * 0030 00 00 00 00[50 4b]01 02 17 03 0a 00 00 00 00 00 |....PK..........|
  605. * ........... sig........ vmade vneed flags compr
  606. * 0040 42 1a b8 3c 00 00 00 00 00 00 00 00 00 00 00 00 |B..<............|
  607. * mtime mdate crc32...... csize...... usize......
  608. * 0050 01 00 0d 00 00 00 00 00 00 00 00 00 a4 81 00 00 |................|
  609. * fnlen exlen clen. dnum. iattr eattr...... relofs> (eattr = rw-r--r--)
  610. * 0060 00 00 7a 55 54 05 00 03 cc d3 f9 4b 55 78 00 00 |..zUT......KUx..|
  611. * >..... fn extra_field...........................
  612. * 0070 [50 4b]05 06 00 00 00 00 01 00 01 00 3c 00 00 00 |PK..........<...|
  613. * 0080 34 00 00 00 00 00 |4.....|
  614. */
  615. total_usize = 0;
  616. total_size = 0;
  617. total_entries = 0;
  618. cdf_offset = find_cdf_offset(); /* try to seek to the end, find CDE and CDF start */
  619. while (1) {
  620. zip_header_t zip;
  621. mode_t dir_mode = 0777;
  622. #if ENABLE_FEATURE_UNZIP_CDF
  623. mode_t file_mode = 0666;
  624. #endif
  625. if (!ENABLE_FEATURE_UNZIP_CDF || cdf_offset == BAD_CDF_OFFSET) {
  626. /* Normally happens when input is unseekable.
  627. *
  628. * Valid ZIP file has Central Directory at the end
  629. * with central directory file headers (CDFs).
  630. * After it, there is a Central Directory End structure.
  631. * CDFs identify what files are in the ZIP and where
  632. * they are located. This allows ZIP readers to load
  633. * the list of files without reading the entire ZIP archive.
  634. * ZIP files may be appended to, only files specified in
  635. * the CD are valid. Scanning for local file headers is
  636. * not a correct algorithm.
  637. *
  638. * We try to do the above, and resort to "linear" reading
  639. * of ZIP file only if seek failed or CDE wasn't found.
  640. */
  641. uint32_t magic;
  642. /* Check magic number */
  643. xread(zip_fd, &magic, 4);
  644. /* CDF item? Assume there are no more files, exit */
  645. if (magic == ZIP_CDF_MAGIC) {
  646. dbg("got ZIP_CDF_MAGIC");
  647. break;
  648. }
  649. /* Data descriptor? It was a streaming file, go on */
  650. if (magic == ZIP_DD_MAGIC) {
  651. dbg("got ZIP_DD_MAGIC");
  652. /* skip over duplicate crc32, cmpsize and ucmpsize */
  653. unzip_skip(3 * 4);
  654. continue;
  655. }
  656. if (magic != ZIP_FILEHEADER_MAGIC)
  657. bb_error_msg_and_die("invalid zip magic %08X", (int)magic);
  658. dbg("got ZIP_FILEHEADER_MAGIC");
  659. xread(zip_fd, zip.raw, ZIP_HEADER_LEN);
  660. FIX_ENDIANNESS_ZIP(zip);
  661. if (zip.fmt.zip_flags & SWAP_LE16(0x0008)) {
  662. bb_error_msg_and_die("zip flag %s is not supported",
  663. "8 (streaming)");
  664. }
  665. }
  666. #if ENABLE_FEATURE_UNZIP_CDF
  667. else {
  668. /* cdf_offset is valid (and we know the file is seekable) */
  669. cdf_header_t cdf;
  670. cdf_offset = read_next_cdf(cdf_offset, &cdf);
  671. if (cdf_offset == 0) /* EOF? */
  672. break;
  673. # if 1
  674. xlseek(zip_fd,
  675. SWAP_LE32(cdf.fmt.relative_offset_of_local_header) + 4,
  676. SEEK_SET);
  677. xread(zip_fd, zip.raw, ZIP_HEADER_LEN);
  678. FIX_ENDIANNESS_ZIP(zip);
  679. if (zip.fmt.zip_flags & SWAP_LE16(0x0008)) {
  680. /* 0x0008 - streaming. [u]cmpsize can be reliably gotten
  681. * only from Central Directory.
  682. */
  683. zip.fmt.crc32 = cdf.fmt.crc32;
  684. zip.fmt.cmpsize = cdf.fmt.cmpsize;
  685. zip.fmt.ucmpsize = cdf.fmt.ucmpsize;
  686. }
  687. // Seen in some zipfiles: central directory 9 byte extra field contains
  688. // a subfield with ID 0x5455 and 5 data bytes, which is a Unix-style UTC mtime.
  689. // Local header version:
  690. // u16 0x5455 ("UT")
  691. // u16 size (1 + 4 * n)
  692. // u8 flags: bit 0:mtime is present, bit 1:atime is present, bit 2:ctime is present
  693. // u32 mtime
  694. // u32 atime
  695. // u32 ctime
  696. // Central header version:
  697. // u16 0x5455 ("UT")
  698. // u16 size (5 (or 1?))
  699. // u8 flags: bit 0:mtime is present, bit 1:atime is present, bit 2:ctime is present
  700. // u32 mtime (CDF does not store atime/ctime)
  701. # else
  702. /* CDF has the same data as local header, no need to read the latter...
  703. * ...not really. An archive was seen with cdf.extra_len == 6 but
  704. * zip.extra_len == 0.
  705. */
  706. memcpy(&zip.fmt.version,
  707. &cdf.fmt.version_needed, ZIP_HEADER_LEN);
  708. xlseek(zip_fd,
  709. SWAP_LE32(cdf.fmt.relative_offset_of_local_header) + 4 + ZIP_HEADER_LEN,
  710. SEEK_SET);
  711. # endif
  712. if ((cdf.fmt.version_made_by >> 8) == 3) {
  713. /* This archive is created on Unix */
  714. dir_mode = file_mode = (cdf.fmt.external_attributes >> 16);
  715. }
  716. }
  717. #endif
  718. if (zip.fmt.zip_flags & SWAP_LE16(0x0001)) {
  719. /* 0x0001 - encrypted */
  720. bb_error_msg_and_die("zip flag %s is not supported",
  721. "1 (encryption)");
  722. }
  723. dbg("File cmpsize:0x%x extra_len:0x%x ucmpsize:0x%x",
  724. (unsigned)zip.fmt.cmpsize,
  725. (unsigned)zip.fmt.extra_len,
  726. (unsigned)zip.fmt.ucmpsize
  727. );
  728. /* Read filename */
  729. free(dst_fn);
  730. die_if_bad_fnamesize(zip.fmt.filename_len);
  731. dst_fn = xzalloc(zip.fmt.filename_len + 1);
  732. xread(zip_fd, dst_fn, zip.fmt.filename_len);
  733. /* Skip extra header bytes */
  734. unzip_skip(zip.fmt.extra_len);
  735. /* Guard against "/abspath", "/../" and similar attacks */
  736. overlapping_strcpy(dst_fn, strip_unsafe_prefix(dst_fn));
  737. /* Filter zip entries */
  738. if (find_list_entry(zreject, dst_fn)
  739. || (zaccept && !find_list_entry(zaccept, dst_fn))
  740. ) { /* Skip entry */
  741. goto skip_cmpsize;
  742. }
  743. if (opts & OPT_l) {
  744. /* List entry */
  745. char dtbuf[sizeof("mm-dd-yyyy hh:mm")];
  746. sprintf(dtbuf, "%02u-%02u-%04u %02u:%02u",
  747. (zip.fmt.moddate >> 5) & 0xf, // mm: 0x01e0
  748. (zip.fmt.moddate) & 0x1f, // dd: 0x001f
  749. (zip.fmt.moddate >> 9) + 1980, // yy: 0xfe00
  750. (zip.fmt.modtime >> 11), // hh: 0xf800
  751. (zip.fmt.modtime >> 5) & 0x3f // mm: 0x07e0
  752. // seconds/2 not shown, encoded in -- 0x001f
  753. );
  754. if (!verbose) {
  755. // " Length Date Time Name\n"
  756. // "--------- ---------- ----- ----"
  757. printf( "%9u " "%s " "%s\n",
  758. (unsigned)zip.fmt.ucmpsize,
  759. dtbuf,
  760. dst_fn);
  761. } else {
  762. char method6[7];
  763. unsigned long percents;
  764. sprintf(method6, "%6u", zip.fmt.method);
  765. if (zip.fmt.method == 0) {
  766. strcpy(method6, "Stored");
  767. }
  768. if (zip.fmt.method == 8) {
  769. strcpy(method6, "Defl:N");
  770. /* normal, maximum, fast, superfast */
  771. IF_DESKTOP(method6[5] = "NXFS"[(zip.fmt.zip_flags >> 1) & 3];)
  772. }
  773. percents = zip.fmt.ucmpsize - zip.fmt.cmpsize;
  774. if ((int32_t)percents < 0)
  775. percents = 0; /* happens if ucmpsize < cmpsize */
  776. percents = percents * 100;
  777. if (zip.fmt.ucmpsize)
  778. percents /= zip.fmt.ucmpsize;
  779. // " Length Method Size Cmpr Date Time CRC-32 Name\n"
  780. // "-------- ------ ------- ---- ---------- ----- -------- ----"
  781. printf( "%8u %s" "%9u%4u%% " "%s " "%08x " "%s\n",
  782. (unsigned)zip.fmt.ucmpsize,
  783. method6,
  784. (unsigned)zip.fmt.cmpsize,
  785. (unsigned)percents,
  786. dtbuf,
  787. zip.fmt.crc32,
  788. dst_fn);
  789. total_size += zip.fmt.cmpsize;
  790. }
  791. total_usize += zip.fmt.ucmpsize;
  792. goto skip_cmpsize;
  793. }
  794. if (dst_fd == STDOUT_FILENO) {
  795. /* Extracting to STDOUT */
  796. goto do_extract;
  797. }
  798. /* Strip paths (after -l: unzip -lj a.zip lists full names) */
  799. if (opts & OPT_j)
  800. overlapping_strcpy(dst_fn, bb_basename(dst_fn));
  801. /* Did this strip everything ("DIR/" case)? Then skip */
  802. if (!dst_fn[0])
  803. goto skip_cmpsize;
  804. if (last_char_is(dst_fn, '/')) {
  805. int mode;
  806. /* Extract directory */
  807. mode = get_lstat_mode(dst_fn);
  808. if (mode == -1) { /* ENOENT */
  809. if (!quiet) {
  810. printf(" creating: %s\n", dst_fn);
  811. }
  812. unzip_create_leading_dirs(dst_fn);
  813. if (bb_make_directory(dst_fn, dir_mode, FILEUTILS_IGNORE_CHMOD_ERR)) {
  814. xfunc_die();
  815. }
  816. } else {
  817. if (!S_ISDIR(mode)) {
  818. bb_error_msg_and_die("'%s' exists but is not a %s",
  819. dst_fn, "directory");
  820. }
  821. }
  822. goto skip_cmpsize;
  823. }
  824. check_file:
  825. /* Does target file already exist? */
  826. {
  827. int mode = get_lstat_mode(dst_fn);
  828. if (mode == -1) {
  829. /* ENOENT: does not exist */
  830. goto do_open_and_extract;
  831. }
  832. if (overwrite == O_NEVER) {
  833. goto skip_cmpsize;
  834. }
  835. if (!S_ISREG(mode)) {
  836. fishy:
  837. bb_error_msg_and_die("'%s' exists but is not a %s",
  838. dst_fn, "regular file");
  839. }
  840. if (overwrite == O_ALWAYS) {
  841. goto do_open_and_extract;
  842. }
  843. printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
  844. my_fgets80(key_buf);
  845. /* User input could take a long time. Is it still a regular file? */
  846. mode = get_lstat_mode(dst_fn);
  847. if (!S_ISREG(mode))
  848. goto fishy;
  849. }
  850. /* Extract (or skip) it */
  851. switch (key_buf[0]) {
  852. case 'A':
  853. overwrite = O_ALWAYS;
  854. case 'y': /* Open file and fall into unzip */
  855. do_open_and_extract:
  856. unzip_create_leading_dirs(dst_fn);
  857. #if ENABLE_FEATURE_UNZIP_CDF
  858. dst_fd = -1;
  859. if (!S_ISLNK(file_mode)) {
  860. dst_fd = xopen3(dst_fn,
  861. O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW,
  862. file_mode);
  863. }
  864. #else
  865. /* O_NOFOLLOW defends against symlink attacks */
  866. dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW);
  867. #endif
  868. do_extract:
  869. if (!quiet) {
  870. printf(/* zip.fmt.method == 0
  871. ? " extracting: %s\n"
  872. : */ " inflating: %s\n", dst_fn);
  873. }
  874. #if ENABLE_FEATURE_UNZIP_CDF
  875. if (S_ISLNK(file_mode)) {
  876. if (dst_fd != STDOUT_FILENO) /* not -p? */
  877. unzip_extract_symlink(&symlink_placeholders, &zip, dst_fn);
  878. } else
  879. #endif
  880. {
  881. unzip_extract(&zip, dst_fd);
  882. if (dst_fd != STDOUT_FILENO) {
  883. /* closing STDOUT is potentially bad for future business */
  884. close(dst_fd);
  885. }
  886. }
  887. break;
  888. case 'N':
  889. overwrite = O_NEVER;
  890. case 'n': /* Skip entry data */
  891. skip_cmpsize:
  892. unzip_skip(zip.fmt.cmpsize);
  893. break;
  894. case 'r':
  895. /* Prompt for new name */
  896. printf("new name: ");
  897. my_fgets80(key_buf);
  898. free(dst_fn);
  899. dst_fn = xstrdup(key_buf);
  900. chomp(dst_fn);
  901. goto check_file;
  902. default:
  903. printf("error: invalid response [%c]\n", (char)key_buf[0]);
  904. goto check_file;
  905. }
  906. total_entries++;
  907. }
  908. #if ENABLE_FEATURE_UNZIP_CDF
  909. create_symlinks_from_list(symlink_placeholders);
  910. #endif
  911. if ((opts & OPT_l) && quiet <= 1) {
  912. if (!verbose) {
  913. // " Length Date Time Name\n"
  914. // "--------- ---------- ----- ----"
  915. printf( " --------%21s" "-------\n"
  916. "%9lu%21s" "%u files\n",
  917. "",
  918. total_usize, "", total_entries);
  919. } else {
  920. unsigned long percents = total_usize - total_size;
  921. if ((long)percents < 0)
  922. percents = 0; /* happens if usize < size */
  923. percents = percents * 100;
  924. if (total_usize)
  925. percents /= total_usize;
  926. // " Length Method Size Cmpr Date Time CRC-32 Name\n"
  927. // "-------- ------ ------- ---- ---------- ----- -------- ----"
  928. printf( "-------- ------- ----%28s" "----\n"
  929. "%8lu" "%17lu%4u%%%28s" "%u files\n",
  930. "",
  931. total_usize, total_size, (unsigned)percents, "",
  932. total_entries);
  933. }
  934. }
  935. return 0;
  936. }