cpio.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. /* vi: set sw=4 ts=4: */
  2. /*
  3. * Mini cpio implementation for busybox
  4. *
  5. * Copyright (C) 2001 by Glenn McGrath
  6. *
  7. * Licensed under GPLv2 or later, see file LICENSE in this source tree.
  8. *
  9. * Limitations:
  10. * Doesn't check CRC's
  11. * Only supports new ASCII and CRC formats
  12. */
  13. #include "libbb.h"
  14. #include "bb_archive.h"
  15. //config:config CPIO
  16. //config: bool "cpio"
  17. //config: default y
  18. //config: help
  19. //config: cpio is an archival utility program used to create, modify, and
  20. //config: extract contents from archives.
  21. //config: cpio has 110 bytes of overheads for every stored file.
  22. //config:
  23. //config: This implementation of cpio can extract cpio archives created in the
  24. //config: "newc" or "crc" format, it cannot create or modify them.
  25. //config:
  26. //config: Unless you have a specific application which requires cpio, you
  27. //config: should probably say N here.
  28. //config:
  29. //config:config FEATURE_CPIO_O
  30. //config: bool "Support for archive creation"
  31. //config: default y
  32. //config: depends on CPIO
  33. //config: help
  34. //config: This implementation of cpio can create cpio archives in the "newc"
  35. //config: format only.
  36. //config:
  37. //config:config FEATURE_CPIO_P
  38. //config: bool "Support for passthrough mode"
  39. //config: default y
  40. //config: depends on FEATURE_CPIO_O
  41. //config: help
  42. //config: Passthrough mode. Rarely used.
  43. //applet:IF_CPIO(APPLET(cpio, BB_DIR_BIN, BB_SUID_DROP))
  44. //kbuild:lib-$(CONFIG_CPIO) += cpio.o
  45. //usage:#define cpio_trivial_usage
  46. //usage: "[-dmvu] [-F FILE]" IF_FEATURE_CPIO_O(" [-H newc]")
  47. //usage: " [-ti"IF_FEATURE_CPIO_O("o")"]" IF_FEATURE_CPIO_P(" [-p DIR]")
  48. //usage: " [EXTR_FILE]..."
  49. //usage:#define cpio_full_usage "\n\n"
  50. //usage: "Extract or list files from a cpio archive"
  51. //usage: IF_FEATURE_CPIO_O(", or"
  52. //usage: "\ncreate an archive" IF_FEATURE_CPIO_P(" (-o) or copy files (-p)")
  53. //usage: " using file list on stdin"
  54. //usage: )
  55. //usage: "\n"
  56. //usage: "\nMain operation mode:"
  57. //usage: "\n -t List"
  58. //usage: "\n -i Extract EXTR_FILEs (or all)"
  59. //usage: IF_FEATURE_CPIO_O(
  60. //usage: "\n -o Create (requires -H newc)"
  61. //usage: )
  62. //usage: IF_FEATURE_CPIO_P(
  63. //usage: "\n -p DIR Copy files to DIR"
  64. //usage: )
  65. //usage: "\nOptions:"
  66. //usage: "\n -d Make leading directories"
  67. //usage: "\n -m Preserve mtime"
  68. //usage: "\n -v Verbose"
  69. //usage: "\n -u Overwrite"
  70. //usage: "\n -F FILE Input (-t,-i,-p) or output (-o) file"
  71. //usage: IF_FEATURE_CPIO_O(
  72. //usage: "\n -H newc Archive format"
  73. //usage: )
  74. /* GNU cpio 2.9 --help (abridged):
  75. Modes:
  76. -t, --list List the archive
  77. -i, --extract Extract files from an archive
  78. -o, --create Create the archive
  79. -p, --pass-through Copy-pass mode
  80. Options valid in any mode:
  81. --block-size=SIZE I/O block size = SIZE * 512 bytes
  82. -B I/O block size = 5120 bytes
  83. -c Use the old portable (ASCII) archive format
  84. -C, --io-size=NUMBER I/O block size in bytes
  85. -f, --nonmatching Only copy files that do not match given pattern
  86. -F, --file=FILE Use FILE instead of standard input or output
  87. -H, --format=FORMAT Use given archive FORMAT
  88. -M, --message=STRING Print STRING when the end of a volume of the
  89. backup media is reached
  90. -n, --numeric-uid-gid If -v, show numeric UID and GID
  91. --quiet Do not print the number of blocks copied
  92. --rsh-command=COMMAND Use remote COMMAND instead of rsh
  93. -v, --verbose Verbosely list the files processed
  94. -V, --dot Print a "." for each file processed
  95. -W, --warning=FLAG Control warning display: 'none','truncate','all';
  96. multiple options accumulate
  97. Options valid only in --extract mode:
  98. -b, --swap Swap both halfwords of words and bytes of
  99. halfwords in the data (equivalent to -sS)
  100. -r, --rename Interactively rename files
  101. -s, --swap-bytes Swap the bytes of each halfword in the files
  102. -S, --swap-halfwords Swap the halfwords of each word (4 bytes)
  103. --to-stdout Extract files to standard output
  104. -E, --pattern-file=FILE Read additional patterns specifying filenames to
  105. extract or list from FILE
  106. --only-verify-crc Verify CRC's, don't actually extract the files
  107. Options valid only in --create mode:
  108. -A, --append Append to an existing archive
  109. -O FILE File to use instead of standard output
  110. Options valid only in --pass-through mode:
  111. -l, --link Link files instead of copying them, when possible
  112. Options valid in --extract and --create modes:
  113. --absolute-filenames Do not strip file system prefix components from
  114. the file names
  115. --no-absolute-filenames Create all files relative to the current dir
  116. Options valid in --create and --pass-through modes:
  117. -0, --null A list of filenames is terminated by a NUL
  118. -a, --reset-access-time Reset the access times of files after reading them
  119. -I FILE File to use instead of standard input
  120. -L, --dereference Dereference symbolic links (copy the files
  121. that they point to instead of copying the links)
  122. -R, --owner=[USER][:.][GROUP] Set owner of created files
  123. Options valid in --extract and --pass-through modes:
  124. -d, --make-directories Create leading directories where needed
  125. -m, --preserve-modification-time Retain mtime when creating files
  126. --no-preserve-owner Do not change the ownership of the files
  127. --sparse Write files with blocks of zeros as sparse files
  128. -u, --unconditional Replace all files unconditionally
  129. */
  130. enum {
  131. OPT_EXTRACT = (1 << 0),
  132. OPT_TEST = (1 << 1),
  133. OPT_NUL_TERMINATED = (1 << 2),
  134. OPT_UNCONDITIONAL = (1 << 3),
  135. OPT_VERBOSE = (1 << 4),
  136. OPT_CREATE_LEADING_DIR = (1 << 5),
  137. OPT_PRESERVE_MTIME = (1 << 6),
  138. OPT_DEREF = (1 << 7),
  139. OPT_FILE = (1 << 8),
  140. OPTBIT_FILE = 8,
  141. IF_FEATURE_CPIO_O(OPTBIT_CREATE ,)
  142. IF_FEATURE_CPIO_O(OPTBIT_FORMAT ,)
  143. IF_FEATURE_CPIO_P(OPTBIT_PASSTHROUGH,)
  144. IF_LONG_OPTS( OPTBIT_QUIET ,)
  145. IF_LONG_OPTS( OPTBIT_2STDOUT ,)
  146. OPT_CREATE = IF_FEATURE_CPIO_O((1 << OPTBIT_CREATE )) + 0,
  147. OPT_FORMAT = IF_FEATURE_CPIO_O((1 << OPTBIT_FORMAT )) + 0,
  148. OPT_PASSTHROUGH = IF_FEATURE_CPIO_P((1 << OPTBIT_PASSTHROUGH)) + 0,
  149. OPT_QUIET = IF_LONG_OPTS( (1 << OPTBIT_QUIET )) + 0,
  150. OPT_2STDOUT = IF_LONG_OPTS( (1 << OPTBIT_2STDOUT )) + 0,
  151. };
  152. #define OPTION_STR "it0uvdmLF:"
  153. #if ENABLE_FEATURE_CPIO_O
  154. static off_t cpio_pad4(off_t size)
  155. {
  156. int i;
  157. i = (- size) & 3;
  158. size += i;
  159. while (--i >= 0)
  160. bb_putchar('\0');
  161. return size;
  162. }
  163. /* Return value will become exit code.
  164. * It's ok to exit instead of return. */
  165. static NOINLINE int cpio_o(void)
  166. {
  167. static const char trailer[] ALIGN1 = "TRAILER!!!";
  168. struct name_s {
  169. struct name_s *next;
  170. char name[1];
  171. };
  172. struct inodes_s {
  173. struct inodes_s *next;
  174. struct name_s *names;
  175. struct stat st;
  176. };
  177. struct inodes_s *links = NULL;
  178. off_t bytes = 0; /* output bytes count */
  179. while (1) {
  180. const char *name;
  181. char *line;
  182. struct stat st;
  183. line = (option_mask32 & OPT_NUL_TERMINATED)
  184. ? bb_get_chunk_from_file(stdin, NULL)
  185. : xmalloc_fgetline(stdin);
  186. if (line) {
  187. /* Strip leading "./[./]..." from the filename */
  188. name = line;
  189. while (name[0] == '.' && name[1] == '/') {
  190. while (*++name == '/')
  191. continue;
  192. }
  193. if (!*name) { /* line is empty */
  194. free(line);
  195. continue;
  196. }
  197. if ((option_mask32 & OPT_DEREF)
  198. ? stat(name, &st)
  199. : lstat(name, &st)
  200. ) {
  201. abort_cpio_o:
  202. bb_simple_perror_msg_and_die(name);
  203. }
  204. if (!(S_ISLNK(st.st_mode) || S_ISREG(st.st_mode)))
  205. st.st_size = 0; /* paranoia */
  206. /* Store hardlinks for later processing, dont output them */
  207. if (!S_ISDIR(st.st_mode) && st.st_nlink > 1) {
  208. struct name_s *n;
  209. struct inodes_s *l;
  210. /* Do we have this hardlink remembered? */
  211. l = links;
  212. while (1) {
  213. if (l == NULL) {
  214. /* Not found: add new item to "links" list */
  215. l = xzalloc(sizeof(*l));
  216. l->st = st;
  217. l->next = links;
  218. links = l;
  219. break;
  220. }
  221. if (l->st.st_ino == st.st_ino) {
  222. /* found */
  223. break;
  224. }
  225. l = l->next;
  226. }
  227. /* Add new name to "l->names" list */
  228. n = xmalloc(sizeof(*n) + strlen(name));
  229. strcpy(n->name, name);
  230. n->next = l->names;
  231. l->names = n;
  232. free(line);
  233. continue;
  234. }
  235. } else { /* line == NULL: EOF */
  236. next_link:
  237. if (links) {
  238. /* Output hardlink's data */
  239. st = links->st;
  240. name = links->names->name;
  241. links->names = links->names->next;
  242. /* GNU cpio is reported to emit file data
  243. * only for the last instance. Mimic that. */
  244. if (links->names == NULL)
  245. links = links->next;
  246. else
  247. st.st_size = 0;
  248. /* NB: we leak links->names and/or links,
  249. * this is intended (we exit soon anyway) */
  250. } else {
  251. /* If no (more) hardlinks to output,
  252. * output "trailer" entry */
  253. name = trailer;
  254. /* st.st_size == 0 is a must, but for uniformity
  255. * in the output, we zero out everything */
  256. memset(&st, 0, sizeof(st));
  257. /* st.st_nlink = 1; - GNU cpio does this */
  258. }
  259. }
  260. bytes += printf("070701"
  261. "%08X%08X%08X%08X%08X%08X%08X"
  262. "%08X%08X%08X%08X" /* GNU cpio uses uppercase hex */
  263. /* strlen+1: */ "%08X"
  264. /* chksum: */ "00000000" /* (only for "070702" files) */
  265. /* name,NUL: */ "%s%c",
  266. (unsigned)(uint32_t) st.st_ino,
  267. (unsigned)(uint32_t) st.st_mode,
  268. (unsigned)(uint32_t) st.st_uid,
  269. (unsigned)(uint32_t) st.st_gid,
  270. (unsigned)(uint32_t) st.st_nlink,
  271. (unsigned)(uint32_t) st.st_mtime,
  272. (unsigned)(uint32_t) st.st_size,
  273. (unsigned)(uint32_t) major(st.st_dev),
  274. (unsigned)(uint32_t) minor(st.st_dev),
  275. (unsigned)(uint32_t) major(st.st_rdev),
  276. (unsigned)(uint32_t) minor(st.st_rdev),
  277. (unsigned)(strlen(name) + 1),
  278. name, '\0');
  279. bytes = cpio_pad4(bytes);
  280. if (st.st_size) {
  281. if (S_ISLNK(st.st_mode)) {
  282. char *lpath = xmalloc_readlink_or_warn(name);
  283. if (!lpath)
  284. goto abort_cpio_o;
  285. bytes += printf("%s", lpath);
  286. free(lpath);
  287. } else { /* S_ISREG */
  288. int fd = xopen(name, O_RDONLY);
  289. fflush_all();
  290. /* We must abort if file got shorter too! */
  291. bb_copyfd_exact_size(fd, STDOUT_FILENO, st.st_size);
  292. bytes += st.st_size;
  293. close(fd);
  294. }
  295. bytes = cpio_pad4(bytes);
  296. }
  297. if (!line) {
  298. if (name != trailer)
  299. goto next_link;
  300. /* TODO: GNU cpio pads trailer to 512 bytes, do we want that? */
  301. return EXIT_SUCCESS;
  302. }
  303. free(line);
  304. } /* end of "while (1)" */
  305. }
  306. #endif
  307. int cpio_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  308. int cpio_main(int argc UNUSED_PARAM, char **argv)
  309. {
  310. archive_handle_t *archive_handle;
  311. char *cpio_filename;
  312. IF_FEATURE_CPIO_O(const char *cpio_fmt = "";)
  313. unsigned opt;
  314. #if ENABLE_LONG_OPTS
  315. applet_long_options =
  316. "extract\0" No_argument "i"
  317. "list\0" No_argument "t"
  318. #if ENABLE_FEATURE_CPIO_O
  319. "create\0" No_argument "o"
  320. "format\0" Required_argument "H"
  321. #if ENABLE_FEATURE_CPIO_P
  322. "pass-through\0" No_argument "p"
  323. #endif
  324. #endif
  325. "verbose\0" No_argument "v"
  326. "quiet\0" No_argument "\xff"
  327. "to-stdout\0" No_argument "\xfe"
  328. ;
  329. #endif
  330. archive_handle = init_handle();
  331. /* archive_handle->src_fd = STDIN_FILENO; - done by init_handle */
  332. archive_handle->ah_flags = ARCHIVE_EXTRACT_NEWER;
  333. /* As of now we do not enforce this: */
  334. /* -i,-t,-o,-p are mutually exclusive */
  335. /* -u,-d,-m make sense only with -i or -p */
  336. /* -L makes sense only with -o or -p */
  337. #if !ENABLE_FEATURE_CPIO_O
  338. opt = getopt32(argv, OPTION_STR, &cpio_filename);
  339. argv += optind;
  340. if (opt & OPT_FILE) { /* -F */
  341. xmove_fd(xopen(cpio_filename, O_RDONLY), STDIN_FILENO);
  342. }
  343. #else
  344. opt = getopt32(argv, OPTION_STR "oH:" IF_FEATURE_CPIO_P("p"), &cpio_filename, &cpio_fmt);
  345. argv += optind;
  346. if ((opt & (OPT_FILE|OPT_CREATE)) == OPT_FILE) { /* -F without -o */
  347. xmove_fd(xopen(cpio_filename, O_RDONLY), STDIN_FILENO);
  348. }
  349. if (opt & OPT_PASSTHROUGH) {
  350. pid_t pid;
  351. struct fd_pair pp;
  352. if (argv[0] == NULL)
  353. bb_show_usage();
  354. if (opt & OPT_CREATE_LEADING_DIR)
  355. mkdir(argv[0], 0777);
  356. /* Crude existence check:
  357. * close(xopen(argv[0], O_RDONLY | O_DIRECTORY));
  358. * We can also xopen, fstat, IS_DIR, later fchdir.
  359. * This would check for existence earlier and cleaner.
  360. * As it stands now, if we fail xchdir later,
  361. * child dies on EPIPE, unless it caught
  362. * a diffrerent problem earlier.
  363. * This is good enough for now.
  364. */
  365. #if !BB_MMU
  366. pp.rd = 3;
  367. pp.wr = 4;
  368. if (!re_execed) {
  369. close(3);
  370. close(4);
  371. xpiped_pair(pp);
  372. }
  373. #else
  374. xpiped_pair(pp);
  375. #endif
  376. pid = fork_or_rexec(argv - optind);
  377. if (pid == 0) { /* child */
  378. close(pp.rd);
  379. xmove_fd(pp.wr, STDOUT_FILENO);
  380. goto dump;
  381. }
  382. /* parent */
  383. USE_FOR_NOMMU(argv[-optind][0] &= 0x7f); /* undo fork_or_rexec() damage */
  384. xchdir(*argv++);
  385. close(pp.wr);
  386. xmove_fd(pp.rd, STDIN_FILENO);
  387. //opt &= ~OPT_PASSTHROUGH;
  388. opt |= OPT_EXTRACT;
  389. goto skip;
  390. }
  391. /* -o */
  392. if (opt & OPT_CREATE) {
  393. if (cpio_fmt[0] != 'n') /* we _require_ "-H newc" */
  394. bb_show_usage();
  395. if (opt & OPT_FILE) {
  396. xmove_fd(xopen(cpio_filename, O_WRONLY | O_CREAT | O_TRUNC), STDOUT_FILENO);
  397. }
  398. dump:
  399. return cpio_o();
  400. }
  401. skip:
  402. #endif
  403. /* One of either extract or test options must be given */
  404. if ((opt & (OPT_TEST | OPT_EXTRACT)) == 0) {
  405. bb_show_usage();
  406. }
  407. if (opt & OPT_TEST) {
  408. /* if both extract and test options are given, ignore extract option */
  409. opt &= ~OPT_EXTRACT;
  410. archive_handle->action_header = header_list;
  411. }
  412. if (opt & OPT_EXTRACT) {
  413. archive_handle->action_data = data_extract_all;
  414. if (opt & OPT_2STDOUT)
  415. archive_handle->action_data = data_extract_to_stdout;
  416. }
  417. if (opt & OPT_UNCONDITIONAL) {
  418. archive_handle->ah_flags |= ARCHIVE_UNLINK_OLD;
  419. archive_handle->ah_flags &= ~ARCHIVE_EXTRACT_NEWER;
  420. }
  421. if (opt & OPT_VERBOSE) {
  422. if (archive_handle->action_header == header_list) {
  423. archive_handle->action_header = header_verbose_list;
  424. } else {
  425. archive_handle->action_header = header_list;
  426. }
  427. }
  428. if (opt & OPT_CREATE_LEADING_DIR) {
  429. archive_handle->ah_flags |= ARCHIVE_CREATE_LEADING_DIRS;
  430. }
  431. if (opt & OPT_PRESERVE_MTIME) {
  432. archive_handle->ah_flags |= ARCHIVE_RESTORE_DATE;
  433. }
  434. while (*argv) {
  435. archive_handle->filter = filter_accept_list;
  436. llist_add_to(&archive_handle->accept, *argv);
  437. argv++;
  438. }
  439. /* see get_header_cpio */
  440. archive_handle->cpio__blocks = (off_t)-1;
  441. while (get_header_cpio(archive_handle) == EXIT_SUCCESS)
  442. continue;
  443. if (archive_handle->cpio__blocks != (off_t)-1
  444. && !(opt & OPT_QUIET)
  445. ) {
  446. fprintf(stderr, "%"OFF_FMT"u blocks\n", archive_handle->cpio__blocks);
  447. }
  448. return EXIT_SUCCESS;
  449. }