unzip.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  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. * Endian issues
  18. * Zip64 + other methods
  19. * Improve handling of zip format, ie.
  20. * - deferred CRC, comp. & uncomp. lengths (zip header flags bit 3)
  21. * - unix file permissions, etc.
  22. * - central directory
  23. */
  24. #include "libbb.h"
  25. #include "unarchive.h"
  26. enum {
  27. #if BB_BIG_ENDIAN
  28. ZIP_FILEHEADER_MAGIC = 0x504b0304,
  29. ZIP_CDS_MAGIC = 0x504b0102,
  30. ZIP_CDS_END_MAGIC = 0x504b0506,
  31. ZIP_DD_MAGIC = 0x504b0708,
  32. #else
  33. ZIP_FILEHEADER_MAGIC = 0x04034b50,
  34. ZIP_CDS_MAGIC = 0x02014b50,
  35. ZIP_CDS_END_MAGIC = 0x06054b50,
  36. ZIP_DD_MAGIC = 0x08074b50,
  37. #endif
  38. };
  39. #define ZIP_HEADER_LEN 26
  40. typedef union {
  41. uint8_t raw[ZIP_HEADER_LEN];
  42. struct {
  43. uint16_t version; /* 0-1 */
  44. uint16_t flags; /* 2-3 */
  45. uint16_t method; /* 4-5 */
  46. uint16_t modtime; /* 6-7 */
  47. uint16_t moddate; /* 8-9 */
  48. uint32_t crc32 PACKED; /* 10-13 */
  49. uint32_t cmpsize PACKED; /* 14-17 */
  50. uint32_t ucmpsize PACKED; /* 18-21 */
  51. uint16_t filename_len; /* 22-23 */
  52. uint16_t extra_len; /* 24-25 */
  53. } formatted PACKED;
  54. } zip_header_t; /* PACKED - gcc 4.2.1 doesn't like it (spews warning) */
  55. /* Check the offset of the last element, not the length. This leniency
  56. * allows for poor packing, whereby the overall struct may be too long,
  57. * even though the elements are all in the right place.
  58. */
  59. struct BUG_zip_header_must_be_26_bytes {
  60. char BUG_zip_header_must_be_26_bytes[
  61. offsetof(zip_header_t, formatted.extra_len) + 2 ==
  62. ZIP_HEADER_LEN ? 1 : -1];
  63. };
  64. #define FIX_ENDIANNESS(zip_header) do { \
  65. (zip_header).formatted.version = SWAP_LE16((zip_header).formatted.version ); \
  66. (zip_header).formatted.flags = SWAP_LE16((zip_header).formatted.flags ); \
  67. (zip_header).formatted.method = SWAP_LE16((zip_header).formatted.method ); \
  68. (zip_header).formatted.modtime = SWAP_LE16((zip_header).formatted.modtime ); \
  69. (zip_header).formatted.moddate = SWAP_LE16((zip_header).formatted.moddate ); \
  70. (zip_header).formatted.crc32 = SWAP_LE32((zip_header).formatted.crc32 ); \
  71. (zip_header).formatted.cmpsize = SWAP_LE32((zip_header).formatted.cmpsize ); \
  72. (zip_header).formatted.ucmpsize = SWAP_LE32((zip_header).formatted.ucmpsize ); \
  73. (zip_header).formatted.filename_len = SWAP_LE16((zip_header).formatted.filename_len); \
  74. (zip_header).formatted.extra_len = SWAP_LE16((zip_header).formatted.extra_len ); \
  75. } while (0)
  76. static void unzip_skip(int fd, off_t skip)
  77. {
  78. bb_copyfd_exact_size(fd, -1, skip);
  79. }
  80. static void unzip_create_leading_dirs(const char *fn)
  81. {
  82. /* Create all leading directories */
  83. char *name = xstrdup(fn);
  84. if (bb_make_directory(dirname(name), 0777, FILEUTILS_RECUR)) {
  85. bb_error_msg_and_die("exiting"); /* bb_make_directory is noisy */
  86. }
  87. free(name);
  88. }
  89. static void unzip_extract(zip_header_t *zip_header, int src_fd, int dst_fd)
  90. {
  91. if (zip_header->formatted.method == 0) {
  92. /* Method 0 - stored (not compressed) */
  93. off_t size = zip_header->formatted.ucmpsize;
  94. if (size)
  95. bb_copyfd_exact_size(src_fd, dst_fd, size);
  96. } else {
  97. /* Method 8 - inflate */
  98. inflate_unzip_result res;
  99. if (inflate_unzip(&res, zip_header->formatted.cmpsize, src_fd, dst_fd) < 0)
  100. bb_error_msg_and_die("inflate error");
  101. /* Validate decompression - crc */
  102. if (zip_header->formatted.crc32 != (res.crc ^ 0xffffffffL)) {
  103. bb_error_msg_and_die("crc error");
  104. }
  105. /* Validate decompression - size */
  106. if (zip_header->formatted.ucmpsize != res.bytes_out) {
  107. /* Don't die. Who knows, maybe len calculation
  108. * was botched somewhere. After all, crc matched! */
  109. bb_error_msg("bad length");
  110. }
  111. }
  112. }
  113. int unzip_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  114. int unzip_main(int argc, char **argv)
  115. {
  116. enum { O_PROMPT, O_NEVER, O_ALWAYS };
  117. zip_header_t zip_header;
  118. smallint verbose = 1;
  119. smallint listing = 0;
  120. smallint overwrite = O_PROMPT;
  121. unsigned total_size;
  122. unsigned total_entries;
  123. int src_fd = -1;
  124. int dst_fd = -1;
  125. char *src_fn = NULL;
  126. char *dst_fn = NULL;
  127. llist_t *zaccept = NULL;
  128. llist_t *zreject = NULL;
  129. char *base_dir = NULL;
  130. int i, opt;
  131. int opt_range = 0;
  132. char key_buf[80];
  133. struct stat stat_buf;
  134. /* '-' makes getopt return 1 for non-options */
  135. while ((opt = getopt(argc, argv, "-d:lnopqx")) != -1) {
  136. switch (opt_range) {
  137. case 0: /* Options */
  138. switch (opt) {
  139. case 'l': /* List */
  140. listing = 1;
  141. break;
  142. case 'n': /* Never overwrite existing files */
  143. overwrite = O_NEVER;
  144. break;
  145. case 'o': /* Always overwrite existing files */
  146. overwrite = O_ALWAYS;
  147. break;
  148. case 'p': /* Extract files to stdout and fall through to set verbosity */
  149. dst_fd = STDOUT_FILENO;
  150. case 'q': /* Be quiet */
  151. verbose = 0;
  152. break;
  153. case 1: /* The zip file */
  154. /* +5: space for ".zip" and NUL */
  155. src_fn = xmalloc(strlen(optarg) + 5);
  156. strcpy(src_fn, optarg);
  157. opt_range++;
  158. break;
  159. default:
  160. bb_show_usage();
  161. }
  162. break;
  163. case 1: /* Include files */
  164. if (opt == 1) {
  165. llist_add_to(&zaccept, optarg);
  166. break;
  167. }
  168. if (opt == 'd') {
  169. base_dir = optarg;
  170. opt_range += 2;
  171. break;
  172. }
  173. if (opt == 'x') {
  174. opt_range++;
  175. break;
  176. }
  177. bb_show_usage();
  178. case 2 : /* Exclude files */
  179. if (opt == 1) {
  180. llist_add_to(&zreject, optarg);
  181. break;
  182. }
  183. if (opt == 'd') { /* Extract to base directory */
  184. base_dir = optarg;
  185. opt_range++;
  186. break;
  187. }
  188. /* fall through */
  189. default:
  190. bb_show_usage();
  191. }
  192. }
  193. if (src_fn == NULL) {
  194. bb_show_usage();
  195. }
  196. /* Open input file */
  197. if (LONE_DASH(src_fn)) {
  198. src_fd = STDIN_FILENO;
  199. /* Cannot use prompt mode since zip data is arriving on STDIN */
  200. if (overwrite == O_PROMPT)
  201. overwrite = O_NEVER;
  202. } else {
  203. static const char extn[][5] = {"", ".zip", ".ZIP"};
  204. int orig_src_fn_len = strlen(src_fn);
  205. for (i = 0; (i < 3) && (src_fd == -1); i++) {
  206. strcpy(src_fn + orig_src_fn_len, extn[i]);
  207. src_fd = open(src_fn, O_RDONLY);
  208. }
  209. if (src_fd == -1) {
  210. src_fn[orig_src_fn_len] = '\0';
  211. bb_error_msg_and_die("can't open %s, %s.zip, %s.ZIP", src_fn, src_fn, src_fn);
  212. }
  213. }
  214. /* Change dir if necessary */
  215. if (base_dir)
  216. xchdir(base_dir);
  217. if (verbose) {
  218. printf("Archive: %s\n", src_fn);
  219. if (listing){
  220. puts(" Length Date Time Name\n"
  221. " -------- ---- ---- ----");
  222. }
  223. }
  224. total_size = 0;
  225. total_entries = 0;
  226. while (1) {
  227. uint32_t magic;
  228. /* Check magic number */
  229. xread(src_fd, &magic, 4);
  230. /* Central directory? It's at the end, so exit */
  231. if (magic == ZIP_CDS_MAGIC)
  232. break;
  233. if (magic != ZIP_FILEHEADER_MAGIC)
  234. bb_error_msg_and_die("invalid zip magic %08X", (int)magic);
  235. /* Read the file header */
  236. xread(src_fd, zip_header.raw, ZIP_HEADER_LEN);
  237. FIX_ENDIANNESS(zip_header);
  238. if ((zip_header.formatted.method != 0) && (zip_header.formatted.method != 8)) {
  239. bb_error_msg_and_die("unsupported method %d", zip_header.formatted.method);
  240. }
  241. if (zip_header.formatted.flags & (0x0008|0x0001)) {
  242. /* 0x0001 - encrypted */
  243. /* 0x0008 - streaming. [u]cmpsize can be reliably gotten
  244. * only from Central Directory. See unzip_doc.txt */
  245. bb_error_msg_and_die("zip flags 8 and 1 are not supported");
  246. }
  247. /* Read filename */
  248. free(dst_fn);
  249. dst_fn = xzalloc(zip_header.formatted.filename_len + 1);
  250. xread(src_fd, dst_fn, zip_header.formatted.filename_len);
  251. /* Skip extra header bytes */
  252. unzip_skip(src_fd, zip_header.formatted.extra_len);
  253. /* Filter zip entries */
  254. if (find_list_entry(zreject, dst_fn)
  255. || (zaccept && !find_list_entry(zaccept, dst_fn))
  256. ) { /* Skip entry */
  257. i = 'n';
  258. } else { /* Extract entry */
  259. if (listing) { /* List entry */
  260. if (verbose) {
  261. unsigned dostime = zip_header.formatted.modtime | (zip_header.formatted.moddate << 16);
  262. printf("%9u %02u-%02u-%02u %02u:%02u %s\n",
  263. zip_header.formatted.ucmpsize,
  264. (dostime & 0x01e00000) >> 21,
  265. (dostime & 0x001f0000) >> 16,
  266. (((dostime & 0xfe000000) >> 25) + 1980) % 100,
  267. (dostime & 0x0000f800) >> 11,
  268. (dostime & 0x000007e0) >> 5,
  269. dst_fn);
  270. total_size += zip_header.formatted.ucmpsize;
  271. total_entries++;
  272. } else {
  273. /* short listing -- filenames only */
  274. puts(dst_fn);
  275. }
  276. i = 'n';
  277. } else if (dst_fd == STDOUT_FILENO) { /* Extracting to STDOUT */
  278. i = -1;
  279. } else if (last_char_is(dst_fn, '/')) { /* Extract directory */
  280. if (stat(dst_fn, &stat_buf) == -1) {
  281. if (errno != ENOENT) {
  282. bb_perror_msg_and_die("cannot stat '%s'", dst_fn);
  283. }
  284. if (verbose) {
  285. printf(" creating: %s\n", dst_fn);
  286. }
  287. unzip_create_leading_dirs(dst_fn);
  288. if (bb_make_directory(dst_fn, 0777, 0)) {
  289. bb_error_msg_and_die("exiting");
  290. }
  291. } else {
  292. if (!S_ISDIR(stat_buf.st_mode)) {
  293. bb_error_msg_and_die("'%s' exists but is not directory", dst_fn);
  294. }
  295. }
  296. i = 'n';
  297. } else { /* Extract file */
  298. check_file:
  299. if (stat(dst_fn, &stat_buf) == -1) { /* File does not exist */
  300. if (errno != ENOENT) {
  301. bb_perror_msg_and_die("cannot stat '%s'", dst_fn);
  302. }
  303. i = 'y';
  304. } else { /* File already exists */
  305. if (overwrite == O_NEVER) {
  306. i = 'n';
  307. } else if (S_ISREG(stat_buf.st_mode)) { /* File is regular file */
  308. if (overwrite == O_ALWAYS) {
  309. i = 'y';
  310. } else {
  311. printf("replace %s? [y]es, [n]o, [A]ll, [N]one, [r]ename: ", dst_fn);
  312. if (!fgets(key_buf, sizeof(key_buf), stdin)) {
  313. bb_perror_msg_and_die("cannot read input");
  314. }
  315. i = key_buf[0];
  316. }
  317. } else { /* File is not regular file */
  318. bb_error_msg_and_die("'%s' exists but is not regular file", dst_fn);
  319. }
  320. }
  321. }
  322. }
  323. switch (i) {
  324. case 'A':
  325. overwrite = O_ALWAYS;
  326. case 'y': /* Open file and fall into unzip */
  327. unzip_create_leading_dirs(dst_fn);
  328. dst_fd = xopen(dst_fn, O_WRONLY | O_CREAT | O_TRUNC);
  329. case -1: /* Unzip */
  330. if (verbose) {
  331. printf(" inflating: %s\n", dst_fn);
  332. }
  333. unzip_extract(&zip_header, src_fd, dst_fd);
  334. if (dst_fd != STDOUT_FILENO) {
  335. /* closing STDOUT is potentially bad for future business */
  336. close(dst_fd);
  337. }
  338. break;
  339. case 'N':
  340. overwrite = O_NEVER;
  341. case 'n':
  342. /* Skip entry data */
  343. unzip_skip(src_fd, zip_header.formatted.cmpsize);
  344. break;
  345. case 'r':
  346. /* Prompt for new name */
  347. printf("new name: ");
  348. if (!fgets(key_buf, sizeof(key_buf), stdin)) {
  349. bb_perror_msg_and_die("cannot read input");
  350. }
  351. free(dst_fn);
  352. dst_fn = xstrdup(key_buf);
  353. chomp(dst_fn);
  354. goto check_file;
  355. default:
  356. printf("error: invalid response [%c]\n",(char)i);
  357. goto check_file;
  358. }
  359. // Looks like bug (data descriptor cannot be identified this way)
  360. // /* Data descriptor section */
  361. // if (zip_header.formatted.flags & 4) {
  362. // /* skip over duplicate crc, compressed size and uncompressed size */
  363. // unzip_skip(src_fd, 12);
  364. // }
  365. }
  366. if (listing && verbose) {
  367. printf(" -------- -------\n"
  368. "%9d %d files\n",
  369. total_size, total_entries);
  370. }
  371. return 0;
  372. }