cpio.c 16 KB

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