unzip.c 30 KB

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