cpio.c 15 KB

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