3
0

unzip.c 31 KB

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