cpio.c 14 KB

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