3
0

cpio.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  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 (14 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: "\n -d Make leading directories"
  65. //usage: "\n -m Preserve mtime"
  66. //usage: "\n -v Verbose"
  67. //usage: "\n -u Overwrite"
  68. //usage: "\n -F FILE Input (-t,-i,-p) or output (-o) file"
  69. //usage: "\n -R USER[:GRP] Set owner of created files"
  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][:.][GRP] 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. #include "libbb.h"
  130. #include "common_bufsiz.h"
  131. #include "bb_archive.h"
  132. enum {
  133. OPT_EXTRACT = (1 << 0),
  134. OPT_TEST = (1 << 1),
  135. OPT_NUL_TERMINATED = (1 << 2),
  136. OPT_UNCONDITIONAL = (1 << 3),
  137. OPT_VERBOSE = (1 << 4),
  138. OPT_CREATE_LEADING_DIR = (1 << 5),
  139. OPT_PRESERVE_MTIME = (1 << 6),
  140. OPT_DEREF = (1 << 7),
  141. OPT_FILE = (1 << 8),
  142. OPT_OWNER = (1 << 9),
  143. OPTBIT_OWNER = 9,
  144. IF_FEATURE_CPIO_O(OPTBIT_CREATE ,)
  145. IF_FEATURE_CPIO_O(OPTBIT_FORMAT ,)
  146. IF_FEATURE_CPIO_P(OPTBIT_PASSTHROUGH,)
  147. IF_LONG_OPTS( OPTBIT_QUIET ,)
  148. IF_LONG_OPTS( OPTBIT_2STDOUT ,)
  149. OPT_CREATE = IF_FEATURE_CPIO_O((1 << OPTBIT_CREATE )) + 0,
  150. OPT_FORMAT = IF_FEATURE_CPIO_O((1 << OPTBIT_FORMAT )) + 0,
  151. OPT_PASSTHROUGH = IF_FEATURE_CPIO_P((1 << OPTBIT_PASSTHROUGH)) + 0,
  152. OPT_QUIET = IF_LONG_OPTS( (1 << OPTBIT_QUIET )) + 0,
  153. OPT_2STDOUT = IF_LONG_OPTS( (1 << OPTBIT_2STDOUT )) + 0,
  154. };
  155. #define OPTION_STR "it0uvdmLF:R:"
  156. struct globals {
  157. struct bb_uidgid_t owner_ugid;
  158. } FIX_ALIASING;
  159. #define G (*(struct globals*)bb_common_bufsiz1)
  160. void BUG_cpio_globals_too_big(void);
  161. #define INIT_G() do { \
  162. setup_common_bufsiz(); \
  163. G.owner_ugid.uid = -1L; \
  164. G.owner_ugid.gid = -1L; \
  165. } while (0)
  166. #if ENABLE_FEATURE_CPIO_O
  167. static off_t cpio_pad4(off_t size)
  168. {
  169. int i;
  170. i = (- size) & 3;
  171. size += i;
  172. while (--i >= 0)
  173. bb_putchar('\0');
  174. return size;
  175. }
  176. /* Return value will become exit code.
  177. * It's ok to exit instead of return. */
  178. static NOINLINE int cpio_o(void)
  179. {
  180. struct name_s {
  181. struct name_s *next;
  182. char name[1];
  183. };
  184. struct inodes_s {
  185. struct inodes_s *next;
  186. struct name_s *names;
  187. struct stat st;
  188. };
  189. struct inodes_s *links = NULL;
  190. off_t bytes = 0; /* output bytes count */
  191. while (1) {
  192. const char *name;
  193. char *line;
  194. struct stat st;
  195. line = (option_mask32 & OPT_NUL_TERMINATED)
  196. ? bb_get_chunk_from_file(stdin, NULL)
  197. : xmalloc_fgetline(stdin);
  198. if (line) {
  199. /* Strip leading "./[./]..." from the filename */
  200. name = line;
  201. while (name[0] == '.' && name[1] == '/') {
  202. while (*++name == '/')
  203. continue;
  204. }
  205. if (!*name) { /* line is empty */
  206. free(line);
  207. continue;
  208. }
  209. if ((option_mask32 & OPT_DEREF)
  210. ? stat(name, &st)
  211. : lstat(name, &st)
  212. ) {
  213. abort_cpio_o:
  214. bb_simple_perror_msg_and_die(name);
  215. }
  216. if (G.owner_ugid.uid != (uid_t)-1L)
  217. st.st_uid = G.owner_ugid.uid;
  218. if (G.owner_ugid.gid != (gid_t)-1L)
  219. st.st_gid = G.owner_ugid.gid;
  220. if (!(S_ISLNK(st.st_mode) || S_ISREG(st.st_mode)))
  221. st.st_size = 0; /* paranoia */
  222. /* Store hardlinks for later processing, dont output them */
  223. if (!S_ISDIR(st.st_mode) && st.st_nlink > 1) {
  224. struct name_s *n;
  225. struct inodes_s *l;
  226. /* Do we have this hardlink remembered? */
  227. l = links;
  228. while (1) {
  229. if (l == NULL) {
  230. /* Not found: add new item to "links" list */
  231. l = xzalloc(sizeof(*l));
  232. l->st = st;
  233. l->next = links;
  234. links = l;
  235. break;
  236. }
  237. if (l->st.st_ino == st.st_ino) {
  238. /* found */
  239. break;
  240. }
  241. l = l->next;
  242. }
  243. /* Add new name to "l->names" list */
  244. n = xmalloc(sizeof(*n) + strlen(name));
  245. strcpy(n->name, name);
  246. n->next = l->names;
  247. l->names = n;
  248. free(line);
  249. continue;
  250. }
  251. } else { /* line == NULL: EOF */
  252. next_link:
  253. if (links) {
  254. /* Output hardlink's data */
  255. st = links->st;
  256. name = links->names->name;
  257. links->names = links->names->next;
  258. /* GNU cpio is reported to emit file data
  259. * only for the last instance. Mimic that. */
  260. if (links->names == NULL)
  261. links = links->next;
  262. else
  263. st.st_size = 0;
  264. /* NB: we leak links->names and/or links,
  265. * this is intended (we exit soon anyway) */
  266. } else {
  267. /* If no (more) hardlinks to output,
  268. * output "trailer" entry */
  269. name = cpio_TRAILER;
  270. /* st.st_size == 0 is a must, but for uniformity
  271. * in the output, we zero out everything */
  272. memset(&st, 0, sizeof(st));
  273. /* st.st_nlink = 1; - GNU cpio does this */
  274. }
  275. }
  276. bytes += printf("070701"
  277. "%08X%08X%08X%08X%08X%08X%08X"
  278. "%08X%08X%08X%08X" /* GNU cpio uses uppercase hex */
  279. /* strlen+1: */ "%08X"
  280. /* chksum: */ "00000000" /* (only for "070702" files) */
  281. /* name,NUL: */ "%s%c",
  282. (unsigned)(uint32_t) st.st_ino,
  283. (unsigned)(uint32_t) st.st_mode,
  284. (unsigned)(uint32_t) st.st_uid,
  285. (unsigned)(uint32_t) st.st_gid,
  286. (unsigned)(uint32_t) st.st_nlink,
  287. (unsigned)(uint32_t) st.st_mtime,
  288. (unsigned)(uint32_t) st.st_size,
  289. (unsigned)(uint32_t) major(st.st_dev),
  290. (unsigned)(uint32_t) minor(st.st_dev),
  291. (unsigned)(uint32_t) major(st.st_rdev),
  292. (unsigned)(uint32_t) minor(st.st_rdev),
  293. (unsigned)(strlen(name) + 1),
  294. name, '\0');
  295. bytes = cpio_pad4(bytes);
  296. if (st.st_size) {
  297. if (S_ISLNK(st.st_mode)) {
  298. char *lpath = xmalloc_readlink_or_warn(name);
  299. if (!lpath)
  300. goto abort_cpio_o;
  301. bytes += printf("%s", lpath);
  302. free(lpath);
  303. } else { /* S_ISREG */
  304. int fd = xopen(name, O_RDONLY);
  305. fflush_all();
  306. /* We must abort if file got shorter too! */
  307. bb_copyfd_exact_size(fd, STDOUT_FILENO, st.st_size);
  308. bytes += st.st_size;
  309. close(fd);
  310. }
  311. bytes = cpio_pad4(bytes);
  312. }
  313. if (!line) {
  314. if (name != cpio_TRAILER)
  315. goto next_link;
  316. /* TODO: GNU cpio pads trailer to 512 bytes, do we want that? */
  317. return EXIT_SUCCESS;
  318. }
  319. free(line);
  320. } /* end of "while (1)" */
  321. }
  322. #endif
  323. int cpio_main(int argc, char **argv) MAIN_EXTERNALLY_VISIBLE;
  324. int cpio_main(int argc UNUSED_PARAM, char **argv)
  325. {
  326. archive_handle_t *archive_handle;
  327. char *cpio_filename;
  328. char *cpio_owner;
  329. IF_FEATURE_CPIO_O(const char *cpio_fmt = "";)
  330. unsigned opt;
  331. #if ENABLE_LONG_OPTS
  332. const char *long_opts =
  333. "extract\0" No_argument "i"
  334. "list\0" No_argument "t"
  335. #if ENABLE_FEATURE_CPIO_O
  336. "create\0" No_argument "o"
  337. "format\0" Required_argument "H"
  338. #if ENABLE_FEATURE_CPIO_P
  339. "pass-through\0" No_argument "p"
  340. #endif
  341. #endif
  342. "owner\0" Required_argument "R"
  343. "verbose\0" No_argument "v"
  344. "quiet\0" No_argument "\xff"
  345. "to-stdout\0" No_argument "\xfe"
  346. ;
  347. #endif
  348. INIT_G();
  349. archive_handle = init_handle();
  350. /* archive_handle->src_fd = STDIN_FILENO; - done by init_handle */
  351. archive_handle->ah_flags = ARCHIVE_EXTRACT_NEWER;
  352. /* As of now we do not enforce this: */
  353. /* -i,-t,-o,-p are mutually exclusive */
  354. /* -u,-d,-m make sense only with -i or -p */
  355. /* -L makes sense only with -o or -p */
  356. #if !ENABLE_FEATURE_CPIO_O
  357. opt = getopt32long(argv, OPTION_STR, long_opts, &cpio_filename, &cpio_owner);
  358. #else
  359. opt = getopt32long(argv, OPTION_STR "oH:" IF_FEATURE_CPIO_P("p"), long_opts,
  360. &cpio_filename, &cpio_owner, &cpio_fmt);
  361. #endif
  362. argv += optind;
  363. if (opt & OPT_OWNER) { /* -R */
  364. parse_chown_usergroup_or_die(&G.owner_ugid, cpio_owner);
  365. archive_handle->cpio__owner = G.owner_ugid;
  366. }
  367. #if !ENABLE_FEATURE_CPIO_O
  368. if (opt & OPT_FILE) { /* -F */
  369. xmove_fd(xopen(cpio_filename, O_RDONLY), STDIN_FILENO);
  370. }
  371. #else
  372. if ((opt & (OPT_FILE|OPT_CREATE)) == OPT_FILE) { /* -F without -o */
  373. xmove_fd(xopen(cpio_filename, O_RDONLY), STDIN_FILENO);
  374. }
  375. if (opt & OPT_PASSTHROUGH) {
  376. pid_t pid;
  377. struct fd_pair pp;
  378. if (argv[0] == NULL)
  379. bb_show_usage();
  380. if (opt & OPT_CREATE_LEADING_DIR)
  381. mkdir(argv[0], 0777);
  382. /* Crude existence check:
  383. * close(xopen(argv[0], O_RDONLY | O_DIRECTORY));
  384. * We can also xopen, fstat, IS_DIR, later fchdir.
  385. * This would check for existence earlier and cleaner.
  386. * As it stands now, if we fail xchdir later,
  387. * child dies on EPIPE, unless it caught
  388. * a diffrerent problem earlier.
  389. * This is good enough for now.
  390. */
  391. #if !BB_MMU
  392. pp.rd = 3;
  393. pp.wr = 4;
  394. if (!re_execed) {
  395. close(3);
  396. close(4);
  397. xpiped_pair(pp);
  398. }
  399. #else
  400. xpiped_pair(pp);
  401. #endif
  402. pid = fork_or_rexec(argv - optind);
  403. if (pid == 0) { /* child */
  404. close(pp.rd);
  405. xmove_fd(pp.wr, STDOUT_FILENO);
  406. goto dump;
  407. }
  408. /* parent */
  409. USE_FOR_NOMMU(argv[-optind][0] &= 0x7f); /* undo fork_or_rexec() damage */
  410. xchdir(*argv++);
  411. close(pp.wr);
  412. xmove_fd(pp.rd, STDIN_FILENO);
  413. //opt &= ~OPT_PASSTHROUGH;
  414. opt |= OPT_EXTRACT;
  415. goto skip;
  416. }
  417. /* -o */
  418. if (opt & OPT_CREATE) {
  419. if (cpio_fmt[0] != 'n') /* we _require_ "-H newc" */
  420. bb_show_usage();
  421. if (opt & OPT_FILE) {
  422. xmove_fd(xopen(cpio_filename, O_WRONLY | O_CREAT | O_TRUNC), STDOUT_FILENO);
  423. }
  424. dump:
  425. return cpio_o();
  426. }
  427. skip:
  428. #endif
  429. /* One of either extract or test options must be given */
  430. if ((opt & (OPT_TEST | OPT_EXTRACT)) == 0) {
  431. bb_show_usage();
  432. }
  433. if (opt & OPT_TEST) {
  434. /* if both extract and test options are given, ignore extract option */
  435. opt &= ~OPT_EXTRACT;
  436. archive_handle->action_header = header_list;
  437. }
  438. if (opt & OPT_EXTRACT) {
  439. archive_handle->action_data = data_extract_all;
  440. if (opt & OPT_2STDOUT)
  441. archive_handle->action_data = data_extract_to_stdout;
  442. }
  443. if (opt & OPT_UNCONDITIONAL) {
  444. archive_handle->ah_flags |= ARCHIVE_UNLINK_OLD;
  445. archive_handle->ah_flags &= ~ARCHIVE_EXTRACT_NEWER;
  446. }
  447. if (opt & OPT_VERBOSE) {
  448. if (archive_handle->action_header == header_list) {
  449. archive_handle->action_header = header_verbose_list;
  450. } else {
  451. archive_handle->action_header = header_list;
  452. }
  453. }
  454. if (opt & OPT_CREATE_LEADING_DIR) {
  455. archive_handle->ah_flags |= ARCHIVE_CREATE_LEADING_DIRS;
  456. }
  457. if (opt & OPT_PRESERVE_MTIME) {
  458. archive_handle->ah_flags |= ARCHIVE_RESTORE_DATE;
  459. }
  460. while (*argv) {
  461. archive_handle->filter = filter_accept_list;
  462. llist_add_to(&archive_handle->accept, *argv);
  463. argv++;
  464. }
  465. /* see get_header_cpio */
  466. archive_handle->cpio__blocks = (off_t)-1;
  467. while (get_header_cpio(archive_handle) == EXIT_SUCCESS)
  468. continue;
  469. create_links_from_list(archive_handle->link_placeholders);
  470. if (archive_handle->cpio__blocks != (off_t)-1
  471. && !(opt & OPT_QUIET)
  472. ) {
  473. fprintf(stderr, "%"OFF_FMT"u blocks\n", archive_handle->cpio__blocks);
  474. }
  475. return EXIT_SUCCESS;
  476. }