unzip.c 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040
  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_error_msg_and_die("bad archive");
  294. }
  295. static void unzip_skip(off_t skip)
  296. {
  297. if (skip != 0)
  298. if (lseek(zip_fd, skip, SEEK_CUR) == (off_t)-1)
  299. bb_copyfd_exact_size(zip_fd, -1, skip);
  300. }
  301. static void unzip_create_leading_dirs(const char *fn)
  302. {
  303. /* Create all leading directories */
  304. char *name = xstrdup(fn);
  305. /* mode of -1: set mode according to umask */
  306. if (bb_make_directory(dirname(name), -1, FILEUTILS_RECUR)) {
  307. xfunc_die(); /* bb_make_directory is noisy */
  308. }
  309. free(name);
  310. }
  311. #if ENABLE_FEATURE_UNZIP_CDF
  312. static void unzip_extract_symlink(llist_t **symlink_placeholders,
  313. zip_header_t *zip,
  314. const char *dst_fn)
  315. {
  316. char *target;
  317. die_if_bad_fnamesize(zip->fmt.ucmpsize);
  318. if (zip->fmt.method == 0) {
  319. /* Method 0 - stored (not compressed) */
  320. target = xzalloc(zip->fmt.ucmpsize + 1);
  321. xread(zip_fd, target, zip->fmt.ucmpsize);
  322. } else {
  323. #if 1
  324. bb_error_msg_and_die("compressed symlink is not supported");
  325. #else
  326. transformer_state_t xstate;
  327. init_transformer_state(&xstate);
  328. xstate.mem_output_size_max = zip->fmt.ucmpsize;
  329. /* ...unpack... */
  330. if (!xstate.mem_output_buf)
  331. WTF();
  332. target = xstate.mem_output_buf;
  333. target = xrealloc(target, xstate.mem_output_size + 1);
  334. target[xstate.mem_output_size] = '\0';
  335. #endif
  336. }
  337. create_or_remember_link(symlink_placeholders,
  338. target,
  339. dst_fn,
  340. 0);
  341. free(target);
  342. }
  343. #endif
  344. static void unzip_extract(zip_header_t *zip, int dst_fd)
  345. {
  346. transformer_state_t xstate;
  347. if (zip->fmt.method == 0) {
  348. /* Method 0 - stored (not compressed) */
  349. off_t size = zip->fmt.ucmpsize;
  350. if (size)
  351. bb_copyfd_exact_size(zip_fd, dst_fd, size);
  352. return;
  353. }
  354. init_transformer_state(&xstate);
  355. xstate.bytes_in = zip->fmt.cmpsize;
  356. xstate.src_fd = zip_fd;
  357. xstate.dst_fd = dst_fd;
  358. if (zip->fmt.method == 8) {
  359. /* Method 8 - inflate */
  360. if (inflate_unzip(&xstate) < 0)
  361. bb_error_msg_and_die("inflate error");
  362. /* Validate decompression - crc */
  363. if (zip->fmt.crc32 != (xstate.crc32 ^ 0xffffffffL)) {
  364. bb_error_msg_and_die("crc error");
  365. }
  366. }
  367. #if ENABLE_FEATURE_UNZIP_BZIP2
  368. else if (zip->fmt.method == 12) {
  369. /* Tested. Unpacker reads too much, but we use CDF
  370. * and will seek to the correct beginning of next file.
  371. */
  372. xstate.bytes_out = unpack_bz2_stream(&xstate);
  373. if (xstate.bytes_out < 0)
  374. bb_error_msg_and_die("inflate error");
  375. }
  376. #endif
  377. #if ENABLE_FEATURE_UNZIP_LZMA
  378. else if (zip->fmt.method == 14) {
  379. /* Not tested yet */
  380. xstate.bytes_out = unpack_lzma_stream(&xstate);
  381. if (xstate.bytes_out < 0)
  382. bb_error_msg_and_die("inflate error");
  383. }
  384. #endif
  385. #if ENABLE_FEATURE_UNZIP_XZ
  386. else if (zip->fmt.method == 95) {
  387. /* Not tested yet */
  388. xstate.bytes_out = unpack_xz_stream(&xstate);
  389. if (xstate.bytes_out < 0)
  390. bb_error_msg_and_die("inflate error");
  391. }
  392. #endif
  393. else {
  394. bb_error_msg_and_die("unsupported method %u", zip->fmt.method);
  395. }
  396. /* Validate decompression - size */
  397. if (zip->fmt.ucmpsize != xstate.bytes_out) {
  398. /* Don't die. Who knows, maybe len calculation
  399. * was botched somewhere. After all, crc matched! */
  400. bb_error_msg("bad length");
  401. }
  402. }
  403. static void my_fgets80(char *buf80)
  404. {
  405. fflush_all();
  406. if (!fgets(buf80, 80, stdin)) {
  407. bb_perror_msg_and_die("can't read standard input");
  408. }
  409. }
  410. static int get_lstat_mode(const char *dst_fn)
  411. {
  412. struct stat stat_buf;
  413. if (lstat(dst_fn, &stat_buf) == -1) {
  414. if (errno != ENOENT) {
  415. bb_perror_msg_and_die("can't stat '%s'",
  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. xchdir(base_dir);
  589. if (quiet <= 1) { /* not -qq */
  590. if (quiet == 0) {
  591. printf("Archive: %s\n",
  592. printable_string(src_fn)
  593. );
  594. }
  595. if (opts & OPT_l) {
  596. puts(verbose ?
  597. " Length Method Size Cmpr Date Time CRC-32 Name\n"
  598. "-------- ------ ------- ---- ---------- ----- -------- ----"
  599. :
  600. " Length Date Time Name\n"
  601. "--------- ---------- ----- ----"
  602. );
  603. }
  604. }
  605. /* Example of an archive with one 0-byte long file named 'z'
  606. * created by Zip 2.31 on Unix:
  607. * 0000 [50 4b]03 04 0a 00 00 00 00 00 42 1a b8 3c 00 00 |PK........B..<..|
  608. * sig........ vneed flags compr mtime mdate crc32>
  609. * 0010 00 00 00 00 00 00 00 00 00 00 01 00 15 00 7a 55 |..............zU|
  610. * >..... csize...... usize...... fnlen exlen fn ex>
  611. * 0020 54 09 00 03 cc d3 f9 4b cc d3 f9 4b 55 78 04 00 |T......K...KUx..|
  612. * >tra_field......................................
  613. * 0030 00 00 00 00[50 4b]01 02 17 03 0a 00 00 00 00 00 |....PK..........|
  614. * ........... sig........ vmade vneed flags compr
  615. * 0040 42 1a b8 3c 00 00 00 00 00 00 00 00 00 00 00 00 |B..<............|
  616. * mtime mdate crc32...... csize...... usize......
  617. * 0050 01 00 0d 00 00 00 00 00 00 00 00 00 a4 81 00 00 |................|
  618. * fnlen exlen clen. dnum. iattr eattr...... relofs> (eattr = rw-r--r--)
  619. * 0060 00 00 7a 55 54 05 00 03 cc d3 f9 4b 55 78 00 00 |..zUT......KUx..|
  620. * >..... fn extra_field...........................
  621. * 0070 [50 4b]05 06 00 00 00 00 01 00 01 00 3c 00 00 00 |PK..........<...|
  622. * 0080 34 00 00 00 00 00 |4.....|
  623. */
  624. total_usize = 0;
  625. total_size = 0;
  626. total_entries = 0;
  627. cdf_offset = find_cdf_offset(); /* try to seek to the end, find CDE and CDF start */
  628. while (1) {
  629. zip_header_t zip;
  630. mode_t dir_mode = 0777;
  631. #if ENABLE_FEATURE_UNZIP_CDF
  632. mode_t file_mode = 0666;
  633. #endif
  634. if (!ENABLE_FEATURE_UNZIP_CDF || cdf_offset == BAD_CDF_OFFSET) {
  635. /* Normally happens when input is unseekable.
  636. *
  637. * Valid ZIP file has Central Directory at the end
  638. * with central directory file headers (CDFs).
  639. * After it, there is a Central Directory End structure.
  640. * CDFs identify what files are in the ZIP and where
  641. * they are located. This allows ZIP readers to load
  642. * the list of files without reading the entire ZIP archive.
  643. * ZIP files may be appended to, only files specified in
  644. * the CD are valid. Scanning for local file headers is
  645. * not a correct algorithm.
  646. *
  647. * We try to do the above, and resort to "linear" reading
  648. * of ZIP file only if seek failed or CDE wasn't found.
  649. */
  650. uint32_t magic;
  651. /* Check magic number */
  652. xread(zip_fd, &magic, 4);
  653. /* CDF item? Assume there are no more files, exit */
  654. if (magic == ZIP_CDF_MAGIC) {
  655. dbg("got ZIP_CDF_MAGIC");
  656. break;
  657. }
  658. /* Data descriptor? It was a streaming file, go on */
  659. if (magic == ZIP_DD_MAGIC) {
  660. dbg("got ZIP_DD_MAGIC");
  661. /* skip over duplicate crc32, cmpsize and ucmpsize */
  662. unzip_skip(3 * 4);
  663. continue;
  664. }
  665. if (magic != ZIP_FILEHEADER_MAGIC)
  666. bb_error_msg_and_die("invalid zip magic %08X", (int)magic);
  667. dbg("got ZIP_FILEHEADER_MAGIC");
  668. xread(zip_fd, zip.raw, ZIP_HEADER_LEN);
  669. FIX_ENDIANNESS_ZIP(zip);
  670. if (zip.fmt.zip_flags & SWAP_LE16(0x0008)) {
  671. bb_error_msg_and_die("zip flag %s is not supported",
  672. "8 (streaming)");
  673. }
  674. }
  675. #if ENABLE_FEATURE_UNZIP_CDF
  676. else {
  677. /* cdf_offset is valid (and we know the file is seekable) */
  678. cdf_header_t cdf;
  679. cdf_offset = read_next_cdf(cdf_offset, &cdf);
  680. if (cdf_offset == 0) /* EOF? */
  681. break;
  682. # if 1
  683. xlseek(zip_fd,
  684. SWAP_LE32(cdf.fmt.relative_offset_of_local_header) + 4,
  685. SEEK_SET);
  686. xread(zip_fd, zip.raw, ZIP_HEADER_LEN);
  687. FIX_ENDIANNESS_ZIP(zip);
  688. if (zip.fmt.zip_flags & SWAP_LE16(0x0008)) {
  689. /* 0x0008 - streaming. [u]cmpsize can be reliably gotten
  690. * only from Central Directory.
  691. */
  692. zip.fmt.crc32 = cdf.fmt.crc32;
  693. zip.fmt.cmpsize = cdf.fmt.cmpsize;
  694. zip.fmt.ucmpsize = cdf.fmt.ucmpsize;
  695. }
  696. // Seen in some zipfiles: central directory 9 byte extra field contains
  697. // a subfield with ID 0x5455 and 5 data bytes, which is a Unix-style UTC mtime.
  698. // Local header version:
  699. // u16 0x5455 ("UT")
  700. // u16 size (1 + 4 * n)
  701. // u8 flags: bit 0:mtime is present, bit 1:atime is present, bit 2:ctime is present
  702. // u32 mtime
  703. // u32 atime
  704. // u32 ctime
  705. // Central header version:
  706. // u16 0x5455 ("UT")
  707. // u16 size (5 (or 1?))
  708. // u8 flags: bit 0:mtime is present, bit 1:atime is present, bit 2:ctime is present
  709. // u32 mtime (CDF does not store atime/ctime)
  710. # else
  711. /* CDF has the same data as local header, no need to read the latter...
  712. * ...not really. An archive was seen with cdf.extra_len == 6 but
  713. * zip.extra_len == 0.
  714. */
  715. memcpy(&zip.fmt.version,
  716. &cdf.fmt.version_needed, ZIP_HEADER_LEN);
  717. xlseek(zip_fd,
  718. SWAP_LE32(cdf.fmt.relative_offset_of_local_header) + 4 + ZIP_HEADER_LEN,
  719. SEEK_SET);
  720. # endif
  721. if ((cdf.fmt.version_made_by >> 8) == 3) {
  722. /* This archive is created on Unix */
  723. dir_mode = file_mode = (cdf.fmt.external_attributes >> 16);
  724. }
  725. }
  726. #endif
  727. if (zip.fmt.zip_flags & SWAP_LE16(0x0001)) {
  728. /* 0x0001 - encrypted */
  729. bb_error_msg_and_die("zip flag %s is not supported",
  730. "1 (encryption)");
  731. }
  732. dbg("File cmpsize:0x%x extra_len:0x%x ucmpsize:0x%x",
  733. (unsigned)zip.fmt.cmpsize,
  734. (unsigned)zip.fmt.extra_len,
  735. (unsigned)zip.fmt.ucmpsize
  736. );
  737. /* Read filename */
  738. free(dst_fn);
  739. die_if_bad_fnamesize(zip.fmt.filename_len);
  740. dst_fn = xzalloc(zip.fmt.filename_len + 1);
  741. xread(zip_fd, dst_fn, zip.fmt.filename_len);
  742. /* Skip extra header bytes */
  743. unzip_skip(zip.fmt.extra_len);
  744. /* Guard against "/abspath", "/../" and similar attacks */
  745. overlapping_strcpy(dst_fn, strip_unsafe_prefix(dst_fn));
  746. /* Filter zip entries */
  747. if (find_list_entry(zreject, dst_fn)
  748. || (zaccept && !find_list_entry(zaccept, dst_fn))
  749. ) { /* Skip entry */
  750. goto skip_cmpsize;
  751. }
  752. if (opts & OPT_l) {
  753. /* List entry */
  754. char dtbuf[sizeof("mm-dd-yyyy hh:mm")];
  755. sprintf(dtbuf, "%02u-%02u-%04u %02u:%02u",
  756. (zip.fmt.moddate >> 5) & 0xf, // mm: 0x01e0
  757. (zip.fmt.moddate) & 0x1f, // dd: 0x001f
  758. (zip.fmt.moddate >> 9) + 1980, // yy: 0xfe00
  759. (zip.fmt.modtime >> 11), // hh: 0xf800
  760. (zip.fmt.modtime >> 5) & 0x3f // mm: 0x07e0
  761. // seconds/2 not shown, encoded in -- 0x001f
  762. );
  763. if (!verbose) {
  764. // " Length Date Time Name\n"
  765. // "--------- ---------- ----- ----"
  766. printf( "%9u " "%s " "%s\n",
  767. (unsigned)zip.fmt.ucmpsize,
  768. dtbuf,
  769. printable_string(dst_fn)
  770. );
  771. } else {
  772. char method6[7];
  773. unsigned long percents;
  774. sprintf(method6, "%6u", zip.fmt.method);
  775. if (zip.fmt.method == 0) {
  776. strcpy(method6, "Stored");
  777. }
  778. if (zip.fmt.method == 8) {
  779. strcpy(method6, "Defl:N");
  780. /* normal, maximum, fast, superfast */
  781. IF_DESKTOP(method6[5] = "NXFS"[(zip.fmt.zip_flags >> 1) & 3];)
  782. }
  783. percents = zip.fmt.ucmpsize - zip.fmt.cmpsize;
  784. if ((int32_t)percents < 0)
  785. percents = 0; /* happens if ucmpsize < cmpsize */
  786. percents = percents * 100;
  787. if (zip.fmt.ucmpsize)
  788. percents /= zip.fmt.ucmpsize;
  789. // " Length Method Size Cmpr Date Time CRC-32 Name\n"
  790. // "-------- ------ ------- ---- ---------- ----- -------- ----"
  791. printf( "%8u %s" "%9u%4u%% " "%s " "%08x " "%s\n",
  792. (unsigned)zip.fmt.ucmpsize,
  793. method6,
  794. (unsigned)zip.fmt.cmpsize,
  795. (unsigned)percents,
  796. dtbuf,
  797. zip.fmt.crc32,
  798. printable_string(dst_fn)
  799. );
  800. total_size += zip.fmt.cmpsize;
  801. }
  802. total_usize += zip.fmt.ucmpsize;
  803. goto skip_cmpsize;
  804. }
  805. if (dst_fd == STDOUT_FILENO) {
  806. /* Extracting to STDOUT */
  807. goto do_extract;
  808. }
  809. /* Strip paths (after -l: unzip -lj a.zip lists full names) */
  810. if (opts & OPT_j)
  811. overlapping_strcpy(dst_fn, bb_basename(dst_fn));
  812. /* Did this strip everything ("DIR/" case)? Then skip */
  813. if (!dst_fn[0])
  814. goto skip_cmpsize;
  815. if (last_char_is(dst_fn, '/')) {
  816. int mode;
  817. /* Extract directory */
  818. mode = get_lstat_mode(dst_fn);
  819. if (mode == -1) { /* ENOENT */
  820. if (!quiet) {
  821. printf(" creating: %s\n", printable_string(dst_fn));
  822. }
  823. unzip_create_leading_dirs(dst_fn);
  824. if (bb_make_directory(dst_fn, dir_mode, FILEUTILS_IGNORE_CHMOD_ERR)) {
  825. xfunc_die();
  826. }
  827. } else {
  828. if (!S_ISDIR(mode)) {
  829. bb_error_msg_and_die("'%s' exists but is not a %s",
  830. printable_string(dst_fn),
  831. "directory"
  832. );
  833. }
  834. }
  835. goto skip_cmpsize;
  836. }
  837. check_file:
  838. /* Does target file already exist? */
  839. {
  840. int mode = get_lstat_mode(dst_fn);
  841. if (mode == -1) {
  842. /* ENOENT: does not exist */
  843. goto do_open_and_extract;
  844. }
  845. if (overwrite == O_NEVER) {
  846. goto skip_cmpsize;
  847. }
  848. if (!S_ISREG(mode)) {
  849. fishy:
  850. bb_error_msg_and_die("'%s' exists but is not a %s",
  851. printable_string(dst_fn),
  852. "regular file"
  853. );
  854. }
  855. if (overwrite == O_ALWAYS) {
  856. goto do_open_and_extract;
  857. }
  858. printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ",
  859. printable_string(dst_fn)
  860. );
  861. my_fgets80(key_buf);
  862. /* User input could take a long time. Is it still a regular file? */
  863. mode = get_lstat_mode(dst_fn);
  864. if (!S_ISREG(mode))
  865. goto fishy;
  866. }
  867. /* Extract (or skip) it */
  868. switch (key_buf[0]) {
  869. case 'A':
  870. overwrite = O_ALWAYS;
  871. case 'y': /* Open file and fall into unzip */
  872. do_open_and_extract:
  873. unzip_create_leading_dirs(dst_fn);
  874. #if ENABLE_FEATURE_UNZIP_CDF
  875. dst_fd = -1;
  876. if (!S_ISLNK(file_mode)) {
  877. dst_fd = xopen3(dst_fn,
  878. O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW,
  879. file_mode);
  880. }
  881. #else
  882. /* O_NOFOLLOW defends against symlink attacks */
  883. dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW);
  884. #endif
  885. do_extract:
  886. if (!quiet) {
  887. printf(/* zip.fmt.method == 0
  888. ? " extracting: %s\n"
  889. : */ " inflating: %s\n",
  890. printable_string(dst_fn)
  891. );
  892. }
  893. #if ENABLE_FEATURE_UNZIP_CDF
  894. if (S_ISLNK(file_mode)) {
  895. if (dst_fd != STDOUT_FILENO) /* not -p? */
  896. unzip_extract_symlink(&symlink_placeholders, &zip, dst_fn);
  897. } else
  898. #endif
  899. {
  900. unzip_extract(&zip, dst_fd);
  901. if (dst_fd != STDOUT_FILENO) {
  902. /* closing STDOUT is potentially bad for future business */
  903. close(dst_fd);
  904. }
  905. }
  906. break;
  907. case 'N':
  908. overwrite = O_NEVER;
  909. case 'n': /* Skip entry data */
  910. skip_cmpsize:
  911. unzip_skip(zip.fmt.cmpsize);
  912. break;
  913. case 'r':
  914. /* Prompt for new name */
  915. printf("new name: ");
  916. my_fgets80(key_buf);
  917. free(dst_fn);
  918. dst_fn = xstrdup(key_buf);
  919. chomp(dst_fn);
  920. goto check_file;
  921. default:
  922. printf("error: invalid response [%c]\n", (char)key_buf[0]);
  923. goto check_file;
  924. }
  925. total_entries++;
  926. }
  927. #if ENABLE_FEATURE_UNZIP_CDF
  928. create_links_from_list(symlink_placeholders);
  929. #endif
  930. if ((opts & OPT_l) && quiet <= 1) {
  931. if (!verbose) {
  932. // " Length Date Time Name\n"
  933. // "--------- ---------- ----- ----"
  934. printf( " --------%21s" "-------\n"
  935. "%9lu%21s" "%u files\n",
  936. "",
  937. total_usize, "", total_entries);
  938. } else {
  939. unsigned long percents = total_usize - total_size;
  940. if ((long)percents < 0)
  941. percents = 0; /* happens if usize < size */
  942. percents = percents * 100;
  943. if (total_usize)
  944. percents /= total_usize;
  945. // " Length Method Size Cmpr Date Time CRC-32 Name\n"
  946. // "-------- ------ ------- ---- ---------- ----- -------- ----"
  947. printf( "-------- ------- ----%28s" "----\n"
  948. "%8lu" "%17lu%4u%%%28s" "%u files\n",
  949. "",
  950. total_usize, total_size, (unsigned)percents, "",
  951. total_entries);
  952. }
  953. }
  954. return 0;
  955. }