unzip.c 31 KB

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