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"
85 #include "passphrase.h"
87 /* Fixed size of uname/gname caches. */
88 #define name_cache_size 101
101 } cache[name_cache_size];
104 static int extract_data(struct archive *, struct archive *);
105 const char * cpio_i64toa(int64_t);
106 static const char *cpio_rename(const char *name);
107 static int entry_to_archive(struct cpio *, struct archive_entry *);
108 static int file_to_archive(struct cpio *, const char *);
109 static void free_cache(struct name_cache *cache);
110 static void list_item_verbose(struct cpio *, struct archive_entry *);
111 static void long_help(void);
112 static const char *lookup_gname(struct cpio *, gid_t gid);
113 static int lookup_gname_helper(struct cpio *,
114 const char **name, id_t gid);
115 static const char *lookup_uname(struct cpio *, uid_t uid);
116 static int lookup_uname_helper(struct cpio *,
117 const char **name, id_t uid);
118 static void mode_in(struct cpio *);
119 static void mode_list(struct cpio *);
120 static void mode_out(struct cpio *);
121 static void mode_pass(struct cpio *, const char *);
122 static const char *remove_leading_slash(const char *);
123 static int restore_time(struct cpio *, struct archive_entry *,
124 const char *, int fd);
125 static void usage(void);
126 static void version(void);
127 static const char * passphrase_callback(struct archive *, void *);
128 static void passphrase_free(char *);
131 main(int argc, char *argv[])
133 static char buff[16384];
134 struct cpio _cpio; /* Allocated on stack. */
141 memset(cpio, 0, sizeof(*cpio));
143 cpio->buff_size = sizeof(buff);
145 #if defined(HAVE_SIGACTION) && defined(SIGPIPE)
146 { /* Ignore SIGPIPE signals. */
148 sigemptyset(&sa.sa_mask);
150 sa.sa_handler = SIG_IGN;
151 sigaction(SIGPIPE, &sa, NULL);
155 /* Set lafe_progname before calling lafe_warnc. */
156 lafe_setprogname(*argv, "bsdcpio");
159 if (setlocale(LC_ALL, "") == NULL)
160 lafe_warnc(0, "Failed to set default locale");
163 cpio->uid_override = -1;
164 cpio->gid_override = -1;
169 cpio->compress = '\0';
170 cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
171 cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
172 cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
173 cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
174 cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
175 cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
176 cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
177 cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
178 #if !defined(_WIN32) && !defined(__CYGWIN__)
180 cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
182 cpio->bytes_per_block = 512;
183 cpio->filename = NULL;
185 cpio->matching = archive_match_new();
186 if (cpio->matching == NULL)
187 lafe_errc(1, 0, "Out of memory");
189 while ((opt = cpio_getopt(cpio)) != -1) {
191 case '0': /* GNU convention: --null, -0 */
192 cpio->option_null = 1;
194 case 'A': /* NetBSD/OpenBSD */
195 cpio->option_append = 1;
197 case 'a': /* POSIX 1997 */
198 cpio->option_atime_restore = 1;
200 case 'B': /* POSIX 1997 */
201 cpio->bytes_per_block = 5120;
203 case OPTION_B64ENCODE:
204 cpio->add_filter = opt;
206 case 'C': /* NetBSD/OpenBSD */
207 cpio->bytes_per_block = atoi(cpio->argument);
208 if (cpio->bytes_per_block <= 0)
209 lafe_errc(1, 0, "Invalid blocksize %s", cpio->argument);
211 case 'c': /* POSIX 1997 */
212 cpio->format = "odc";
214 case 'd': /* POSIX 1997 */
215 cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
217 case 'E': /* NetBSD/OpenBSD */
218 if (archive_match_include_pattern_from_file(
219 cpio->matching, cpio->argument,
220 cpio->option_null) != ARCHIVE_OK)
221 lafe_errc(1, 0, "Error : %s",
222 archive_error_string(cpio->matching));
224 case 'F': /* NetBSD/OpenBSD/GNU cpio */
225 cpio->filename = cpio->argument;
227 case 'f': /* POSIX 1997 */
228 if (archive_match_exclude_pattern(cpio->matching,
229 cpio->argument) != ARCHIVE_OK)
230 lafe_errc(1, 0, "Error : %s",
231 archive_error_string(cpio->matching));
234 cpio->compress = opt;
236 case 'H': /* GNU cpio (also --format) */
237 cpio->format = cpio->argument;
242 case 'I': /* NetBSD/OpenBSD */
243 cpio->filename = cpio->argument;
245 case 'i': /* POSIX 1997 */
246 if (cpio->mode != '\0')
248 "Cannot use both -i and -%c", cpio->mode);
251 case 'J': /* GNU tar, others */
252 cpio->compress = opt;
254 case 'j': /* GNU tar, others */
255 cpio->compress = opt;
257 case OPTION_INSECURE:
258 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
259 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
260 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
262 case 'L': /* GNU cpio */
263 cpio->option_follow_links = 1;
265 case 'l': /* POSIX 1997 */
266 cpio->option_link = 1;
270 case OPTION_LZMA: /* GNU tar, others */
271 case OPTION_LZOP: /* GNU tar, others */
272 cpio->compress = opt;
274 case 'm': /* POSIX 1997 */
275 cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
277 case 'n': /* GNU cpio */
278 cpio->option_numeric_uid_gid = 1;
280 case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
281 cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
283 case 'O': /* GNU cpio */
284 cpio->filename = cpio->argument;
286 case 'o': /* POSIX 1997 */
287 if (cpio->mode != '\0')
289 "Cannot use both -o and -%c", cpio->mode);
292 case 'p': /* POSIX 1997 */
293 if (cpio->mode != '\0')
295 "Cannot use both -p and -%c", cpio->mode);
297 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
298 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
300 case OPTION_PASSPHRASE:
301 cpio->passphrase = cpio->argument;
303 case OPTION_PRESERVE_OWNER:
304 cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
306 case OPTION_QUIET: /* GNU cpio */
309 case 'R': /* GNU cpio, also --owner */
310 /* TODO: owner_parse should return uname/gname
311 * also; use that to set [ug]name_override. */
312 errmsg = owner_parse(cpio->argument, &uid, &gid);
314 lafe_warnc(-1, "%s", errmsg);
318 cpio->uid_override = uid;
319 cpio->uname_override = NULL;
322 cpio->gid_override = gid;
323 cpio->gname_override = NULL;
326 case 'r': /* POSIX 1997 */
327 cpio->option_rename = 1;
329 case 't': /* POSIX 1997 */
330 cpio->option_list = 1;
332 case 'u': /* POSIX 1997 */
334 &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
336 case OPTION_UUENCODE:
337 cpio->add_filter = opt;
339 case 'v': /* POSIX 1997 */
342 case 'V': /* GNU cpio */
345 case OPTION_VERSION: /* GNU convention */
350 * cpio_getopt() handles -W specially, so it's not
353 case 'W': /* Obscure, but useful GNU convention. */
356 case 'y': /* tar convention */
357 cpio->compress = opt;
359 case 'Z': /* tar convention */
360 cpio->compress = opt;
362 case 'z': /* tar convention */
363 cpio->compress = opt;
371 * Sanity-check args, error out on nonsensical combinations.
373 /* -t implies -i if no mode was specified. */
374 if (cpio->option_list && cpio->mode == '\0')
377 if (cpio->option_list && cpio->mode != 'i')
378 lafe_errc(1, 0, "Option -t requires -i");
379 /* -n requires -it */
380 if (cpio->option_numeric_uid_gid && !cpio->option_list)
381 lafe_errc(1, 0, "Option -n requires -it");
382 /* Can only specify format when writing */
383 if (cpio->format != NULL && cpio->mode != 'o')
384 lafe_errc(1, 0, "Option --format requires -o");
386 if (cpio->option_link && cpio->mode != 'p')
387 lafe_errc(1, 0, "Option -l requires -p");
388 /* -v overrides -V */
389 if (cpio->dot && cpio->verbose)
391 /* TODO: Flag other nonsensical combinations. */
393 switch (cpio->mode) {
395 /* TODO: Implement old binary format in libarchive,
397 if (cpio->format == NULL)
398 cpio->format = "odc"; /* Default format */
403 while (*cpio->argv != NULL) {
404 if (archive_match_include_pattern(cpio->matching,
405 *cpio->argv) != ARCHIVE_OK)
406 lafe_errc(1, 0, "Error : %s",
407 archive_error_string(cpio->matching));
411 if (cpio->option_list)
417 if (*cpio->argv == NULL || **cpio->argv == '\0')
419 "-p mode requires a target directory");
420 mode_pass(cpio, *cpio->argv);
424 "Must specify at least one of -i, -o, or -p");
427 archive_match_free(cpio->matching);
428 free_cache(cpio->gname_cache);
429 free_cache(cpio->uname_cache);
431 passphrase_free(cpio->ppbuff);
432 return (cpio->return_value);
440 p = lafe_getprogname();
442 fprintf(stderr, "Brief Usage:\n");
443 fprintf(stderr, " List: %s -it < archive\n", p);
444 fprintf(stderr, " Extract: %s -i < archive\n", p);
445 fprintf(stderr, " Create: %s -o < filenames > archive\n", p);
446 fprintf(stderr, " Help: %s --help\n", p);
450 static const char *long_help_msg =
451 "First option must be a mode specifier:\n"
452 " -i Input -o Output -p Pass\n"
454 " -v Verbose filenames -V one dot per file\n"
455 "Create: %p -o [options] < [list of files] > [archive]\n"
456 " -J,-y,-z,--lzma Compress archive with xz/bzip2/gzip/lzma\n"
457 " --format {odc|newc|ustar} Select archive format\n"
458 "List: %p -it < [archive]\n"
459 "Extract: %p -i [options] < [archive]\n";
463 * Note that the word 'bsdcpio' will always appear in the first line
466 * In particular, /bin/sh scripts that need to test for the presence
467 * of bsdcpio can use the following template:
469 * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
470 * echo bsdcpio; else echo not bsdcpio; fi
478 prog = lafe_getprogname();
482 p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
483 printf("%s%s: manipulate archive files\n", prog, p);
485 for (p = long_help_msg; *p != '\0'; p++) {
501 fprintf(stdout,"bsdcpio %s -- %s\n",
502 BSDCPIO_VERSION_STRING,
503 archive_version_details());
508 mode_out(struct cpio *cpio)
510 struct archive_entry *entry, *spare;
511 struct lafe_line_reader *lr;
515 if (cpio->option_append)
516 lafe_errc(1, 0, "Append mode not yet supported.");
518 cpio->archive_read_disk = archive_read_disk_new();
519 if (cpio->archive_read_disk == NULL)
520 lafe_errc(1, 0, "Failed to allocate archive object");
521 if (cpio->option_follow_links)
522 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
524 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
525 archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
527 cpio->archive = archive_write_new();
528 if (cpio->archive == NULL)
529 lafe_errc(1, 0, "Failed to allocate archive object");
530 switch (cpio->compress) {
532 r = archive_write_add_filter_grzip(cpio->archive);
535 r = archive_write_add_filter_xz(cpio->archive);
538 r = archive_write_add_filter_lrzip(cpio->archive);
541 r = archive_write_add_filter_lz4(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));
584 if (cpio->passphrase != NULL)
585 r = archive_write_set_passphrase(cpio->archive,
588 r = archive_write_set_passphrase_callback(cpio->archive, cpio,
589 &passphrase_callback);
591 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
594 * The main loop: Copy each file into the output archive.
596 r = archive_write_open_filename(cpio->archive, cpio->filename);
598 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
599 lr = lafe_line_reader("-", cpio->option_null);
600 while ((p = lafe_line_reader_next(lr)) != NULL)
601 file_to_archive(cpio, p);
602 lafe_line_reader_free(lr);
605 * The hardlink detection may have queued up a couple of entries
606 * that can now be flushed.
609 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
610 while (entry != NULL) {
611 entry_to_archive(cpio, entry);
612 archive_entry_free(entry);
614 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
617 r = archive_write_close(cpio->archive);
619 fprintf(stderr, "\n");
621 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
625 (archive_filter_bytes(cpio->archive, 0) + 511)
627 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
628 blocks == 1 ? "block" : "blocks");
630 archive_write_free(cpio->archive);
634 remove_leading_slash(const char *p)
638 /* Remove leading "//./" or "//?/" or "//?/UNC/"
639 * (absolute path prefixes used by Windows API) */
640 if ((p[0] == '/' || p[0] == '\\') &&
641 (p[1] == '/' || p[1] == '\\') &&
642 (p[2] == '.' || p[2] == '?') &&
643 (p[3] == '/' || p[3] == '\\'))
646 (p[4] == 'U' || p[4] == 'u') &&
647 (p[5] == 'N' || p[5] == 'n') &&
648 (p[6] == 'C' || p[6] == 'c') &&
649 (p[7] == '/' || p[7] == '\\'))
656 /* Remove leading drive letter from archives created
658 if (((p[0] >= 'a' && p[0] <= 'z') ||
659 (p[0] >= 'A' && p[0] <= 'Z')) &&
663 /* Remove leading "/../", "//", etc. */
664 while (p[0] == '/' || p[0] == '\\') {
665 if (p[1] == '.' && p[2] == '.' &&
666 (p[3] == '/' || p[3] == '\\')) {
667 p += 3; /* Remove "/..", leave "/"
670 p += 1; /* Remove "/". */
677 * This is used by both out mode (to copy objects from disk into
678 * an archive) and pass mode (to copy objects from disk to
679 * an archive_write_disk "archive").
682 file_to_archive(struct cpio *cpio, const char *srcpath)
684 const char *destpath;
685 struct archive_entry *entry, *spare;
690 * Create an archive_entry describing the source file.
693 entry = archive_entry_new();
695 lafe_errc(1, 0, "Couldn't allocate entry");
696 archive_entry_copy_sourcepath(entry, srcpath);
697 r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
699 if (r < ARCHIVE_FAILED)
700 lafe_errc(1, 0, "%s",
701 archive_error_string(cpio->archive_read_disk));
704 archive_error_string(cpio->archive_read_disk));
705 if (r <= ARCHIVE_FAILED) {
706 cpio->return_value = 1;
710 if (cpio->uid_override >= 0) {
711 archive_entry_set_uid(entry, cpio->uid_override);
712 archive_entry_set_uname(entry, cpio->uname_override);
714 if (cpio->gid_override >= 0) {
715 archive_entry_set_gid(entry, cpio->gid_override);
716 archive_entry_set_gname(entry, cpio->gname_override);
720 * Generate a destination path for this entry.
721 * "destination path" is the name to which it will be copied in
722 * pass mode or the name that will go into the archive in
727 len = strlen(cpio->destdir) + strlen(srcpath) + 8;
728 if (len >= cpio->pass_destpath_alloc) {
729 while (len >= cpio->pass_destpath_alloc) {
730 cpio->pass_destpath_alloc += 512;
731 cpio->pass_destpath_alloc *= 2;
733 free(cpio->pass_destpath);
734 cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
735 if (cpio->pass_destpath == NULL)
737 "Can't allocate path buffer");
739 strcpy(cpio->pass_destpath, cpio->destdir);
740 strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
741 destpath = cpio->pass_destpath;
743 if (cpio->option_rename)
744 destpath = cpio_rename(destpath);
745 if (destpath == NULL)
747 archive_entry_copy_pathname(entry, destpath);
750 * If we're trying to preserve hardlinks, match them here.
753 if (cpio->linkresolver != NULL
754 && archive_entry_filetype(entry) != AE_IFDIR) {
755 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
759 r = entry_to_archive(cpio, entry);
760 archive_entry_free(entry);
763 r = entry_to_archive(cpio, spare);
764 archive_entry_free(spare);
771 entry_to_archive(struct cpio *cpio, struct archive_entry *entry)
773 const char *destpath = archive_entry_pathname(entry);
774 const char *srcpath = archive_entry_sourcepath(entry);
779 /* Print out the destination name to the user. */
781 fprintf(stderr,"%s", destpath);
783 fprintf(stderr, ".");
786 * Option_link only makes sense in pass mode and for
787 * regular files. Also note: if a link operation fails
788 * because of cross-device restrictions, we'll fall back
789 * to copy mode for that entry.
791 * TODO: Test other cpio implementations to see if they
792 * hard-link anything other than regular files here.
794 if (cpio->option_link
795 && archive_entry_filetype(entry) == AE_IFREG)
797 struct archive_entry *t;
798 /* Save the original entry in case we need it later. */
799 t = archive_entry_clone(entry);
801 lafe_errc(1, ENOMEM, "Can't create link");
802 /* Note: link(2) doesn't create parent directories,
803 * so we use archive_write_header() instead as a
805 archive_entry_set_hardlink(t, srcpath);
806 /* This is a straight link that carries no data. */
807 archive_entry_set_size(t, 0);
808 r = archive_write_header(cpio->archive, t);
809 archive_entry_free(t);
811 lafe_warnc(archive_errno(cpio->archive),
812 "%s", archive_error_string(cpio->archive));
813 if (r == ARCHIVE_FATAL)
816 if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
817 /* Cross-device link: Just fall through and use
818 * the original entry to copy the file over. */
819 lafe_warnc(0, "Copying file instead");
826 * Make sure we can open the file (if necessary) before
827 * trying to write the header.
829 if (archive_entry_filetype(entry) == AE_IFREG) {
830 if (archive_entry_size(entry) > 0) {
831 fd = open(srcpath, O_RDONLY | O_BINARY);
834 "%s: could not open file", srcpath);
839 archive_entry_set_size(entry, 0);
842 r = archive_write_header(cpio->archive, entry);
845 lafe_warnc(archive_errno(cpio->archive),
848 archive_error_string(cpio->archive));
850 if (r == ARCHIVE_FATAL)
853 if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
854 bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size);
855 while (bytes_read > 0) {
857 bytes_write = archive_write_data(cpio->archive,
858 cpio->buff, bytes_read);
860 lafe_errc(1, archive_errno(cpio->archive),
861 "%s", archive_error_string(cpio->archive));
862 if (bytes_write < bytes_read) {
864 "Truncated write; file may have "
865 "grown while being archived.");
867 bytes_read = read(fd, cpio->buff,
868 (unsigned)cpio->buff_size);
872 fd = restore_time(cpio, entry, srcpath, fd);
876 fprintf(stderr,"\n");
883 restore_time(struct cpio *cpio, struct archive_entry *entry,
884 const char *name, int fd)
887 static int warned = 0;
889 (void)cpio; /* UNUSED */
890 (void)entry; /* UNUSED */
891 (void)name; /* UNUSED */
894 lafe_warnc(0, "Can't restore access times on this platform");
898 #if defined(_WIN32) && !defined(__CYGWIN__)
899 struct __timeval times[2];
901 struct timeval times[2];
904 if (!cpio->option_atime_restore)
907 times[1].tv_sec = archive_entry_mtime(entry);
908 times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
910 times[0].tv_sec = archive_entry_atime(entry);
911 times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
913 #if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
914 if (fd >= 0 && futimes(fd, times) == 0)
918 * Some platform cannot restore access times if the file descriptor
927 if (lutimes(name, times) != 0)
929 if ((AE_IFLNK != archive_entry_filetype(entry))
930 && utimes(name, times) != 0)
932 lafe_warnc(errno, "Can't update time for %s", name);
939 mode_in(struct cpio *cpio)
942 struct archive_entry *entry;
944 const char *destpath;
947 ext = archive_write_disk_new();
949 lafe_errc(1, 0, "Couldn't allocate restore object");
950 r = archive_write_disk_set_options(ext, cpio->extract_flags);
952 lafe_errc(1, 0, "%s", archive_error_string(ext));
953 a = archive_read_new();
955 lafe_errc(1, 0, "Couldn't allocate archive object");
956 archive_read_support_filter_all(a);
957 archive_read_support_format_all(a);
958 if (cpio->passphrase != NULL)
959 r = archive_read_add_passphrase(a, cpio->passphrase);
961 r = archive_read_set_passphrase_callback(a, cpio,
962 &passphrase_callback);
964 lafe_errc(1, 0, "%s", archive_error_string(a));
966 if (archive_read_open_filename(a, cpio->filename,
967 cpio->bytes_per_block))
968 lafe_errc(1, archive_errno(a),
969 "%s", archive_error_string(a));
971 r = archive_read_next_header(a, &entry);
972 if (r == ARCHIVE_EOF)
974 if (r != ARCHIVE_OK) {
975 lafe_errc(1, archive_errno(a),
976 "%s", archive_error_string(a));
978 if (archive_match_path_excluded(cpio->matching, entry))
980 if (cpio->option_rename) {
981 destpath = cpio_rename(archive_entry_pathname(entry));
982 archive_entry_set_pathname(entry, destpath);
984 destpath = archive_entry_pathname(entry);
985 if (destpath == NULL)
988 fprintf(stderr, "%s\n", destpath);
990 fprintf(stderr, ".");
991 if (cpio->uid_override >= 0)
992 archive_entry_set_uid(entry, cpio->uid_override);
993 if (cpio->gid_override >= 0)
994 archive_entry_set_gid(entry, cpio->gid_override);
995 r = archive_write_header(ext, entry);
996 if (r != ARCHIVE_OK) {
997 fprintf(stderr, "%s: %s\n",
998 archive_entry_pathname(entry),
999 archive_error_string(ext));
1000 } else if (!archive_entry_size_is_set(entry)
1001 || archive_entry_size(entry) > 0) {
1002 r = extract_data(a, ext);
1003 if (r != ARCHIVE_OK)
1004 cpio->return_value = 1;
1007 r = archive_read_close(a);
1009 fprintf(stderr, "\n");
1010 if (r != ARCHIVE_OK)
1011 lafe_errc(1, 0, "%s", archive_error_string(a));
1012 r = archive_write_close(ext);
1013 if (r != ARCHIVE_OK)
1014 lafe_errc(1, 0, "%s", archive_error_string(ext));
1016 int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1018 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1019 blocks == 1 ? "block" : "blocks");
1021 archive_read_free(a);
1022 archive_write_free(ext);
1023 exit(cpio->return_value);
1027 * Exits if there's a fatal error. Returns ARCHIVE_OK
1028 * if everything is kosher.
1031 extract_data(struct archive *ar, struct archive *aw)
1039 r = archive_read_data_block(ar, &block, &size, &offset);
1040 if (r == ARCHIVE_EOF)
1041 return (ARCHIVE_OK);
1042 if (r != ARCHIVE_OK) {
1043 lafe_warnc(archive_errno(ar),
1044 "%s", archive_error_string(ar));
1047 r = (int)archive_write_data_block(aw, block, size, offset);
1048 if (r != ARCHIVE_OK) {
1049 lafe_warnc(archive_errno(aw),
1050 "%s", archive_error_string(aw));
1057 mode_list(struct cpio *cpio)
1060 struct archive_entry *entry;
1063 a = archive_read_new();
1065 lafe_errc(1, 0, "Couldn't allocate archive object");
1066 archive_read_support_filter_all(a);
1067 archive_read_support_format_all(a);
1068 if (cpio->passphrase != NULL)
1069 r = archive_read_add_passphrase(a, cpio->passphrase);
1071 r = archive_read_set_passphrase_callback(a, cpio,
1072 &passphrase_callback);
1073 if (r != ARCHIVE_OK)
1074 lafe_errc(1, 0, "%s", archive_error_string(a));
1076 if (archive_read_open_filename(a, cpio->filename,
1077 cpio->bytes_per_block))
1078 lafe_errc(1, archive_errno(a),
1079 "%s", archive_error_string(a));
1081 r = archive_read_next_header(a, &entry);
1082 if (r == ARCHIVE_EOF)
1084 if (r != ARCHIVE_OK) {
1085 lafe_errc(1, archive_errno(a),
1086 "%s", archive_error_string(a));
1088 if (archive_match_path_excluded(cpio->matching, entry))
1091 list_item_verbose(cpio, entry);
1093 fprintf(stdout, "%s\n", archive_entry_pathname(entry));
1095 r = archive_read_close(a);
1096 if (r != ARCHIVE_OK)
1097 lafe_errc(1, 0, "%s", archive_error_string(a));
1099 int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1101 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1102 blocks == 1 ? "block" : "blocks");
1104 archive_read_free(a);
1109 * Display information about the current file.
1111 * The format here roughly duplicates the output of 'ls -l'.
1112 * This is based on SUSv2, where 'tar tv' is documented as
1113 * listing additional information in an "unspecified format,"
1114 * and 'pax -l' is documented as using the same format as 'ls -l'.
1117 list_item_verbose(struct cpio *cpio, struct archive_entry *entry)
1121 char uids[16], gids[16];
1122 const char *uname, *gname;
1131 if (cpio->option_numeric_uid_gid) {
1132 /* Format numeric uid/gid for display. */
1133 strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
1135 strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
1138 /* Use uname if it's present, else lookup name from uid. */
1139 uname = archive_entry_uname(entry);
1141 uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
1142 /* Use gname if it's present, else lookup name from gid. */
1143 gname = archive_entry_gname(entry);
1145 gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
1148 /* Print device number or file size. */
1149 if (archive_entry_filetype(entry) == AE_IFCHR
1150 || archive_entry_filetype(entry) == AE_IFBLK) {
1151 snprintf(size, sizeof(size), "%lu,%lu",
1152 (unsigned long)archive_entry_rdevmajor(entry),
1153 (unsigned long)archive_entry_rdevminor(entry));
1155 strcpy(size, cpio_i64toa(archive_entry_size(entry)));
1158 /* Format the time using 'ls -l' conventions. */
1159 mtime = archive_entry_mtime(entry);
1160 #if defined(_WIN32) && !defined(__CYGWIN__)
1161 /* Windows' strftime function does not support %e format. */
1162 if (mtime - now > 365*86400/2
1163 || mtime - now < -365*86400/2)
1164 fmt = cpio->day_first ? "%d %b %Y" : "%b %d %Y";
1166 fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
1168 if (mtime - now > 365*86400/2
1169 || mtime - now < -365*86400/2)
1170 fmt = cpio->day_first ? "%e %b %Y" : "%b %e %Y";
1172 fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
1174 strftime(date, sizeof(date), fmt, localtime(&mtime));
1176 fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
1177 archive_entry_strmode(entry),
1178 archive_entry_nlink(entry),
1179 uname, gname, size, date,
1180 archive_entry_pathname(entry));
1182 /* Extra information for links. */
1183 if (archive_entry_hardlink(entry)) /* Hard link */
1184 fprintf(out, " link to %s", archive_entry_hardlink(entry));
1185 else if (archive_entry_symlink(entry)) /* Symbolic link */
1186 fprintf(out, " -> %s", archive_entry_symlink(entry));
1191 mode_pass(struct cpio *cpio, const char *destdir)
1193 struct lafe_line_reader *lr;
1197 /* Ensure target dir has a trailing '/' to simplify path surgery. */
1198 cpio->destdir = malloc(strlen(destdir) + 8);
1199 strcpy(cpio->destdir, destdir);
1200 if (destdir[strlen(destdir) - 1] != '/')
1201 strcat(cpio->destdir, "/");
1203 cpio->archive = archive_write_disk_new();
1204 if (cpio->archive == NULL)
1205 lafe_errc(1, 0, "Failed to allocate archive object");
1206 r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
1207 if (r != ARCHIVE_OK)
1208 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1209 cpio->linkresolver = archive_entry_linkresolver_new();
1210 archive_write_disk_set_standard_lookup(cpio->archive);
1212 cpio->archive_read_disk = archive_read_disk_new();
1213 if (cpio->archive_read_disk == NULL)
1214 lafe_errc(1, 0, "Failed to allocate archive object");
1215 if (cpio->option_follow_links)
1216 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
1218 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
1219 archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
1221 lr = lafe_line_reader("-", cpio->option_null);
1222 while ((p = lafe_line_reader_next(lr)) != NULL)
1223 file_to_archive(cpio, p);
1224 lafe_line_reader_free(lr);
1226 archive_entry_linkresolver_free(cpio->linkresolver);
1227 r = archive_write_close(cpio->archive);
1229 fprintf(stderr, "\n");
1230 if (r != ARCHIVE_OK)
1231 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1235 (archive_filter_bytes(cpio->archive, 0) + 511)
1237 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1238 blocks == 1 ? "block" : "blocks");
1241 archive_write_free(cpio->archive);
1245 * Prompt for a new name for this entry. Returns a pointer to the
1246 * new name or NULL if the entry should not be copied. This
1247 * implements the semantics defined in POSIX.1-1996, which specifies
1248 * that an input of '.' means the name should be unchanged. GNU cpio
1249 * treats '.' as a literal new name.
1252 cpio_rename(const char *name)
1254 static char buff[1024];
1257 #if defined(_WIN32) && !defined(__CYGWIN__)
1260 t = fopen("CONIN$", "r");
1263 to = fopen("CONOUT$", "w");
1268 fprintf(to, "%s (Enter/./(new name))? ", name);
1271 t = fopen("/dev/tty", "r+");
1274 fprintf(t, "%s (Enter/./(new name))? ", name);
1278 p = fgets(buff, sizeof(buff), t);
1281 /* End-of-file is a blank line. */
1284 while (*p == ' ' || *p == '\t')
1286 if (*p == '\n' || *p == '\0')
1289 if (*p == '.' && p[1] == '\n')
1290 /* Single period preserves original name. */
1293 /* Trim the final newline. */
1294 while (*p != '\0' && *p != '\n')
1296 /* Overwrite the final \n with a null character. */
1302 free_cache(struct name_cache *cache)
1306 if (cache != NULL) {
1307 for (i = 0; i < cache->size; i++)
1308 free(cache->cache[i].name);
1314 * Lookup uname/gname from uid/gid, return NULL if no match.
1317 lookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
1318 int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
1321 struct name_cache *cache;
1326 if (*name_cache_variable == NULL) {
1327 *name_cache_variable = malloc(sizeof(struct name_cache));
1328 if (*name_cache_variable == NULL)
1329 lafe_errc(1, ENOMEM, "No more memory");
1330 memset(*name_cache_variable, 0, sizeof(struct name_cache));
1331 (*name_cache_variable)->size = name_cache_size;
1334 cache = *name_cache_variable;
1337 slot = id % cache->size;
1338 if (cache->cache[slot].name != NULL) {
1339 if (cache->cache[slot].id == id) {
1341 return (cache->cache[slot].name);
1343 free(cache->cache[slot].name);
1344 cache->cache[slot].name = NULL;
1347 if (lookup_fn(cpio, &name, id) == 0) {
1348 if (name == NULL || name[0] == '\0') {
1349 /* If lookup failed, format it as a number. */
1350 snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
1353 cache->cache[slot].name = strdup(name);
1354 if (cache->cache[slot].name != NULL) {
1355 cache->cache[slot].id = id;
1356 return (cache->cache[slot].name);
1359 * Conveniently, NULL marks an empty slot, so
1360 * if the strdup() fails, we've just failed to
1361 * cache it. No recovery necessary.
1368 lookup_uname(struct cpio *cpio, uid_t uid)
1370 return (lookup_name(cpio, &cpio->uname_cache,
1371 &lookup_uname_helper, (id_t)uid));
1375 lookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
1377 struct passwd *pwent;
1379 (void)cpio; /* UNUSED */
1382 pwent = getpwuid((uid_t)id);
1383 if (pwent == NULL) {
1385 if (errno != 0 && errno != ENOENT)
1386 lafe_warnc(errno, "getpwuid(%s) failed",
1387 cpio_i64toa((int64_t)id));
1391 *name = pwent->pw_name;
1396 lookup_gname(struct cpio *cpio, gid_t gid)
1398 return (lookup_name(cpio, &cpio->gname_cache,
1399 &lookup_gname_helper, (id_t)gid));
1403 lookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
1405 struct group *grent;
1407 (void)cpio; /* UNUSED */
1410 grent = getgrgid((gid_t)id);
1411 if (grent == NULL) {
1414 lafe_warnc(errno, "getgrgid(%s) failed",
1415 cpio_i64toa((int64_t)id));
1419 *name = grent->gr_name;
1424 * It would be nice to just use printf() for formatting large numbers,
1425 * but the compatibility problems are a big headache. Hence the
1426 * following simple utility function.
1429 cpio_i64toa(int64_t n0)
1431 /* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
1432 * We also need 1 byte for '-' and 1 for '\0'.
1434 static char buff[22];
1435 int64_t n = n0 < 0 ? -n0 : n0;
1436 char *p = buff + sizeof(buff);
1440 *--p = '0' + (int)(n % 10);
1448 #define PPBUFF_SIZE 1024
1450 passphrase_callback(struct archive *a, void *_client_data)
1452 struct cpio *cpio = (struct cpio *)_client_data;
1453 (void)a; /* UNUSED */
1455 if (cpio->ppbuff == NULL) {
1456 cpio->ppbuff = malloc(PPBUFF_SIZE);
1457 if (cpio->ppbuff == NULL)
1458 lafe_errc(1, errno, "Out of memory");
1460 return lafe_readpassphrase("Enter passphrase:",
1461 cpio->ppbuff, PPBUFF_SIZE);
1465 passphrase_free(char *ppbuff)
1467 if (ppbuff != NULL) {
1468 memset(ppbuff, 0, PPBUFF_SIZE);