2 * Copyright (c) 2003-2007 Tim Kientzle
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
8 * 1. Redistributions of source code must retain the above copyright
9 * notice, this list of conditions and the following disclaimer
10 * in this position and unchanged.
11 * 2. Redistributions in binary form must reproduce the above copyright
12 * notice, this list of conditions and the following disclaimer in the
13 * documentation and/or other materials provided with the distribution.
15 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18 * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 #include "cpio_platform.h"
29 __FBSDID("$FreeBSD: src/usr.bin/cpio/cpio.c,v 1.15 2008/12/06 07:30:40 kientzle Exp $");
31 #include <sys/types.h>
33 #include <archive_entry.h>
35 #ifdef HAVE_SYS_MKDEV_H
36 #include <sys/mkdev.h>
38 #ifdef HAVE_SYS_STAT_H
41 #ifdef HAVE_SYS_TIME_H
84 #include "line_reader.h"
86 /* Fixed size of uname/gname caches. */
87 #define name_cache_size 101
100 } cache[name_cache_size];
103 static int extract_data(struct archive *, struct archive *);
104 const char * cpio_i64toa(int64_t);
105 static const char *cpio_rename(const char *name);
106 static int entry_to_archive(struct cpio *, struct archive_entry *);
107 static int file_to_archive(struct cpio *, const char *);
108 static void free_cache(struct name_cache *cache);
109 static void list_item_verbose(struct cpio *, struct archive_entry *);
110 static void long_help(void);
111 static const char *lookup_gname(struct cpio *, gid_t gid);
112 static int lookup_gname_helper(struct cpio *,
113 const char **name, id_t gid);
114 static const char *lookup_uname(struct cpio *, uid_t uid);
115 static int lookup_uname_helper(struct cpio *,
116 const char **name, id_t uid);
117 static void mode_in(struct cpio *);
118 static void mode_list(struct cpio *);
119 static void mode_out(struct cpio *);
120 static void mode_pass(struct cpio *, const char *);
121 static const char *remove_leading_slash(const char *);
122 static int restore_time(struct cpio *, struct archive_entry *,
123 const char *, int fd);
124 static void usage(void);
125 static void version(void);
128 main(int argc, char *argv[])
130 static char buff[16384];
131 struct cpio _cpio; /* Allocated on stack. */
138 memset(cpio, 0, sizeof(*cpio));
140 cpio->buff_size = sizeof(buff);
142 #if defined(HAVE_SIGACTION) && defined(SIGPIPE)
143 { /* Ignore SIGPIPE signals. */
145 sigemptyset(&sa.sa_mask);
147 sa.sa_handler = SIG_IGN;
148 sigaction(SIGPIPE, &sa, NULL);
152 /* Need lafe_progname before calling lafe_warnc. */
154 lafe_progname = "bsdcpio";
156 #if defined(_WIN32) && !defined(__CYGWIN__)
157 lafe_progname = strrchr(*argv, '\\');
158 if (strrchr(*argv, '/') > lafe_progname)
160 lafe_progname = strrchr(*argv, '/');
161 if (lafe_progname != NULL)
164 lafe_progname = *argv;
167 if (setlocale(LC_ALL, "") == NULL)
168 lafe_warnc(0, "Failed to set default locale");
171 cpio->uid_override = -1;
172 cpio->gid_override = -1;
177 cpio->compress = '\0';
178 cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
179 cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
180 cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
181 cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
182 cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
183 cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
184 cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
185 #if !defined(_WIN32) && !defined(__CYGWIN__)
187 cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
189 cpio->bytes_per_block = 512;
190 cpio->filename = NULL;
192 cpio->matching = archive_match_new();
193 if (cpio->matching == NULL)
194 lafe_errc(1, 0, "Out of memory");
196 while ((opt = cpio_getopt(cpio)) != -1) {
198 case '0': /* GNU convention: --null, -0 */
199 cpio->option_null = 1;
201 case 'A': /* NetBSD/OpenBSD */
202 cpio->option_append = 1;
204 case 'a': /* POSIX 1997 */
205 cpio->option_atime_restore = 1;
207 case 'B': /* POSIX 1997 */
208 cpio->bytes_per_block = 5120;
210 case 'C': /* NetBSD/OpenBSD */
211 cpio->bytes_per_block = atoi(cpio->argument);
212 if (cpio->bytes_per_block <= 0)
213 lafe_errc(1, 0, "Invalid blocksize %s", cpio->argument);
215 case 'c': /* POSIX 1997 */
216 cpio->format = "odc";
218 case 'd': /* POSIX 1997 */
219 cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
221 case 'E': /* NetBSD/OpenBSD */
222 if (archive_match_include_pattern_from_file(
223 cpio->matching, cpio->argument,
224 cpio->option_null) != ARCHIVE_OK)
225 lafe_errc(1, 0, "Error : %s",
226 archive_error_string(cpio->matching));
228 case 'F': /* NetBSD/OpenBSD/GNU cpio */
229 cpio->filename = cpio->argument;
231 case 'f': /* POSIX 1997 */
232 if (archive_match_exclude_pattern(cpio->matching,
233 cpio->argument) != ARCHIVE_OK)
234 lafe_errc(1, 0, "Error : %s",
235 archive_error_string(cpio->matching));
237 case 'H': /* GNU cpio (also --format) */
238 cpio->format = cpio->argument;
243 case 'I': /* NetBSD/OpenBSD */
244 cpio->filename = cpio->argument;
246 case 'i': /* POSIX 1997 */
247 if (cpio->mode != '\0')
249 "Cannot use both -i and -%c", cpio->mode);
252 case 'J': /* GNU tar, others */
253 cpio->compress = opt;
255 case 'j': /* GNU tar, others */
256 cpio->compress = opt;
258 case OPTION_INSECURE:
259 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
260 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
262 case 'L': /* GNU cpio */
263 cpio->option_follow_links = 1;
265 case 'l': /* POSIX 1997 */
266 cpio->option_link = 1;
268 case OPTION_LZMA: /* GNU tar, others */
269 cpio->compress = opt;
271 case 'm': /* POSIX 1997 */
272 cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
274 case 'n': /* GNU cpio */
275 cpio->option_numeric_uid_gid = 1;
277 case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
278 cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
280 case 'O': /* GNU cpio */
281 cpio->filename = cpio->argument;
283 case 'o': /* POSIX 1997 */
284 if (cpio->mode != '\0')
286 "Cannot use both -o and -%c", cpio->mode);
289 case 'p': /* POSIX 1997 */
290 if (cpio->mode != '\0')
292 "Cannot use both -p and -%c", cpio->mode);
294 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
296 case OPTION_PRESERVE_OWNER:
297 cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
299 case OPTION_QUIET: /* GNU cpio */
302 case 'R': /* GNU cpio, also --owner */
303 /* TODO: owner_parse should return uname/gname
304 * also; use that to set [ug]name_override. */
305 errmsg = owner_parse(cpio->argument, &uid, &gid);
307 lafe_warnc(-1, "%s", errmsg);
311 cpio->uid_override = uid;
312 cpio->uname_override = NULL;
315 cpio->gid_override = gid;
316 cpio->gname_override = NULL;
319 case 'r': /* POSIX 1997 */
320 cpio->option_rename = 1;
322 case 't': /* POSIX 1997 */
323 cpio->option_list = 1;
325 case 'u': /* POSIX 1997 */
327 &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
329 case 'v': /* POSIX 1997 */
332 case 'V': /* GNU cpio */
335 case OPTION_VERSION: /* GNU convention */
340 * cpio_getopt() handles -W specially, so it's not
343 case 'W': /* Obscure, but useful GNU convention. */
346 case 'y': /* tar convention */
347 cpio->compress = opt;
349 case 'Z': /* tar convention */
350 cpio->compress = opt;
352 case 'z': /* tar convention */
353 cpio->compress = opt;
361 * Sanity-check args, error out on nonsensical combinations.
363 /* -t implies -i if no mode was specified. */
364 if (cpio->option_list && cpio->mode == '\0')
367 if (cpio->option_list && cpio->mode != 'i')
368 lafe_errc(1, 0, "Option -t requires -i");
369 /* -n requires -it */
370 if (cpio->option_numeric_uid_gid && !cpio->option_list)
371 lafe_errc(1, 0, "Option -n requires -it");
372 /* Can only specify format when writing */
373 if (cpio->format != NULL && cpio->mode != 'o')
374 lafe_errc(1, 0, "Option --format requires -o");
376 if (cpio->option_link && cpio->mode != 'p')
377 lafe_errc(1, 0, "Option -l requires -p");
378 /* -v overrides -V */
379 if (cpio->dot && cpio->verbose)
381 /* TODO: Flag other nonsensical combinations. */
383 switch (cpio->mode) {
385 /* TODO: Implement old binary format in libarchive,
387 if (cpio->format == NULL)
388 cpio->format = "odc"; /* Default format */
393 while (*cpio->argv != NULL) {
394 if (archive_match_include_pattern(cpio->matching,
395 *cpio->argv) != ARCHIVE_OK)
396 lafe_errc(1, 0, "Error : %s",
397 archive_error_string(cpio->matching));
401 if (cpio->option_list)
407 if (*cpio->argv == NULL || **cpio->argv == '\0')
409 "-p mode requires a target directory");
410 mode_pass(cpio, *cpio->argv);
414 "Must specify at least one of -i, -o, or -p");
417 archive_match_free(cpio->matching);
418 free_cache(cpio->gname_cache);
419 free_cache(cpio->uname_cache);
420 return (cpio->return_value);
430 fprintf(stderr, "Brief Usage:\n");
431 fprintf(stderr, " List: %s -it < archive\n", p);
432 fprintf(stderr, " Extract: %s -i < archive\n", p);
433 fprintf(stderr, " Create: %s -o < filenames > archive\n", p);
434 fprintf(stderr, " Help: %s --help\n", p);
438 static const char *long_help_msg =
439 "First option must be a mode specifier:\n"
440 " -i Input -o Output -p Pass\n"
442 " -v Verbose filenames -V one dot per file\n"
443 "Create: %p -o [options] < [list of files] > [archive]\n"
444 " -J,-y,-z,--lzma Compress archive with xz/bzip2/gzip/lzma\n"
445 " --format {odc|newc|ustar} Select archive format\n"
446 "List: %p -it < [archive]\n"
447 "Extract: %p -i [options] < [archive]\n";
451 * Note that the word 'bsdcpio' will always appear in the first line
454 * In particular, /bin/sh scripts that need to test for the presence
455 * of bsdcpio can use the following template:
457 * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
458 * echo bsdcpio; else echo not bsdcpio; fi
466 prog = lafe_progname;
470 p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
471 printf("%s%s: manipulate archive files\n", prog, p);
473 for (p = long_help_msg; *p != '\0'; p++) {
489 fprintf(stdout,"bsdcpio %s -- %s\n",
490 BSDCPIO_VERSION_STRING,
491 archive_version_string());
496 mode_out(struct cpio *cpio)
498 struct archive_entry *entry, *spare;
499 struct lafe_line_reader *lr;
503 if (cpio->option_append)
504 lafe_errc(1, 0, "Append mode not yet supported.");
506 cpio->archive_read_disk = archive_read_disk_new();
507 if (cpio->archive_read_disk == NULL)
508 lafe_errc(1, 0, "Failed to allocate archive object");
509 if (cpio->option_follow_links)
510 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
512 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
513 archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
515 cpio->archive = archive_write_new();
516 if (cpio->archive == NULL)
517 lafe_errc(1, 0, "Failed to allocate archive object");
518 switch (cpio->compress) {
520 r = archive_write_set_compression_xz(cpio->archive);
523 r = archive_write_set_compression_lzma(cpio->archive);
526 r = archive_write_set_compression_bzip2(cpio->archive);
529 r = archive_write_set_compression_gzip(cpio->archive);
532 r = archive_write_set_compression_compress(cpio->archive);
535 r = archive_write_set_compression_none(cpio->archive);
538 if (r < ARCHIVE_WARN)
539 lafe_errc(1, 0, "Requested compression not available");
540 r = archive_write_set_format_by_name(cpio->archive, cpio->format);
542 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
543 archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
544 cpio->linkresolver = archive_entry_linkresolver_new();
545 archive_entry_linkresolver_set_strategy(cpio->linkresolver,
546 archive_format(cpio->archive));
549 * The main loop: Copy each file into the output archive.
551 r = archive_write_open_file(cpio->archive, cpio->filename);
553 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
554 lr = lafe_line_reader("-", cpio->option_null);
555 while ((p = lafe_line_reader_next(lr)) != NULL)
556 file_to_archive(cpio, p);
557 lafe_line_reader_free(lr);
560 * The hardlink detection may have queued up a couple of entries
561 * that can now be flushed.
564 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
565 while (entry != NULL) {
566 entry_to_archive(cpio, entry);
567 archive_entry_free(entry);
569 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
572 r = archive_write_close(cpio->archive);
574 fprintf(stderr, "\n");
576 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
580 (archive_position_uncompressed(cpio->archive) + 511)
582 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
583 blocks == 1 ? "block" : "blocks");
585 archive_write_free(cpio->archive);
589 remove_leading_slash(const char *p)
593 /* Remove leading "//./" or "//?/" or "//?/UNC/"
594 * (absolute path prefixes used by Windows API) */
595 if ((p[0] == '/' || p[0] == '\\') &&
596 (p[1] == '/' || p[1] == '\\') &&
597 (p[2] == '.' || p[2] == '?') &&
598 (p[3] == '/' || p[3] == '\\'))
601 (p[4] == 'U' || p[4] == 'u') &&
602 (p[5] == 'N' || p[5] == 'n') &&
603 (p[6] == 'C' || p[6] == 'c') &&
604 (p[7] == '/' || p[7] == '\\'))
611 /* Remove leading drive letter from archives created
613 if (((p[0] >= 'a' && p[0] <= 'z') ||
614 (p[0] >= 'A' && p[0] <= 'Z')) &&
618 /* Remove leading "/../", "//", etc. */
619 while (p[0] == '/' || p[0] == '\\') {
620 if (p[1] == '.' && p[2] == '.' &&
621 (p[3] == '/' || p[3] == '\\')) {
622 p += 3; /* Remove "/..", leave "/"
625 p += 1; /* Remove "/". */
632 * This is used by both out mode (to copy objects from disk into
633 * an archive) and pass mode (to copy objects from disk to
634 * an archive_write_disk "archive").
637 file_to_archive(struct cpio *cpio, const char *srcpath)
639 const char *destpath;
640 struct archive_entry *entry, *spare;
645 * Create an archive_entry describing the source file.
648 entry = archive_entry_new();
650 lafe_errc(1, 0, "Couldn't allocate entry");
651 archive_entry_copy_sourcepath(entry, srcpath);
652 r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
654 if (r < ARCHIVE_FAILED)
655 lafe_errc(1, 0, "%s",
656 archive_error_string(cpio->archive_read_disk));
659 archive_error_string(cpio->archive_read_disk));
660 if (r <= ARCHIVE_FAILED) {
661 cpio->return_value = 1;
665 if (cpio->uid_override >= 0) {
666 archive_entry_set_uid(entry, cpio->uid_override);
667 archive_entry_set_uname(entry, cpio->uname_override);
669 if (cpio->gid_override >= 0) {
670 archive_entry_set_gid(entry, cpio->gid_override);
671 archive_entry_set_gname(entry, cpio->gname_override);
675 * Generate a destination path for this entry.
676 * "destination path" is the name to which it will be copied in
677 * pass mode or the name that will go into the archive in
682 len = strlen(cpio->destdir) + strlen(srcpath) + 8;
683 if (len >= cpio->pass_destpath_alloc) {
684 while (len >= cpio->pass_destpath_alloc) {
685 cpio->pass_destpath_alloc += 512;
686 cpio->pass_destpath_alloc *= 2;
688 free(cpio->pass_destpath);
689 cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
690 if (cpio->pass_destpath == NULL)
692 "Can't allocate path buffer");
694 strcpy(cpio->pass_destpath, cpio->destdir);
695 strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
696 destpath = cpio->pass_destpath;
698 if (cpio->option_rename)
699 destpath = cpio_rename(destpath);
700 if (destpath == NULL)
702 archive_entry_copy_pathname(entry, destpath);
705 * If we're trying to preserve hardlinks, match them here.
708 if (cpio->linkresolver != NULL
709 && archive_entry_filetype(entry) != AE_IFDIR) {
710 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
714 r = entry_to_archive(cpio, entry);
715 archive_entry_free(entry);
718 r = entry_to_archive(cpio, spare);
719 archive_entry_free(spare);
726 entry_to_archive(struct cpio *cpio, struct archive_entry *entry)
728 const char *destpath = archive_entry_pathname(entry);
729 const char *srcpath = archive_entry_sourcepath(entry);
734 /* Print out the destination name to the user. */
736 fprintf(stderr,"%s", destpath);
738 fprintf(stderr, ".");
741 * Option_link only makes sense in pass mode and for
742 * regular files. Also note: if a link operation fails
743 * because of cross-device restrictions, we'll fall back
744 * to copy mode for that entry.
746 * TODO: Test other cpio implementations to see if they
747 * hard-link anything other than regular files here.
749 if (cpio->option_link
750 && archive_entry_filetype(entry) == AE_IFREG)
752 struct archive_entry *t;
753 /* Save the original entry in case we need it later. */
754 t = archive_entry_clone(entry);
756 lafe_errc(1, ENOMEM, "Can't create link");
757 /* Note: link(2) doesn't create parent directories,
758 * so we use archive_write_header() instead as a
760 archive_entry_set_hardlink(t, srcpath);
761 /* This is a straight link that carries no data. */
762 archive_entry_set_size(t, 0);
763 r = archive_write_header(cpio->archive, t);
764 archive_entry_free(t);
766 lafe_warnc(archive_errno(cpio->archive),
767 "%s", archive_error_string(cpio->archive));
768 if (r == ARCHIVE_FATAL)
771 if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
772 /* Cross-device link: Just fall through and use
773 * the original entry to copy the file over. */
774 lafe_warnc(0, "Copying file instead");
781 * Make sure we can open the file (if necessary) before
782 * trying to write the header.
784 if (archive_entry_filetype(entry) == AE_IFREG) {
785 if (archive_entry_size(entry) > 0) {
786 fd = open(srcpath, O_RDONLY | O_BINARY);
789 "%s: could not open file", srcpath);
794 archive_entry_set_size(entry, 0);
797 r = archive_write_header(cpio->archive, entry);
800 lafe_warnc(archive_errno(cpio->archive),
803 archive_error_string(cpio->archive));
805 if (r == ARCHIVE_FATAL)
808 if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
809 bytes_read = read(fd, cpio->buff, cpio->buff_size);
810 while (bytes_read > 0) {
811 r = archive_write_data(cpio->archive,
812 cpio->buff, bytes_read);
814 lafe_errc(1, archive_errno(cpio->archive),
815 "%s", archive_error_string(cpio->archive));
816 if (r < bytes_read) {
818 "Truncated write; file may have grown while being archived.");
820 bytes_read = read(fd, cpio->buff, cpio->buff_size);
824 fd = restore_time(cpio, entry, srcpath, fd);
828 fprintf(stderr,"\n");
835 restore_time(struct cpio *cpio, struct archive_entry *entry,
836 const char *name, int fd)
839 static int warned = 0;
841 (void)cpio; /* UNUSED */
842 (void)entry; /* UNUSED */
843 (void)name; /* UNUSED */
846 lafe_warnc(0, "Can't restore access times on this platform");
850 #if defined(_WIN32) && !defined(__CYGWIN__)
851 struct __timeval times[2];
853 struct timeval times[2];
856 if (!cpio->option_atime_restore)
859 times[1].tv_sec = archive_entry_mtime(entry);
860 times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
862 times[0].tv_sec = archive_entry_atime(entry);
863 times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
865 #if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
866 if (fd >= 0 && futimes(fd, times) == 0)
870 * Some platform cannot restore access times if the file descriptor
879 if (lutimes(name, times) != 0)
881 if ((AE_IFLNK != archive_entry_filetype(entry))
882 && utimes(name, times) != 0)
884 lafe_warnc(errno, "Can't update time for %s", name);
891 mode_in(struct cpio *cpio)
894 struct archive_entry *entry;
896 const char *destpath;
899 ext = archive_write_disk_new();
901 lafe_errc(1, 0, "Couldn't allocate restore object");
902 r = archive_write_disk_set_options(ext, cpio->extract_flags);
904 lafe_errc(1, 0, "%s", archive_error_string(ext));
905 a = archive_read_new();
907 lafe_errc(1, 0, "Couldn't allocate archive object");
908 archive_read_support_filter_all(a);
909 archive_read_support_format_all(a);
911 if (archive_read_open_file(a, cpio->filename, cpio->bytes_per_block))
912 lafe_errc(1, archive_errno(a),
913 "%s", archive_error_string(a));
915 r = archive_read_next_header(a, &entry);
916 if (r == ARCHIVE_EOF)
918 if (r != ARCHIVE_OK) {
919 lafe_errc(1, archive_errno(a),
920 "%s", archive_error_string(a));
922 if (archive_match_path_excluded(cpio->matching, entry))
924 if (cpio->option_rename) {
925 destpath = cpio_rename(archive_entry_pathname(entry));
926 archive_entry_set_pathname(entry, destpath);
928 destpath = archive_entry_pathname(entry);
929 if (destpath == NULL)
932 fprintf(stderr, "%s\n", destpath);
934 fprintf(stderr, ".");
935 if (cpio->uid_override >= 0)
936 archive_entry_set_uid(entry, cpio->uid_override);
937 if (cpio->gid_override >= 0)
938 archive_entry_set_gid(entry, cpio->gid_override);
939 r = archive_write_header(ext, entry);
940 if (r != ARCHIVE_OK) {
941 fprintf(stderr, "%s: %s\n",
942 archive_entry_pathname(entry),
943 archive_error_string(ext));
944 } else if (!archive_entry_size_is_set(entry)
945 || archive_entry_size(entry) > 0) {
946 r = extract_data(a, ext);
948 cpio->return_value = 1;
951 r = archive_read_close(a);
953 fprintf(stderr, "\n");
955 lafe_errc(1, 0, "%s", archive_error_string(a));
956 r = archive_write_close(ext);
958 lafe_errc(1, 0, "%s", archive_error_string(ext));
960 int64_t blocks = (archive_position_uncompressed(a) + 511)
962 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
963 blocks == 1 ? "block" : "blocks");
965 archive_read_free(a);
966 archive_write_free(ext);
967 exit(cpio->return_value);
971 * Exits if there's a fatal error. Returns ARCHIVE_OK
972 * if everything is kosher.
975 extract_data(struct archive *ar, struct archive *aw)
983 r = archive_read_data_block(ar, &block, &size, &offset);
984 if (r == ARCHIVE_EOF)
986 if (r != ARCHIVE_OK) {
987 lafe_warnc(archive_errno(ar),
988 "%s", archive_error_string(ar));
991 r = archive_write_data_block(aw, block, size, offset);
992 if (r != ARCHIVE_OK) {
993 lafe_warnc(archive_errno(aw),
994 "%s", archive_error_string(aw));
1001 mode_list(struct cpio *cpio)
1004 struct archive_entry *entry;
1007 a = archive_read_new();
1009 lafe_errc(1, 0, "Couldn't allocate archive object");
1010 archive_read_support_filter_all(a);
1011 archive_read_support_format_all(a);
1013 if (archive_read_open_file(a, cpio->filename, cpio->bytes_per_block))
1014 lafe_errc(1, archive_errno(a),
1015 "%s", archive_error_string(a));
1017 r = archive_read_next_header(a, &entry);
1018 if (r == ARCHIVE_EOF)
1020 if (r != ARCHIVE_OK) {
1021 lafe_errc(1, archive_errno(a),
1022 "%s", archive_error_string(a));
1024 if (archive_match_path_excluded(cpio->matching, entry))
1027 list_item_verbose(cpio, entry);
1029 fprintf(stdout, "%s\n", archive_entry_pathname(entry));
1031 r = archive_read_close(a);
1032 if (r != ARCHIVE_OK)
1033 lafe_errc(1, 0, "%s", archive_error_string(a));
1035 int64_t blocks = (archive_position_uncompressed(a) + 511)
1037 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1038 blocks == 1 ? "block" : "blocks");
1040 archive_read_free(a);
1045 * Display information about the current file.
1047 * The format here roughly duplicates the output of 'ls -l'.
1048 * This is based on SUSv2, where 'tar tv' is documented as
1049 * listing additional information in an "unspecified format,"
1050 * and 'pax -l' is documented as using the same format as 'ls -l'.
1053 list_item_verbose(struct cpio *cpio, struct archive_entry *entry)
1057 char uids[16], gids[16];
1058 const char *uname, *gname;
1067 if (cpio->option_numeric_uid_gid) {
1068 /* Format numeric uid/gid for display. */
1069 strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
1071 strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
1074 /* Use uname if it's present, else lookup name from uid. */
1075 uname = archive_entry_uname(entry);
1077 uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
1078 /* Use gname if it's present, else lookup name from gid. */
1079 gname = archive_entry_gname(entry);
1081 gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
1084 /* Print device number or file size. */
1085 if (archive_entry_filetype(entry) == AE_IFCHR
1086 || archive_entry_filetype(entry) == AE_IFBLK) {
1087 snprintf(size, sizeof(size), "%lu,%lu",
1088 (unsigned long)archive_entry_rdevmajor(entry),
1089 (unsigned long)archive_entry_rdevminor(entry));
1091 strcpy(size, cpio_i64toa(archive_entry_size(entry)));
1094 /* Format the time using 'ls -l' conventions. */
1095 mtime = archive_entry_mtime(entry);
1096 #if defined(_WIN32) && !defined(__CYGWIN__)
1097 /* Windows' strftime function does not support %e format. */
1098 if (mtime - now > 365*86400/2
1099 || mtime - now < -365*86400/2)
1100 fmt = cpio->day_first ? "%d %b %Y" : "%b %d %Y";
1102 fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
1104 if (abs(mtime - now) > (365/2)*86400)
1105 fmt = cpio->day_first ? "%e %b %Y" : "%b %e %Y";
1107 fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
1109 strftime(date, sizeof(date), fmt, localtime(&mtime));
1111 fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
1112 archive_entry_strmode(entry),
1113 archive_entry_nlink(entry),
1114 uname, gname, size, date,
1115 archive_entry_pathname(entry));
1117 /* Extra information for links. */
1118 if (archive_entry_hardlink(entry)) /* Hard link */
1119 fprintf(out, " link to %s", archive_entry_hardlink(entry));
1120 else if (archive_entry_symlink(entry)) /* Symbolic link */
1121 fprintf(out, " -> %s", archive_entry_symlink(entry));
1126 mode_pass(struct cpio *cpio, const char *destdir)
1128 struct lafe_line_reader *lr;
1132 /* Ensure target dir has a trailing '/' to simplify path surgery. */
1133 cpio->destdir = malloc(strlen(destdir) + 8);
1134 strcpy(cpio->destdir, destdir);
1135 if (destdir[strlen(destdir) - 1] != '/')
1136 strcat(cpio->destdir, "/");
1138 cpio->archive = archive_write_disk_new();
1139 if (cpio->archive == NULL)
1140 lafe_errc(1, 0, "Failed to allocate archive object");
1141 r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
1142 if (r != ARCHIVE_OK)
1143 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1144 cpio->linkresolver = archive_entry_linkresolver_new();
1145 archive_write_disk_set_standard_lookup(cpio->archive);
1147 cpio->archive_read_disk = archive_read_disk_new();
1148 if (cpio->archive_read_disk == NULL)
1149 lafe_errc(1, 0, "Failed to allocate archive object");
1150 if (cpio->option_follow_links)
1151 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
1153 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
1154 archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
1156 lr = lafe_line_reader("-", cpio->option_null);
1157 while ((p = lafe_line_reader_next(lr)) != NULL)
1158 file_to_archive(cpio, p);
1159 lafe_line_reader_free(lr);
1161 archive_entry_linkresolver_free(cpio->linkresolver);
1162 r = archive_write_close(cpio->archive);
1164 fprintf(stderr, "\n");
1165 if (r != ARCHIVE_OK)
1166 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1170 (archive_position_uncompressed(cpio->archive) + 511)
1172 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1173 blocks == 1 ? "block" : "blocks");
1176 archive_write_free(cpio->archive);
1180 * Prompt for a new name for this entry. Returns a pointer to the
1181 * new name or NULL if the entry should not be copied. This
1182 * implements the semantics defined in POSIX.1-1996, which specifies
1183 * that an input of '.' means the name should be unchanged. GNU cpio
1184 * treats '.' as a literal new name.
1187 cpio_rename(const char *name)
1189 static char buff[1024];
1192 #if defined(_WIN32) && !defined(__CYGWIN__)
1195 t = fopen("CONIN$", "r");
1198 to = fopen("CONOUT$", "w");
1201 fprintf(to, "%s (Enter/./(new name))? ", name);
1204 t = fopen("/dev/tty", "r+");
1207 fprintf(t, "%s (Enter/./(new name))? ", name);
1211 p = fgets(buff, sizeof(buff), t);
1214 /* End-of-file is a blank line. */
1217 while (*p == ' ' || *p == '\t')
1219 if (*p == '\n' || *p == '\0')
1222 if (*p == '.' && p[1] == '\n')
1223 /* Single period preserves original name. */
1226 /* Trim the final newline. */
1227 while (*p != '\0' && *p != '\n')
1229 /* Overwrite the final \n with a null character. */
1235 free_cache(struct name_cache *cache)
1239 if (cache != NULL) {
1240 for (i = 0; i < cache->size; i++)
1241 free(cache->cache[i].name);
1247 * Lookup uname/gname from uid/gid, return NULL if no match.
1250 lookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
1251 int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
1254 struct name_cache *cache;
1259 if (*name_cache_variable == NULL) {
1260 *name_cache_variable = malloc(sizeof(struct name_cache));
1261 if (*name_cache_variable == NULL)
1262 lafe_errc(1, ENOMEM, "No more memory");
1263 memset(*name_cache_variable, 0, sizeof(struct name_cache));
1264 (*name_cache_variable)->size = name_cache_size;
1267 cache = *name_cache_variable;
1270 slot = id % cache->size;
1271 if (cache->cache[slot].name != NULL) {
1272 if (cache->cache[slot].id == id) {
1274 return (cache->cache[slot].name);
1276 free(cache->cache[slot].name);
1277 cache->cache[slot].name = NULL;
1280 if (lookup_fn(cpio, &name, id) == 0) {
1281 if (name == NULL || name[0] == '\0') {
1282 /* If lookup failed, format it as a number. */
1283 snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
1286 cache->cache[slot].name = strdup(name);
1287 if (cache->cache[slot].name != NULL) {
1288 cache->cache[slot].id = id;
1289 return (cache->cache[slot].name);
1292 * Conveniently, NULL marks an empty slot, so
1293 * if the strdup() fails, we've just failed to
1294 * cache it. No recovery necessary.
1301 lookup_uname(struct cpio *cpio, uid_t uid)
1303 return (lookup_name(cpio, &cpio->uname_cache,
1304 &lookup_uname_helper, (id_t)uid));
1308 lookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
1310 struct passwd *pwent;
1312 (void)cpio; /* UNUSED */
1315 pwent = getpwuid((uid_t)id);
1316 if (pwent == NULL) {
1318 if (errno != 0 && errno != ENOENT)
1319 lafe_warnc(errno, "getpwuid(%s) failed",
1320 cpio_i64toa((int64_t)id));
1324 *name = pwent->pw_name;
1329 lookup_gname(struct cpio *cpio, gid_t gid)
1331 return (lookup_name(cpio, &cpio->gname_cache,
1332 &lookup_gname_helper, (id_t)gid));
1336 lookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
1338 struct group *grent;
1340 (void)cpio; /* UNUSED */
1343 grent = getgrgid((gid_t)id);
1344 if (grent == NULL) {
1347 lafe_warnc(errno, "getgrgid(%s) failed",
1348 cpio_i64toa((int64_t)id));
1352 *name = grent->gr_name;
1357 * It would be nice to just use printf() for formatting large numbers,
1358 * but the compatibility problems are a big headache. Hence the
1359 * following simple utility function.
1362 cpio_i64toa(int64_t n0)
1364 /* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
1365 * We also need 1 byte for '-' and 1 for '\0'.
1367 static char buff[22];
1368 int64_t n = n0 < 0 ? -n0 : n0;
1369 char *p = buff + sizeof(buff);
1373 *--p = '0' + (int)(n % 10);