unzip.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565
  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 the GPL v2 or later, see the file LICENSE in this tarball.
  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. #include "libbb.h"
  20. #include "unarchive.h"
  21. enum {
  22. #if BB_BIG_ENDIAN
  23. ZIP_FILEHEADER_MAGIC = 0x504b0304,
  24. ZIP_CDS_MAGIC = 0x504b0102,
  25. ZIP_CDE_MAGIC = 0x504b0506,
  26. ZIP_DD_MAGIC = 0x504b0708,
  27. #else
  28. ZIP_FILEHEADER_MAGIC = 0x04034b50,
  29. ZIP_CDS_MAGIC = 0x02014b50,
  30. ZIP_CDE_MAGIC = 0x06054b50,
  31. ZIP_DD_MAGIC = 0x08074b50,
  32. #endif
  33. };
  34. #define ZIP_HEADER_LEN 26
  35. typedef union {
  36. uint8_t raw[ZIP_HEADER_LEN];
  37. struct {
  38. uint16_t version; /* 0-1 */
  39. uint16_t flags; /* 2-3 */
  40. uint16_t method; /* 4-5 */
  41. uint16_t modtime; /* 6-7 */
  42. uint16_t moddate; /* 8-9 */
  43. uint32_t crc32 PACKED; /* 10-13 */
  44. uint32_t cmpsize PACKED; /* 14-17 */
  45. uint32_t ucmpsize PACKED; /* 18-21 */
  46. uint16_t filename_len; /* 22-23 */
  47. uint16_t extra_len; /* 24-25 */
  48. } formatted PACKED;
  49. } zip_header_t; /* PACKED - gcc 4.2.1 doesn't like it (spews warning) */
  50. /* Check the offset of the last element, not the length. This leniency
  51. * allows for poor packing, whereby the overall struct may be too long,
  52. * even though the elements are all in the right place.
  53. */
  54. struct BUG_zip_header_must_be_26_bytes {
  55. char BUG_zip_header_must_be_26_bytes[
  56. offsetof(zip_header_t, formatted.extra_len) + 2
  57. == ZIP_HEADER_LEN ? 1 : -1];
  58. };
  59. #define FIX_ENDIANNESS_ZIP(zip_header) do { \
  60. (zip_header).formatted.version = SWAP_LE16((zip_header).formatted.version ); \
  61. (zip_header).formatted.flags = SWAP_LE16((zip_header).formatted.flags ); \
  62. (zip_header).formatted.method = SWAP_LE16((zip_header).formatted.method ); \
  63. (zip_header).formatted.modtime = SWAP_LE16((zip_header).formatted.modtime ); \
  64. (zip_header).formatted.moddate = SWAP_LE16((zip_header).formatted.moddate ); \
  65. (zip_header).formatted.crc32 = SWAP_LE32((zip_header).formatted.crc32 ); \
  66. (zip_header).formatted.cmpsize = SWAP_LE32((zip_header).formatted.cmpsize ); \
  67. (zip_header).formatted.ucmpsize = SWAP_LE32((zip_header).formatted.ucmpsize ); \
  68. (zip_header).formatted.filename_len = SWAP_LE16((zip_header).formatted.filename_len); \
  69. (zip_header).formatted.extra_len = SWAP_LE16((zip_header).formatted.extra_len ); \
  70. } while (0)
  71. #define CDS_HEADER_LEN 42
  72. typedef union {
  73. uint8_t raw[CDS_HEADER_LEN];
  74. struct {
  75. /* uint32_t signature; 50 4b 01 02 */
  76. uint16_t version_made_by; /* 0-1 */
  77. uint16_t version_needed; /* 2-3 */
  78. uint16_t cds_flags; /* 4-5 */
  79. uint16_t method; /* 6-7 */
  80. uint16_t mtime; /* 8-9 */
  81. uint16_t mdate; /* 10-11 */
  82. uint32_t crc32; /* 12-15 */
  83. uint32_t cmpsize; /* 16-19 */
  84. uint32_t ucmpsize; /* 20-23 */
  85. uint16_t file_name_length; /* 24-25 */
  86. uint16_t extra_field_length; /* 26-27 */
  87. uint16_t file_comment_length; /* 28-29 */
  88. uint16_t disk_number_start; /* 30-31 */
  89. uint16_t internal_file_attributes; /* 32-33 */
  90. uint32_t external_file_attributes PACKED; /* 34-37 */
  91. uint32_t relative_offset_of_local_header PACKED; /* 38-41 */
  92. } formatted PACKED;
  93. } cds_header_t;
  94. struct BUG_cds_header_must_be_42_bytes {
  95. char BUG_cds_header_must_be_42_bytes[
  96. offsetof(cds_header_t, formatted.relative_offset_of_local_header) + 4
  97. == CDS_HEADER_LEN ? 1 : -1];
  98. };
  99. #define FIX_ENDIANNESS_CDS(cds_header) do { \
  100. (cds_header).formatted.crc32 = SWAP_LE32((cds_header).formatted.crc32 ); \
  101. (cds_header).formatted.cmpsize = SWAP_LE32((cds_header).formatted.cmpsize ); \
  102. (cds_header).formatted.ucmpsize = SWAP_LE32((cds_header).formatted.ucmpsize ); \
  103. (cds_header).formatted.file_name_length = SWAP_LE16((cds_header).formatted.file_name_length); \
  104. (cds_header).formatted.extra_field_length = SWAP_LE16((cds_header).formatted.extra_field_length); \
  105. (cds_header).formatted.file_comment_length = SWAP_LE16((cds_header).formatted.file_comment_length); \
  106. } while (0)
  107. #define CDE_HEADER_LEN 16
  108. typedef union {
  109. uint8_t raw[CDE_HEADER_LEN];
  110. struct {
  111. /* uint32_t signature; 50 4b 05 06 */
  112. uint16_t this_disk_no;
  113. uint16_t disk_with_cds_no;
  114. uint16_t cds_entries_on_this_disk;
  115. uint16_t cds_entries_total;
  116. uint32_t cds_size;
  117. uint32_t cds_offset;
  118. /* uint16_t file_comment_length; */
  119. /* .ZIP file comment (variable size) */
  120. } formatted PACKED;
  121. } cde_header_t;
  122. struct BUG_cde_header_must_be_16_bytes {
  123. char BUG_cde_header_must_be_16_bytes[
  124. sizeof(cde_header_t) == CDE_HEADER_LEN ? 1 : -1];
  125. };
  126. #define FIX_ENDIANNESS_CDE(cde_header) do { \
  127. (cde_header).formatted.cds_offset = SWAP_LE32((cde_header).formatted.cds_offset); \
  128. } while (0)
  129. enum { zip_fd = 3 };
  130. #if ENABLE_DESKTOP
  131. /* NB: does not preserve file position! */
  132. static uint32_t find_cds_offset(void)
  133. {
  134. unsigned char buf[1024];
  135. cde_header_t cde_header;
  136. unsigned char *p;
  137. off_t end;
  138. end = xlseek(zip_fd, 0, SEEK_END);
  139. if (end < 1024)
  140. end = 1024;
  141. end -= 1024;
  142. xlseek(zip_fd, end, SEEK_SET);
  143. full_read(zip_fd, buf, 1024);
  144. p = buf;
  145. while (p <= buf + 1024 - CDE_HEADER_LEN - 4) {
  146. if (*p != 'P') {
  147. p++;
  148. continue;
  149. }
  150. if (*++p != 'K')
  151. continue;
  152. if (*++p != 5)
  153. continue;
  154. if (*++p != 6)
  155. continue;
  156. /* we found CDE! */
  157. memcpy(cde_header.raw, p + 1, CDE_HEADER_LEN);
  158. FIX_ENDIANNESS_CDE(cde_header);
  159. return cde_header.formatted.cds_offset;
  160. }
  161. bb_error_msg_and_die("can't find file table");
  162. };
  163. static uint32_t read_next_cds(int count_m1, uint32_t cds_offset, cds_header_t *cds_ptr)
  164. {
  165. off_t org;
  166. org = xlseek(zip_fd, 0, SEEK_CUR);
  167. if (!cds_offset)
  168. cds_offset = find_cds_offset();
  169. while (count_m1-- >= 0) {
  170. xlseek(zip_fd, cds_offset + 4, SEEK_SET);
  171. xread(zip_fd, cds_ptr->raw, CDS_HEADER_LEN);
  172. FIX_ENDIANNESS_CDS(*cds_ptr);
  173. cds_offset += 4 + CDS_HEADER_LEN
  174. + cds_ptr->formatted.file_name_length
  175. + cds_ptr->formatted.extra_field_length
  176. + cds_ptr->formatted.file_comment_length;
  177. }
  178. xlseek(zip_fd, org, SEEK_SET);
  179. return cds_offset;
  180. };
  181. #endif
  182. static void unzip_skip(off_t skip)
  183. {
  184. bb_copyfd_exact_size(zip_fd, -1, skip);
  185. }
  186. static void unzip_create_leading_dirs(const char *fn)
  187. {
  188. /* Create all leading directories */
  189. char *name = xstrdup(fn);
  190. if (bb_make_directory(dirname(name), 0777, FILEUTILS_RECUR)) {
  191. bb_error_msg_and_die("exiting"); /* bb_make_directory is noisy */
  192. }
  193. free(name);
  194. }
  195. static void unzip_extract(zip_header_t *zip_header, int dst_fd)
  196. {
  197. if (zip_header->formatted.method == 0) {
  198. /* Method 0 - stored (not compressed) */
  199. off_t size = zip_header->formatted.ucmpsize;
  200. if (size)
  201. bb_copyfd_exact_size(zip_fd, dst_fd, size);
  202. } else {
  203. /* Method 8 - inflate */
  204. inflate_unzip_result res;
  205. if (inflate_unzip(&res, zip_header->formatted.cmpsize, zip_fd, dst_fd) < 0)
  206. bb_error_msg_and_die("inflate error");
  207. /* Validate decompression - crc */
  208. if (zip_header->formatted.crc32 != (res.crc ^ 0xffffffffL)) {
  209. bb_error_msg_and_die("crc error");
  210. }
  211. /* Validate decompression - size */
  212. if (zip_header->formatted.ucmpsize != res.bytes_out) {
  213. /* Don't die. Who knows, maybe len calculation
  214. * was botched somewhere. After all, crc matched! */
  215. bb_error_msg("bad length");
  216. }
  217. }
  218. }
  219. int unzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  220. int unzip_main(int argc, char **argv)
  221. {
  222. enum { O_PROMPT, O_NEVER, O_ALWAYS };
  223. zip_header_t zip_header;
  224. smallint verbose = 1;
  225. smallint listing = 0;
  226. smallint overwrite = O_PROMPT;
  227. #if ENABLE_DESKTOP
  228. uint32_t cds_offset;
  229. unsigned cds_entries;
  230. #endif
  231. unsigned total_size;
  232. unsigned total_entries;
  233. int dst_fd = -1;
  234. char *src_fn = NULL;
  235. char *dst_fn = NULL;
  236. llist_t *zaccept = NULL;
  237. llist_t *zreject = NULL;
  238. char *base_dir = NULL;
  239. int i, opt;
  240. int opt_range = 0;
  241. char key_buf[80];
  242. struct stat stat_buf;
  243. /* '-' makes getopt return 1 for non-options */
  244. while ((opt = getopt(argc, argv, "-d:lnopqx")) != -1) {
  245. switch (opt_range) {
  246. case 0: /* Options */
  247. switch (opt) {
  248. case 'l': /* List */
  249. listing = 1;
  250. break;
  251. case 'n': /* Never overwrite existing files */
  252. overwrite = O_NEVER;
  253. break;
  254. case 'o': /* Always overwrite existing files */
  255. overwrite = O_ALWAYS;
  256. break;
  257. case 'p': /* Extract files to stdout and fall through to set verbosity */
  258. dst_fd = STDOUT_FILENO;
  259. case 'q': /* Be quiet */
  260. verbose = 0;
  261. break;
  262. case 1: /* The zip file */
  263. /* +5: space for ".zip" and NUL */
  264. src_fn = xmalloc(strlen(optarg) + 5);
  265. strcpy(src_fn, optarg);
  266. opt_range++;
  267. break;
  268. default:
  269. bb_show_usage();
  270. }
  271. break;
  272. case 1: /* Include files */
  273. if (opt == 1) {
  274. llist_add_to(&zaccept, optarg);
  275. break;
  276. }
  277. if (opt == 'd') {
  278. base_dir = optarg;
  279. opt_range += 2;
  280. break;
  281. }
  282. if (opt == 'x') {
  283. opt_range++;
  284. break;
  285. }
  286. bb_show_usage();
  287. case 2 : /* Exclude files */
  288. if (opt == 1) {
  289. llist_add_to(&zreject, optarg);
  290. break;
  291. }
  292. if (opt == 'd') { /* Extract to base directory */
  293. base_dir = optarg;
  294. opt_range++;
  295. break;
  296. }
  297. /* fall through */
  298. default:
  299. bb_show_usage();
  300. }
  301. }
  302. if (src_fn == NULL) {
  303. bb_show_usage();
  304. }
  305. /* Open input file */
  306. if (LONE_DASH(src_fn)) {
  307. xdup2(STDIN_FILENO, zip_fd);
  308. /* Cannot use prompt mode since zip data is arriving on STDIN */
  309. if (overwrite == O_PROMPT)
  310. overwrite = O_NEVER;
  311. } else {
  312. static const char extn[][5] = {"", ".zip", ".ZIP"};
  313. int orig_src_fn_len = strlen(src_fn);
  314. int src_fd = -1;
  315. for (i = 0; (i < 3) && (src_fd == -1); i++) {
  316. strcpy(src_fn + orig_src_fn_len, extn[i]);
  317. src_fd = open(src_fn, O_RDONLY);
  318. }
  319. if (src_fd == -1) {
  320. src_fn[orig_src_fn_len] = '\0';
  321. bb_error_msg_and_die("can't open %s, %s.zip, %s.ZIP", src_fn, src_fn, src_fn);
  322. }
  323. xmove_fd(src_fd, zip_fd);
  324. }
  325. /* Change dir if necessary */
  326. if (base_dir)
  327. xchdir(base_dir);
  328. if (verbose) {
  329. printf("Archive: %s\n", src_fn);
  330. if (listing){
  331. puts(" Length Date Time Name\n"
  332. " -------- ---- ---- ----");
  333. }
  334. }
  335. total_size = 0;
  336. total_entries = 0;
  337. #if ENABLE_DESKTOP
  338. cds_entries = 0;
  339. cds_offset = 0;
  340. #endif
  341. while (1) {
  342. uint32_t magic;
  343. /* Check magic number */
  344. xread(zip_fd, &magic, 4);
  345. /* Central directory? It's at the end, so exit */
  346. if (magic == ZIP_CDS_MAGIC)
  347. break;
  348. #if ENABLE_DESKTOP
  349. /* Data descriptor? It was a streaming file, go on */
  350. if (magic == ZIP_DD_MAGIC) {
  351. /* skip over duplicate crc32, cmpsize and ucmpsize */
  352. unzip_skip(3 * 4);
  353. continue;
  354. }
  355. #endif
  356. if (magic != ZIP_FILEHEADER_MAGIC)
  357. bb_error_msg_and_die("invalid zip magic %08X", (int)magic);
  358. /* Read the file header */
  359. xread(zip_fd, zip_header.raw, ZIP_HEADER_LEN);
  360. FIX_ENDIANNESS_ZIP(zip_header);
  361. if ((zip_header.formatted.method != 0) && (zip_header.formatted.method != 8)) {
  362. bb_error_msg_and_die("unsupported method %d", zip_header.formatted.method);
  363. }
  364. #if !ENABLE_DESKTOP
  365. if (zip_header.formatted.flags & 0x0009) {
  366. bb_error_msg_and_die("zip flags 1 and 8 are not supported");
  367. }
  368. #else
  369. if (zip_header.formatted.flags & 0x0001) {
  370. /* 0x0001 - encrypted */
  371. bb_error_msg_and_die("zip flag 1 (encryption) is not supported");
  372. }
  373. if (zip_header.formatted.flags & 0x0008) {
  374. cds_header_t cds_header;
  375. /* 0x0008 - streaming. [u]cmpsize can be reliably gotten
  376. * only from Central Directory. See unzip_doc.txt */
  377. cds_offset = read_next_cds(total_entries - cds_entries, cds_offset, &cds_header);
  378. cds_entries = total_entries + 1;
  379. zip_header.formatted.crc32 = cds_header.formatted.crc32;
  380. zip_header.formatted.cmpsize = cds_header.formatted.cmpsize;
  381. zip_header.formatted.ucmpsize = cds_header.formatted.ucmpsize;
  382. }
  383. #endif
  384. /* Read filename */
  385. free(dst_fn);
  386. dst_fn = xzalloc(zip_header.formatted.filename_len + 1);
  387. xread(zip_fd, dst_fn, zip_header.formatted.filename_len);
  388. /* Skip extra header bytes */
  389. unzip_skip(zip_header.formatted.extra_len);
  390. /* Filter zip entries */
  391. if (find_list_entry(zreject, dst_fn)
  392. || (zaccept && !find_list_entry(zaccept, dst_fn))
  393. ) { /* Skip entry */
  394. i = 'n';
  395. } else { /* Extract entry */
  396. if (listing) { /* List entry */
  397. if (verbose) {
  398. unsigned dostime = zip_header.formatted.modtime | (zip_header.formatted.moddate << 16);
  399. printf("%9u %02u-%02u-%02u %02u:%02u %s\n",
  400. zip_header.formatted.ucmpsize,
  401. (dostime & 0x01e00000) >> 21,
  402. (dostime & 0x001f0000) >> 16,
  403. (((dostime & 0xfe000000) >> 25) + 1980) % 100,
  404. (dostime & 0x0000f800) >> 11,
  405. (dostime & 0x000007e0) >> 5,
  406. dst_fn);
  407. total_size += zip_header.formatted.ucmpsize;
  408. } else {
  409. /* short listing -- filenames only */
  410. puts(dst_fn);
  411. }
  412. i = 'n';
  413. } else if (dst_fd == STDOUT_FILENO) { /* Extracting to STDOUT */
  414. i = -1;
  415. } else if (last_char_is(dst_fn, '/')) { /* Extract directory */
  416. if (stat(dst_fn, &stat_buf) == -1) {
  417. if (errno != ENOENT) {
  418. bb_perror_msg_and_die("can't stat '%s'", dst_fn);
  419. }
  420. if (verbose) {
  421. printf(" creating: %s\n", dst_fn);
  422. }
  423. unzip_create_leading_dirs(dst_fn);
  424. if (bb_make_directory(dst_fn, 0777, 0)) {
  425. bb_error_msg_and_die("exiting");
  426. }
  427. } else {
  428. if (!S_ISDIR(stat_buf.st_mode)) {
  429. bb_error_msg_and_die("'%s' exists but is not directory", dst_fn);
  430. }
  431. }
  432. i = 'n';
  433. } else { /* Extract file */
  434. check_file:
  435. if (stat(dst_fn, &stat_buf) == -1) { /* File does not exist */
  436. if (errno != ENOENT) {
  437. bb_perror_msg_and_die("can't stat '%s'", dst_fn);
  438. }
  439. i = 'y';
  440. } else { /* File already exists */
  441. if (overwrite == O_NEVER) {
  442. i = 'n';
  443. } else if (S_ISREG(stat_buf.st_mode)) { /* File is regular file */
  444. if (overwrite == O_ALWAYS) {
  445. i = 'y';
  446. } else {
  447. printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
  448. if (!fgets(key_buf, sizeof(key_buf), stdin)) {
  449. bb_perror_msg_and_die("can't read input");
  450. }
  451. i = key_buf[0];
  452. }
  453. } else { /* File is not regular file */
  454. bb_error_msg_and_die("'%s' exists but is not regular file", dst_fn);
  455. }
  456. }
  457. }
  458. }
  459. switch (i) {
  460. case 'A':
  461. overwrite = O_ALWAYS;
  462. case 'y': /* Open file and fall into unzip */
  463. unzip_create_leading_dirs(dst_fn);
  464. dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC);
  465. case -1: /* Unzip */
  466. if (verbose) {
  467. printf(" inflating: %s\n", dst_fn);
  468. }
  469. unzip_extract(&zip_header, dst_fd);
  470. if (dst_fd != STDOUT_FILENO) {
  471. /* closing STDOUT is potentially bad for future business */
  472. close(dst_fd);
  473. }
  474. break;
  475. case 'N':
  476. overwrite = O_NEVER;
  477. case 'n':
  478. /* Skip entry data */
  479. unzip_skip(zip_header.formatted.cmpsize);
  480. break;
  481. case 'r':
  482. /* Prompt for new name */
  483. printf("new name: ");
  484. if (!fgets(key_buf, sizeof(key_buf), stdin)) {
  485. bb_perror_msg_and_die("can't read input");
  486. }
  487. free(dst_fn);
  488. dst_fn = xstrdup(key_buf);
  489. chomp(dst_fn);
  490. goto check_file;
  491. default:
  492. printf("error: invalid response [%c]\n",(char)i);
  493. goto check_file;
  494. }
  495. total_entries++;
  496. }
  497. if (listing && verbose) {
  498. printf(" -------- -------\n"
  499. "%9d %d files\n",
  500. total_size, total_entries);
  501. }
  502. return 0;
  503. }