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$");
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_SECURE_NOABSOLUTEPATHS;
183 cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
184 cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
185 cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
186 #if !defined(_WIN32) && !defined(__CYGWIN__)
188 cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
190 cpio->bytes_per_block = 512;
191 cpio->filename = NULL;
193 cpio->matching = archive_match_new();
194 if (cpio->matching == NULL)
195 lafe_errc(1, 0, "Out of memory");
197 while ((opt = cpio_getopt(cpio)) != -1) {
199 case '0': /* GNU convention: --null, -0 */
200 cpio->option_null = 1;
202 case 'A': /* NetBSD/OpenBSD */
203 cpio->option_append = 1;
205 case 'a': /* POSIX 1997 */
206 cpio->option_atime_restore = 1;
208 case 'B': /* POSIX 1997 */
209 cpio->bytes_per_block = 5120;
211 case OPTION_B64ENCODE:
212 cpio->add_filter = opt;
214 case 'C': /* NetBSD/OpenBSD */
215 cpio->bytes_per_block = atoi(cpio->argument);
216 if (cpio->bytes_per_block <= 0)
217 lafe_errc(1, 0, "Invalid blocksize %s", cpio->argument);
219 case 'c': /* POSIX 1997 */
220 cpio->format = "odc";
222 case 'd': /* POSIX 1997 */
223 cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
225 case 'E': /* NetBSD/OpenBSD */
226 if (archive_match_include_pattern_from_file(
227 cpio->matching, cpio->argument,
228 cpio->option_null) != ARCHIVE_OK)
229 lafe_errc(1, 0, "Error : %s",
230 archive_error_string(cpio->matching));
232 case 'F': /* NetBSD/OpenBSD/GNU cpio */
233 cpio->filename = cpio->argument;
235 case 'f': /* POSIX 1997 */
236 if (archive_match_exclude_pattern(cpio->matching,
237 cpio->argument) != ARCHIVE_OK)
238 lafe_errc(1, 0, "Error : %s",
239 archive_error_string(cpio->matching));
242 cpio->compress = opt;
244 case 'H': /* GNU cpio (also --format) */
245 cpio->format = cpio->argument;
250 case 'I': /* NetBSD/OpenBSD */
251 cpio->filename = cpio->argument;
253 case 'i': /* POSIX 1997 */
254 if (cpio->mode != '\0')
256 "Cannot use both -i and -%c", cpio->mode);
259 case 'J': /* GNU tar, others */
260 cpio->compress = opt;
262 case 'j': /* GNU tar, others */
263 cpio->compress = opt;
265 case OPTION_INSECURE:
266 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
267 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
268 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
270 case 'L': /* GNU cpio */
271 cpio->option_follow_links = 1;
273 case 'l': /* POSIX 1997 */
274 cpio->option_link = 1;
277 case OPTION_LZMA: /* GNU tar, others */
278 case OPTION_LZOP: /* GNU tar, others */
279 cpio->compress = opt;
281 case 'm': /* POSIX 1997 */
282 cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
284 case 'n': /* GNU cpio */
285 cpio->option_numeric_uid_gid = 1;
287 case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
288 cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
290 case 'O': /* GNU cpio */
291 cpio->filename = cpio->argument;
293 case 'o': /* POSIX 1997 */
294 if (cpio->mode != '\0')
296 "Cannot use both -o and -%c", cpio->mode);
299 case 'p': /* POSIX 1997 */
300 if (cpio->mode != '\0')
302 "Cannot use both -p and -%c", cpio->mode);
304 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
305 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
307 case OPTION_PRESERVE_OWNER:
308 cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
310 case OPTION_QUIET: /* GNU cpio */
313 case 'R': /* GNU cpio, also --owner */
314 /* TODO: owner_parse should return uname/gname
315 * also; use that to set [ug]name_override. */
316 errmsg = owner_parse(cpio->argument, &uid, &gid);
318 lafe_warnc(-1, "%s", errmsg);
322 cpio->uid_override = uid;
323 cpio->uname_override = NULL;
326 cpio->gid_override = gid;
327 cpio->gname_override = NULL;
330 case 'r': /* POSIX 1997 */
331 cpio->option_rename = 1;
333 case 't': /* POSIX 1997 */
334 cpio->option_list = 1;
336 case 'u': /* POSIX 1997 */
338 &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
340 case OPTION_UUENCODE:
341 cpio->add_filter = opt;
343 case 'v': /* POSIX 1997 */
346 case 'V': /* GNU cpio */
349 case OPTION_VERSION: /* GNU convention */
354 * cpio_getopt() handles -W specially, so it's not
357 case 'W': /* Obscure, but useful GNU convention. */
360 case 'y': /* tar convention */
361 cpio->compress = opt;
363 case 'Z': /* tar convention */
364 cpio->compress = opt;
366 case 'z': /* tar convention */
367 cpio->compress = opt;
375 * Sanity-check args, error out on nonsensical combinations.
377 /* -t implies -i if no mode was specified. */
378 if (cpio->option_list && cpio->mode == '\0')
381 if (cpio->option_list && cpio->mode != 'i')
382 lafe_errc(1, 0, "Option -t requires -i");
383 /* -n requires -it */
384 if (cpio->option_numeric_uid_gid && !cpio->option_list)
385 lafe_errc(1, 0, "Option -n requires -it");
386 /* Can only specify format when writing */
387 if (cpio->format != NULL && cpio->mode != 'o')
388 lafe_errc(1, 0, "Option --format requires -o");
390 if (cpio->option_link && cpio->mode != 'p')
391 lafe_errc(1, 0, "Option -l requires -p");
392 /* -v overrides -V */
393 if (cpio->dot && cpio->verbose)
395 /* TODO: Flag other nonsensical combinations. */
397 switch (cpio->mode) {
399 /* TODO: Implement old binary format in libarchive,
401 if (cpio->format == NULL)
402 cpio->format = "odc"; /* Default format */
407 while (*cpio->argv != NULL) {
408 if (archive_match_include_pattern(cpio->matching,
409 *cpio->argv) != ARCHIVE_OK)
410 lafe_errc(1, 0, "Error : %s",
411 archive_error_string(cpio->matching));
415 if (cpio->option_list)
421 if (*cpio->argv == NULL || **cpio->argv == '\0')
423 "-p mode requires a target directory");
424 mode_pass(cpio, *cpio->argv);
428 "Must specify at least one of -i, -o, or -p");
431 archive_match_free(cpio->matching);
432 free_cache(cpio->gname_cache);
433 free_cache(cpio->uname_cache);
435 return (cpio->return_value);
445 fprintf(stderr, "Brief Usage:\n");
446 fprintf(stderr, " List: %s -it < archive\n", p);
447 fprintf(stderr, " Extract: %s -i < archive\n", p);
448 fprintf(stderr, " Create: %s -o < filenames > archive\n", p);
449 fprintf(stderr, " Help: %s --help\n", p);
453 static const char *long_help_msg =
454 "First option must be a mode specifier:\n"
455 " -i Input -o Output -p Pass\n"
457 " -v Verbose filenames -V one dot per file\n"
458 "Create: %p -o [options] < [list of files] > [archive]\n"
459 " -J,-y,-z,--lzma Compress archive with xz/bzip2/gzip/lzma\n"
460 " --format {odc|newc|ustar} Select archive format\n"
461 "List: %p -it < [archive]\n"
462 "Extract: %p -i [options] < [archive]\n";
466 * Note that the word 'bsdcpio' will always appear in the first line
469 * In particular, /bin/sh scripts that need to test for the presence
470 * of bsdcpio can use the following template:
472 * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
473 * echo bsdcpio; else echo not bsdcpio; fi
481 prog = lafe_progname;
485 p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
486 printf("%s%s: manipulate archive files\n", prog, p);
488 for (p = long_help_msg; *p != '\0'; p++) {
504 fprintf(stdout,"bsdcpio %s -- %s\n",
505 BSDCPIO_VERSION_STRING,
506 archive_version_string());
511 mode_out(struct cpio *cpio)
513 struct archive_entry *entry, *spare;
514 struct lafe_line_reader *lr;
518 if (cpio->option_append)
519 lafe_errc(1, 0, "Append mode not yet supported.");
521 cpio->archive_read_disk = archive_read_disk_new();
522 if (cpio->archive_read_disk == NULL)
523 lafe_errc(1, 0, "Failed to allocate archive object");
524 if (cpio->option_follow_links)
525 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
527 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
528 archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
530 cpio->archive = archive_write_new();
531 if (cpio->archive == NULL)
532 lafe_errc(1, 0, "Failed to allocate archive object");
533 switch (cpio->compress) {
535 r = archive_write_add_filter_grzip(cpio->archive);
538 r = archive_write_add_filter_xz(cpio->archive);
541 r = archive_write_add_filter_lrzip(cpio->archive);
544 r = archive_write_add_filter_lzma(cpio->archive);
547 r = archive_write_add_filter_lzop(cpio->archive);
550 r = archive_write_add_filter_bzip2(cpio->archive);
553 r = archive_write_add_filter_gzip(cpio->archive);
556 r = archive_write_add_filter_compress(cpio->archive);
559 r = archive_write_add_filter_none(cpio->archive);
562 if (r < ARCHIVE_WARN)
563 lafe_errc(1, 0, "Requested compression not available");
564 switch (cpio->add_filter) {
568 case OPTION_B64ENCODE:
569 r = archive_write_add_filter_b64encode(cpio->archive);
571 case OPTION_UUENCODE:
572 r = archive_write_add_filter_uuencode(cpio->archive);
575 if (r < ARCHIVE_WARN)
576 lafe_errc(1, 0, "Requested filter not available");
577 r = archive_write_set_format_by_name(cpio->archive, cpio->format);
579 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
580 archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
581 cpio->linkresolver = archive_entry_linkresolver_new();
582 archive_entry_linkresolver_set_strategy(cpio->linkresolver,
583 archive_format(cpio->archive));
586 * The main loop: Copy each file into the output archive.
588 r = archive_write_open_filename(cpio->archive, cpio->filename);
590 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
591 lr = lafe_line_reader("-", cpio->option_null);
592 while ((p = lafe_line_reader_next(lr)) != NULL)
593 file_to_archive(cpio, p);
594 lafe_line_reader_free(lr);
597 * The hardlink detection may have queued up a couple of entries
598 * that can now be flushed.
601 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
602 while (entry != NULL) {
603 entry_to_archive(cpio, entry);
604 archive_entry_free(entry);
606 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
609 r = archive_write_close(cpio->archive);
611 fprintf(stderr, "\n");
613 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
617 (archive_filter_bytes(cpio->archive, 0) + 511)
619 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
620 blocks == 1 ? "block" : "blocks");
622 archive_write_free(cpio->archive);
626 remove_leading_slash(const char *p)
630 /* Remove leading "//./" or "//?/" or "//?/UNC/"
631 * (absolute path prefixes used by Windows API) */
632 if ((p[0] == '/' || p[0] == '\\') &&
633 (p[1] == '/' || p[1] == '\\') &&
634 (p[2] == '.' || p[2] == '?') &&
635 (p[3] == '/' || p[3] == '\\'))
638 (p[4] == 'U' || p[4] == 'u') &&
639 (p[5] == 'N' || p[5] == 'n') &&
640 (p[6] == 'C' || p[6] == 'c') &&
641 (p[7] == '/' || p[7] == '\\'))
648 /* Remove leading drive letter from archives created
650 if (((p[0] >= 'a' && p[0] <= 'z') ||
651 (p[0] >= 'A' && p[0] <= 'Z')) &&
655 /* Remove leading "/../", "//", etc. */
656 while (p[0] == '/' || p[0] == '\\') {
657 if (p[1] == '.' && p[2] == '.' &&
658 (p[3] == '/' || p[3] == '\\')) {
659 p += 3; /* Remove "/..", leave "/"
662 p += 1; /* Remove "/". */
669 * This is used by both out mode (to copy objects from disk into
670 * an archive) and pass mode (to copy objects from disk to
671 * an archive_write_disk "archive").
674 file_to_archive(struct cpio *cpio, const char *srcpath)
676 const char *destpath;
677 struct archive_entry *entry, *spare;
682 * Create an archive_entry describing the source file.
685 entry = archive_entry_new();
687 lafe_errc(1, 0, "Couldn't allocate entry");
688 archive_entry_copy_sourcepath(entry, srcpath);
689 r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
691 if (r < ARCHIVE_FAILED)
692 lafe_errc(1, 0, "%s",
693 archive_error_string(cpio->archive_read_disk));
696 archive_error_string(cpio->archive_read_disk));
697 if (r <= ARCHIVE_FAILED) {
698 cpio->return_value = 1;
702 if (cpio->uid_override >= 0) {
703 archive_entry_set_uid(entry, cpio->uid_override);
704 archive_entry_set_uname(entry, cpio->uname_override);
706 if (cpio->gid_override >= 0) {
707 archive_entry_set_gid(entry, cpio->gid_override);
708 archive_entry_set_gname(entry, cpio->gname_override);
712 * Generate a destination path for this entry.
713 * "destination path" is the name to which it will be copied in
714 * pass mode or the name that will go into the archive in
719 len = strlen(cpio->destdir) + strlen(srcpath) + 8;
720 if (len >= cpio->pass_destpath_alloc) {
721 while (len >= cpio->pass_destpath_alloc) {
722 cpio->pass_destpath_alloc += 512;
723 cpio->pass_destpath_alloc *= 2;
725 free(cpio->pass_destpath);
726 cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
727 if (cpio->pass_destpath == NULL)
729 "Can't allocate path buffer");
731 strcpy(cpio->pass_destpath, cpio->destdir);
732 strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
733 destpath = cpio->pass_destpath;
735 if (cpio->option_rename)
736 destpath = cpio_rename(destpath);
737 if (destpath == NULL)
739 archive_entry_copy_pathname(entry, destpath);
742 * If we're trying to preserve hardlinks, match them here.
745 if (cpio->linkresolver != NULL
746 && archive_entry_filetype(entry) != AE_IFDIR) {
747 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
751 r = entry_to_archive(cpio, entry);
752 archive_entry_free(entry);
755 r = entry_to_archive(cpio, spare);
756 archive_entry_free(spare);
763 entry_to_archive(struct cpio *cpio, struct archive_entry *entry)
765 const char *destpath = archive_entry_pathname(entry);
766 const char *srcpath = archive_entry_sourcepath(entry);
771 /* Print out the destination name to the user. */
773 fprintf(stderr,"%s", destpath);
775 fprintf(stderr, ".");
778 * Option_link only makes sense in pass mode and for
779 * regular files. Also note: if a link operation fails
780 * because of cross-device restrictions, we'll fall back
781 * to copy mode for that entry.
783 * TODO: Test other cpio implementations to see if they
784 * hard-link anything other than regular files here.
786 if (cpio->option_link
787 && archive_entry_filetype(entry) == AE_IFREG)
789 struct archive_entry *t;
790 /* Save the original entry in case we need it later. */
791 t = archive_entry_clone(entry);
793 lafe_errc(1, ENOMEM, "Can't create link");
794 /* Note: link(2) doesn't create parent directories,
795 * so we use archive_write_header() instead as a
797 archive_entry_set_hardlink(t, srcpath);
798 /* This is a straight link that carries no data. */
799 archive_entry_set_size(t, 0);
800 r = archive_write_header(cpio->archive, t);
801 archive_entry_free(t);
803 lafe_warnc(archive_errno(cpio->archive),
804 "%s", archive_error_string(cpio->archive));
805 if (r == ARCHIVE_FATAL)
808 if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
809 /* Cross-device link: Just fall through and use
810 * the original entry to copy the file over. */
811 lafe_warnc(0, "Copying file instead");
818 * Make sure we can open the file (if necessary) before
819 * trying to write the header.
821 if (archive_entry_filetype(entry) == AE_IFREG) {
822 if (archive_entry_size(entry) > 0) {
823 fd = open(srcpath, O_RDONLY | O_BINARY);
826 "%s: could not open file", srcpath);
831 archive_entry_set_size(entry, 0);
834 r = archive_write_header(cpio->archive, entry);
837 lafe_warnc(archive_errno(cpio->archive),
840 archive_error_string(cpio->archive));
842 if (r == ARCHIVE_FATAL)
845 if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
846 bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size);
847 while (bytes_read > 0) {
849 bytes_write = archive_write_data(cpio->archive,
850 cpio->buff, bytes_read);
852 lafe_errc(1, archive_errno(cpio->archive),
853 "%s", archive_error_string(cpio->archive));
854 if (bytes_write < bytes_read) {
856 "Truncated write; file may have "
857 "grown while being archived.");
859 bytes_read = read(fd, cpio->buff,
860 (unsigned)cpio->buff_size);
864 fd = restore_time(cpio, entry, srcpath, fd);
868 fprintf(stderr,"\n");
875 restore_time(struct cpio *cpio, struct archive_entry *entry,
876 const char *name, int fd)
879 static int warned = 0;
881 (void)cpio; /* UNUSED */
882 (void)entry; /* UNUSED */
883 (void)name; /* UNUSED */
886 lafe_warnc(0, "Can't restore access times on this platform");
890 #if defined(_WIN32) && !defined(__CYGWIN__)
891 struct __timeval times[2];
893 struct timeval times[2];
896 if (!cpio->option_atime_restore)
899 times[1].tv_sec = archive_entry_mtime(entry);
900 times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
902 times[0].tv_sec = archive_entry_atime(entry);
903 times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
905 #if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
906 if (fd >= 0 && futimes(fd, times) == 0)
910 * Some platform cannot restore access times if the file descriptor
919 if (lutimes(name, times) != 0)
921 if ((AE_IFLNK != archive_entry_filetype(entry))
922 && utimes(name, times) != 0)
924 lafe_warnc(errno, "Can't update time for %s", name);
931 mode_in(struct cpio *cpio)
934 struct archive_entry *entry;
936 const char *destpath;
939 ext = archive_write_disk_new();
941 lafe_errc(1, 0, "Couldn't allocate restore object");
942 r = archive_write_disk_set_options(ext, cpio->extract_flags);
944 lafe_errc(1, 0, "%s", archive_error_string(ext));
945 a = archive_read_new();
947 lafe_errc(1, 0, "Couldn't allocate archive object");
948 archive_read_support_filter_all(a);
949 archive_read_support_format_all(a);
951 if (archive_read_open_filename(a, cpio->filename,
952 cpio->bytes_per_block))
953 lafe_errc(1, archive_errno(a),
954 "%s", archive_error_string(a));
956 r = archive_read_next_header(a, &entry);
957 if (r == ARCHIVE_EOF)
959 if (r != ARCHIVE_OK) {
960 lafe_errc(1, archive_errno(a),
961 "%s", archive_error_string(a));
963 if (archive_match_path_excluded(cpio->matching, entry))
965 if (cpio->option_rename) {
966 destpath = cpio_rename(archive_entry_pathname(entry));
967 archive_entry_set_pathname(entry, destpath);
969 destpath = archive_entry_pathname(entry);
970 if (destpath == NULL)
973 fprintf(stderr, "%s\n", destpath);
975 fprintf(stderr, ".");
976 if (cpio->uid_override >= 0)
977 archive_entry_set_uid(entry, cpio->uid_override);
978 if (cpio->gid_override >= 0)
979 archive_entry_set_gid(entry, cpio->gid_override);
980 r = archive_write_header(ext, entry);
981 if (r != ARCHIVE_OK) {
982 fprintf(stderr, "%s: %s\n",
983 archive_entry_pathname(entry),
984 archive_error_string(ext));
985 } else if (!archive_entry_size_is_set(entry)
986 || archive_entry_size(entry) > 0) {
987 r = extract_data(a, ext);
989 cpio->return_value = 1;
992 r = archive_read_close(a);
994 fprintf(stderr, "\n");
996 lafe_errc(1, 0, "%s", archive_error_string(a));
997 r = archive_write_close(ext);
999 lafe_errc(1, 0, "%s", archive_error_string(ext));
1001 int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1003 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1004 blocks == 1 ? "block" : "blocks");
1006 archive_read_free(a);
1007 archive_write_free(ext);
1008 exit(cpio->return_value);
1012 * Exits if there's a fatal error. Returns ARCHIVE_OK
1013 * if everything is kosher.
1016 extract_data(struct archive *ar, struct archive *aw)
1024 r = archive_read_data_block(ar, &block, &size, &offset);
1025 if (r == ARCHIVE_EOF)
1026 return (ARCHIVE_OK);
1027 if (r != ARCHIVE_OK) {
1028 lafe_warnc(archive_errno(ar),
1029 "%s", archive_error_string(ar));
1032 r = (int)archive_write_data_block(aw, block, size, offset);
1033 if (r != ARCHIVE_OK) {
1034 lafe_warnc(archive_errno(aw),
1035 "%s", archive_error_string(aw));
1042 mode_list(struct cpio *cpio)
1045 struct archive_entry *entry;
1048 a = archive_read_new();
1050 lafe_errc(1, 0, "Couldn't allocate archive object");
1051 archive_read_support_filter_all(a);
1052 archive_read_support_format_all(a);
1054 if (archive_read_open_filename(a, cpio->filename,
1055 cpio->bytes_per_block))
1056 lafe_errc(1, archive_errno(a),
1057 "%s", archive_error_string(a));
1059 r = archive_read_next_header(a, &entry);
1060 if (r == ARCHIVE_EOF)
1062 if (r != ARCHIVE_OK) {
1063 lafe_errc(1, archive_errno(a),
1064 "%s", archive_error_string(a));
1066 if (archive_match_path_excluded(cpio->matching, entry))
1069 list_item_verbose(cpio, entry);
1071 fprintf(stdout, "%s\n", archive_entry_pathname(entry));
1073 r = archive_read_close(a);
1074 if (r != ARCHIVE_OK)
1075 lafe_errc(1, 0, "%s", archive_error_string(a));
1077 int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1079 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1080 blocks == 1 ? "block" : "blocks");
1082 archive_read_free(a);
1087 * Display information about the current file.
1089 * The format here roughly duplicates the output of 'ls -l'.
1090 * This is based on SUSv2, where 'tar tv' is documented as
1091 * listing additional information in an "unspecified format,"
1092 * and 'pax -l' is documented as using the same format as 'ls -l'.
1095 list_item_verbose(struct cpio *cpio, struct archive_entry *entry)
1099 char uids[16], gids[16];
1100 const char *uname, *gname;
1109 if (cpio->option_numeric_uid_gid) {
1110 /* Format numeric uid/gid for display. */
1111 strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
1113 strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
1116 /* Use uname if it's present, else lookup name from uid. */
1117 uname = archive_entry_uname(entry);
1119 uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
1120 /* Use gname if it's present, else lookup name from gid. */
1121 gname = archive_entry_gname(entry);
1123 gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
1126 /* Print device number or file size. */
1127 if (archive_entry_filetype(entry) == AE_IFCHR
1128 || archive_entry_filetype(entry) == AE_IFBLK) {
1129 snprintf(size, sizeof(size), "%lu,%lu",
1130 (unsigned long)archive_entry_rdevmajor(entry),
1131 (unsigned long)archive_entry_rdevminor(entry));
1133 strcpy(size, cpio_i64toa(archive_entry_size(entry)));
1136 /* Format the time using 'ls -l' conventions. */
1137 mtime = archive_entry_mtime(entry);
1138 #if defined(_WIN32) && !defined(__CYGWIN__)
1139 /* Windows' strftime function does not support %e format. */
1140 if (mtime - now > 365*86400/2
1141 || mtime - now < -365*86400/2)
1142 fmt = cpio->day_first ? "%d %b %Y" : "%b %d %Y";
1144 fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
1146 if (mtime - now > 365*86400/2
1147 || mtime - now < -365*86400/2)
1148 fmt = cpio->day_first ? "%e %b %Y" : "%b %e %Y";
1150 fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
1152 strftime(date, sizeof(date), fmt, localtime(&mtime));
1154 fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
1155 archive_entry_strmode(entry),
1156 archive_entry_nlink(entry),
1157 uname, gname, size, date,
1158 archive_entry_pathname(entry));
1160 /* Extra information for links. */
1161 if (archive_entry_hardlink(entry)) /* Hard link */
1162 fprintf(out, " link to %s", archive_entry_hardlink(entry));
1163 else if (archive_entry_symlink(entry)) /* Symbolic link */
1164 fprintf(out, " -> %s", archive_entry_symlink(entry));
1169 mode_pass(struct cpio *cpio, const char *destdir)
1171 struct lafe_line_reader *lr;
1175 /* Ensure target dir has a trailing '/' to simplify path surgery. */
1176 cpio->destdir = malloc(strlen(destdir) + 8);
1177 strcpy(cpio->destdir, destdir);
1178 if (destdir[strlen(destdir) - 1] != '/')
1179 strcat(cpio->destdir, "/");
1181 cpio->archive = archive_write_disk_new();
1182 if (cpio->archive == NULL)
1183 lafe_errc(1, 0, "Failed to allocate archive object");
1184 r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
1185 if (r != ARCHIVE_OK)
1186 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1187 cpio->linkresolver = archive_entry_linkresolver_new();
1188 archive_write_disk_set_standard_lookup(cpio->archive);
1190 cpio->archive_read_disk = archive_read_disk_new();
1191 if (cpio->archive_read_disk == NULL)
1192 lafe_errc(1, 0, "Failed to allocate archive object");
1193 if (cpio->option_follow_links)
1194 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
1196 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
1197 archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
1199 lr = lafe_line_reader("-", cpio->option_null);
1200 while ((p = lafe_line_reader_next(lr)) != NULL)
1201 file_to_archive(cpio, p);
1202 lafe_line_reader_free(lr);
1204 archive_entry_linkresolver_free(cpio->linkresolver);
1205 r = archive_write_close(cpio->archive);
1207 fprintf(stderr, "\n");
1208 if (r != ARCHIVE_OK)
1209 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1213 (archive_filter_bytes(cpio->archive, 0) + 511)
1215 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1216 blocks == 1 ? "block" : "blocks");
1219 archive_write_free(cpio->archive);
1223 * Prompt for a new name for this entry. Returns a pointer to the
1224 * new name or NULL if the entry should not be copied. This
1225 * implements the semantics defined in POSIX.1-1996, which specifies
1226 * that an input of '.' means the name should be unchanged. GNU cpio
1227 * treats '.' as a literal new name.
1230 cpio_rename(const char *name)
1232 static char buff[1024];
1235 #if defined(_WIN32) && !defined(__CYGWIN__)
1238 t = fopen("CONIN$", "r");
1241 to = fopen("CONOUT$", "w");
1244 fprintf(to, "%s (Enter/./(new name))? ", name);
1247 t = fopen("/dev/tty", "r+");
1250 fprintf(t, "%s (Enter/./(new name))? ", name);
1254 p = fgets(buff, sizeof(buff), t);
1257 /* End-of-file is a blank line. */
1260 while (*p == ' ' || *p == '\t')
1262 if (*p == '\n' || *p == '\0')
1265 if (*p == '.' && p[1] == '\n')
1266 /* Single period preserves original name. */
1269 /* Trim the final newline. */
1270 while (*p != '\0' && *p != '\n')
1272 /* Overwrite the final \n with a null character. */
1278 free_cache(struct name_cache *cache)
1282 if (cache != NULL) {
1283 for (i = 0; i < cache->size; i++)
1284 free(cache->cache[i].name);
1290 * Lookup uname/gname from uid/gid, return NULL if no match.
1293 lookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
1294 int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
1297 struct name_cache *cache;
1302 if (*name_cache_variable == NULL) {
1303 *name_cache_variable = malloc(sizeof(struct name_cache));
1304 if (*name_cache_variable == NULL)
1305 lafe_errc(1, ENOMEM, "No more memory");
1306 memset(*name_cache_variable, 0, sizeof(struct name_cache));
1307 (*name_cache_variable)->size = name_cache_size;
1310 cache = *name_cache_variable;
1313 slot = id % cache->size;
1314 if (cache->cache[slot].name != NULL) {
1315 if (cache->cache[slot].id == id) {
1317 return (cache->cache[slot].name);
1319 free(cache->cache[slot].name);
1320 cache->cache[slot].name = NULL;
1323 if (lookup_fn(cpio, &name, id) == 0) {
1324 if (name == NULL || name[0] == '\0') {
1325 /* If lookup failed, format it as a number. */
1326 snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
1329 cache->cache[slot].name = strdup(name);
1330 if (cache->cache[slot].name != NULL) {
1331 cache->cache[slot].id = id;
1332 return (cache->cache[slot].name);
1335 * Conveniently, NULL marks an empty slot, so
1336 * if the strdup() fails, we've just failed to
1337 * cache it. No recovery necessary.
1344 lookup_uname(struct cpio *cpio, uid_t uid)
1346 return (lookup_name(cpio, &cpio->uname_cache,
1347 &lookup_uname_helper, (id_t)uid));
1351 lookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
1353 struct passwd *pwent;
1355 (void)cpio; /* UNUSED */
1358 pwent = getpwuid((uid_t)id);
1359 if (pwent == NULL) {
1361 if (errno != 0 && errno != ENOENT)
1362 lafe_warnc(errno, "getpwuid(%s) failed",
1363 cpio_i64toa((int64_t)id));
1367 *name = pwent->pw_name;
1372 lookup_gname(struct cpio *cpio, gid_t gid)
1374 return (lookup_name(cpio, &cpio->gname_cache,
1375 &lookup_gname_helper, (id_t)gid));
1379 lookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
1381 struct group *grent;
1383 (void)cpio; /* UNUSED */
1386 grent = getgrgid((gid_t)id);
1387 if (grent == NULL) {
1390 lafe_warnc(errno, "getgrgid(%s) failed",
1391 cpio_i64toa((int64_t)id));
1395 *name = grent->gr_name;
1400 * It would be nice to just use printf() for formatting large numbers,
1401 * but the compatibility problems are a big headache. Hence the
1402 * following simple utility function.
1405 cpio_i64toa(int64_t n0)
1407 /* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
1408 * We also need 1 byte for '-' and 1 for '\0'.
1410 static char buff[22];
1411 int64_t n = n0 < 0 ? -n0 : n0;
1412 char *p = buff + sizeof(buff);
1416 *--p = '0' + (int)(n % 10);