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_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 OPTION_B64ENCODE:
211 cpio->add_filter = opt;
213 case 'C': /* NetBSD/OpenBSD */
214 cpio->bytes_per_block = atoi(cpio->argument);
215 if (cpio->bytes_per_block <= 0)
216 lafe_errc(1, 0, "Invalid blocksize %s", cpio->argument);
218 case 'c': /* POSIX 1997 */
219 cpio->format = "odc";
221 case 'd': /* POSIX 1997 */
222 cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
224 case 'E': /* NetBSD/OpenBSD */
225 if (archive_match_include_pattern_from_file(
226 cpio->matching, cpio->argument,
227 cpio->option_null) != ARCHIVE_OK)
228 lafe_errc(1, 0, "Error : %s",
229 archive_error_string(cpio->matching));
231 case 'F': /* NetBSD/OpenBSD/GNU cpio */
232 cpio->filename = cpio->argument;
234 case 'f': /* POSIX 1997 */
235 if (archive_match_exclude_pattern(cpio->matching,
236 cpio->argument) != ARCHIVE_OK)
237 lafe_errc(1, 0, "Error : %s",
238 archive_error_string(cpio->matching));
241 cpio->compress = opt;
243 case 'H': /* GNU cpio (also --format) */
244 cpio->format = cpio->argument;
249 case 'I': /* NetBSD/OpenBSD */
250 cpio->filename = cpio->argument;
252 case 'i': /* POSIX 1997 */
253 if (cpio->mode != '\0')
255 "Cannot use both -i and -%c", cpio->mode);
258 case 'J': /* GNU tar, others */
259 cpio->compress = opt;
261 case 'j': /* GNU tar, others */
262 cpio->compress = opt;
264 case OPTION_INSECURE:
265 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
266 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
268 case 'L': /* GNU cpio */
269 cpio->option_follow_links = 1;
271 case 'l': /* POSIX 1997 */
272 cpio->option_link = 1;
275 case OPTION_LZMA: /* GNU tar, others */
276 case OPTION_LZOP: /* GNU tar, others */
277 cpio->compress = opt;
279 case 'm': /* POSIX 1997 */
280 cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
282 case 'n': /* GNU cpio */
283 cpio->option_numeric_uid_gid = 1;
285 case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
286 cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
288 case 'O': /* GNU cpio */
289 cpio->filename = cpio->argument;
291 case 'o': /* POSIX 1997 */
292 if (cpio->mode != '\0')
294 "Cannot use both -o and -%c", cpio->mode);
297 case 'p': /* POSIX 1997 */
298 if (cpio->mode != '\0')
300 "Cannot use both -p and -%c", cpio->mode);
302 cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
304 case OPTION_PRESERVE_OWNER:
305 cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
307 case OPTION_QUIET: /* GNU cpio */
310 case 'R': /* GNU cpio, also --owner */
311 /* TODO: owner_parse should return uname/gname
312 * also; use that to set [ug]name_override. */
313 errmsg = owner_parse(cpio->argument, &uid, &gid);
315 lafe_warnc(-1, "%s", errmsg);
319 cpio->uid_override = uid;
320 cpio->uname_override = NULL;
323 cpio->gid_override = gid;
324 cpio->gname_override = NULL;
327 case 'r': /* POSIX 1997 */
328 cpio->option_rename = 1;
330 case 't': /* POSIX 1997 */
331 cpio->option_list = 1;
333 case 'u': /* POSIX 1997 */
335 &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
337 case OPTION_UUENCODE:
338 cpio->add_filter = opt;
340 case 'v': /* POSIX 1997 */
343 case 'V': /* GNU cpio */
346 case OPTION_VERSION: /* GNU convention */
351 * cpio_getopt() handles -W specially, so it's not
354 case 'W': /* Obscure, but useful GNU convention. */
357 case 'y': /* tar convention */
358 cpio->compress = opt;
360 case 'Z': /* tar convention */
361 cpio->compress = opt;
363 case 'z': /* tar convention */
364 cpio->compress = opt;
372 * Sanity-check args, error out on nonsensical combinations.
374 /* -t implies -i if no mode was specified. */
375 if (cpio->option_list && cpio->mode == '\0')
378 if (cpio->option_list && cpio->mode != 'i')
379 lafe_errc(1, 0, "Option -t requires -i");
380 /* -n requires -it */
381 if (cpio->option_numeric_uid_gid && !cpio->option_list)
382 lafe_errc(1, 0, "Option -n requires -it");
383 /* Can only specify format when writing */
384 if (cpio->format != NULL && cpio->mode != 'o')
385 lafe_errc(1, 0, "Option --format requires -o");
387 if (cpio->option_link && cpio->mode != 'p')
388 lafe_errc(1, 0, "Option -l requires -p");
389 /* -v overrides -V */
390 if (cpio->dot && cpio->verbose)
392 /* TODO: Flag other nonsensical combinations. */
394 switch (cpio->mode) {
396 /* TODO: Implement old binary format in libarchive,
398 if (cpio->format == NULL)
399 cpio->format = "odc"; /* Default format */
404 while (*cpio->argv != NULL) {
405 if (archive_match_include_pattern(cpio->matching,
406 *cpio->argv) != ARCHIVE_OK)
407 lafe_errc(1, 0, "Error : %s",
408 archive_error_string(cpio->matching));
412 if (cpio->option_list)
418 if (*cpio->argv == NULL || **cpio->argv == '\0')
420 "-p mode requires a target directory");
421 mode_pass(cpio, *cpio->argv);
425 "Must specify at least one of -i, -o, or -p");
428 archive_match_free(cpio->matching);
429 free_cache(cpio->gname_cache);
430 free_cache(cpio->uname_cache);
432 return (cpio->return_value);
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_progname;
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_string());
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_lzma(cpio->archive);
544 r = archive_write_add_filter_lzop(cpio->archive);
547 r = archive_write_add_filter_bzip2(cpio->archive);
550 r = archive_write_add_filter_gzip(cpio->archive);
553 r = archive_write_add_filter_compress(cpio->archive);
556 r = archive_write_add_filter_none(cpio->archive);
559 if (r < ARCHIVE_WARN)
560 lafe_errc(1, 0, "Requested compression not available");
561 switch (cpio->add_filter) {
565 case OPTION_B64ENCODE:
566 r = archive_write_add_filter_b64encode(cpio->archive);
568 case OPTION_UUENCODE:
569 r = archive_write_add_filter_uuencode(cpio->archive);
572 if (r < ARCHIVE_WARN)
573 lafe_errc(1, 0, "Requested filter not available");
574 r = archive_write_set_format_by_name(cpio->archive, cpio->format);
576 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
577 archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
578 cpio->linkresolver = archive_entry_linkresolver_new();
579 archive_entry_linkresolver_set_strategy(cpio->linkresolver,
580 archive_format(cpio->archive));
583 * The main loop: Copy each file into the output archive.
585 r = archive_write_open_filename(cpio->archive, cpio->filename);
587 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
588 lr = lafe_line_reader("-", cpio->option_null);
589 while ((p = lafe_line_reader_next(lr)) != NULL)
590 file_to_archive(cpio, p);
591 lafe_line_reader_free(lr);
594 * The hardlink detection may have queued up a couple of entries
595 * that can now be flushed.
598 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
599 while (entry != NULL) {
600 entry_to_archive(cpio, entry);
601 archive_entry_free(entry);
603 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
606 r = archive_write_close(cpio->archive);
608 fprintf(stderr, "\n");
610 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
614 (archive_filter_bytes(cpio->archive, 0) + 511)
616 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
617 blocks == 1 ? "block" : "blocks");
619 archive_write_free(cpio->archive);
623 remove_leading_slash(const char *p)
627 /* Remove leading "//./" or "//?/" or "//?/UNC/"
628 * (absolute path prefixes used by Windows API) */
629 if ((p[0] == '/' || p[0] == '\\') &&
630 (p[1] == '/' || p[1] == '\\') &&
631 (p[2] == '.' || p[2] == '?') &&
632 (p[3] == '/' || p[3] == '\\'))
635 (p[4] == 'U' || p[4] == 'u') &&
636 (p[5] == 'N' || p[5] == 'n') &&
637 (p[6] == 'C' || p[6] == 'c') &&
638 (p[7] == '/' || p[7] == '\\'))
645 /* Remove leading drive letter from archives created
647 if (((p[0] >= 'a' && p[0] <= 'z') ||
648 (p[0] >= 'A' && p[0] <= 'Z')) &&
652 /* Remove leading "/../", "//", etc. */
653 while (p[0] == '/' || p[0] == '\\') {
654 if (p[1] == '.' && p[2] == '.' &&
655 (p[3] == '/' || p[3] == '\\')) {
656 p += 3; /* Remove "/..", leave "/"
659 p += 1; /* Remove "/". */
666 * This is used by both out mode (to copy objects from disk into
667 * an archive) and pass mode (to copy objects from disk to
668 * an archive_write_disk "archive").
671 file_to_archive(struct cpio *cpio, const char *srcpath)
673 const char *destpath;
674 struct archive_entry *entry, *spare;
679 * Create an archive_entry describing the source file.
682 entry = archive_entry_new();
684 lafe_errc(1, 0, "Couldn't allocate entry");
685 archive_entry_copy_sourcepath(entry, srcpath);
686 r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
688 if (r < ARCHIVE_FAILED)
689 lafe_errc(1, 0, "%s",
690 archive_error_string(cpio->archive_read_disk));
693 archive_error_string(cpio->archive_read_disk));
694 if (r <= ARCHIVE_FAILED) {
695 cpio->return_value = 1;
699 if (cpio->uid_override >= 0) {
700 archive_entry_set_uid(entry, cpio->uid_override);
701 archive_entry_set_uname(entry, cpio->uname_override);
703 if (cpio->gid_override >= 0) {
704 archive_entry_set_gid(entry, cpio->gid_override);
705 archive_entry_set_gname(entry, cpio->gname_override);
709 * Generate a destination path for this entry.
710 * "destination path" is the name to which it will be copied in
711 * pass mode or the name that will go into the archive in
716 len = strlen(cpio->destdir) + strlen(srcpath) + 8;
717 if (len >= cpio->pass_destpath_alloc) {
718 while (len >= cpio->pass_destpath_alloc) {
719 cpio->pass_destpath_alloc += 512;
720 cpio->pass_destpath_alloc *= 2;
722 free(cpio->pass_destpath);
723 cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
724 if (cpio->pass_destpath == NULL)
726 "Can't allocate path buffer");
728 strcpy(cpio->pass_destpath, cpio->destdir);
729 strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
730 destpath = cpio->pass_destpath;
732 if (cpio->option_rename)
733 destpath = cpio_rename(destpath);
734 if (destpath == NULL)
736 archive_entry_copy_pathname(entry, destpath);
739 * If we're trying to preserve hardlinks, match them here.
742 if (cpio->linkresolver != NULL
743 && archive_entry_filetype(entry) != AE_IFDIR) {
744 archive_entry_linkify(cpio->linkresolver, &entry, &spare);
748 r = entry_to_archive(cpio, entry);
749 archive_entry_free(entry);
752 r = entry_to_archive(cpio, spare);
753 archive_entry_free(spare);
760 entry_to_archive(struct cpio *cpio, struct archive_entry *entry)
762 const char *destpath = archive_entry_pathname(entry);
763 const char *srcpath = archive_entry_sourcepath(entry);
768 /* Print out the destination name to the user. */
770 fprintf(stderr,"%s", destpath);
772 fprintf(stderr, ".");
775 * Option_link only makes sense in pass mode and for
776 * regular files. Also note: if a link operation fails
777 * because of cross-device restrictions, we'll fall back
778 * to copy mode for that entry.
780 * TODO: Test other cpio implementations to see if they
781 * hard-link anything other than regular files here.
783 if (cpio->option_link
784 && archive_entry_filetype(entry) == AE_IFREG)
786 struct archive_entry *t;
787 /* Save the original entry in case we need it later. */
788 t = archive_entry_clone(entry);
790 lafe_errc(1, ENOMEM, "Can't create link");
791 /* Note: link(2) doesn't create parent directories,
792 * so we use archive_write_header() instead as a
794 archive_entry_set_hardlink(t, srcpath);
795 /* This is a straight link that carries no data. */
796 archive_entry_set_size(t, 0);
797 r = archive_write_header(cpio->archive, t);
798 archive_entry_free(t);
800 lafe_warnc(archive_errno(cpio->archive),
801 "%s", archive_error_string(cpio->archive));
802 if (r == ARCHIVE_FATAL)
805 if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
806 /* Cross-device link: Just fall through and use
807 * the original entry to copy the file over. */
808 lafe_warnc(0, "Copying file instead");
815 * Make sure we can open the file (if necessary) before
816 * trying to write the header.
818 if (archive_entry_filetype(entry) == AE_IFREG) {
819 if (archive_entry_size(entry) > 0) {
820 fd = open(srcpath, O_RDONLY | O_BINARY);
823 "%s: could not open file", srcpath);
828 archive_entry_set_size(entry, 0);
831 r = archive_write_header(cpio->archive, entry);
834 lafe_warnc(archive_errno(cpio->archive),
837 archive_error_string(cpio->archive));
839 if (r == ARCHIVE_FATAL)
842 if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
843 bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size);
844 while (bytes_read > 0) {
846 bytes_write = archive_write_data(cpio->archive,
847 cpio->buff, bytes_read);
849 lafe_errc(1, archive_errno(cpio->archive),
850 "%s", archive_error_string(cpio->archive));
851 if (bytes_write < bytes_read) {
853 "Truncated write; file may have "
854 "grown while being archived.");
856 bytes_read = read(fd, cpio->buff,
857 (unsigned)cpio->buff_size);
861 fd = restore_time(cpio, entry, srcpath, fd);
865 fprintf(stderr,"\n");
872 restore_time(struct cpio *cpio, struct archive_entry *entry,
873 const char *name, int fd)
876 static int warned = 0;
878 (void)cpio; /* UNUSED */
879 (void)entry; /* UNUSED */
880 (void)name; /* UNUSED */
883 lafe_warnc(0, "Can't restore access times on this platform");
887 #if defined(_WIN32) && !defined(__CYGWIN__)
888 struct __timeval times[2];
890 struct timeval times[2];
893 if (!cpio->option_atime_restore)
896 times[1].tv_sec = archive_entry_mtime(entry);
897 times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
899 times[0].tv_sec = archive_entry_atime(entry);
900 times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
902 #if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
903 if (fd >= 0 && futimes(fd, times) == 0)
907 * Some platform cannot restore access times if the file descriptor
916 if (lutimes(name, times) != 0)
918 if ((AE_IFLNK != archive_entry_filetype(entry))
919 && utimes(name, times) != 0)
921 lafe_warnc(errno, "Can't update time for %s", name);
928 mode_in(struct cpio *cpio)
931 struct archive_entry *entry;
933 const char *destpath;
936 ext = archive_write_disk_new();
938 lafe_errc(1, 0, "Couldn't allocate restore object");
939 r = archive_write_disk_set_options(ext, cpio->extract_flags);
941 lafe_errc(1, 0, "%s", archive_error_string(ext));
942 a = archive_read_new();
944 lafe_errc(1, 0, "Couldn't allocate archive object");
945 archive_read_support_filter_all(a);
946 archive_read_support_format_all(a);
948 if (archive_read_open_filename(a, cpio->filename,
949 cpio->bytes_per_block))
950 lafe_errc(1, archive_errno(a),
951 "%s", archive_error_string(a));
953 r = archive_read_next_header(a, &entry);
954 if (r == ARCHIVE_EOF)
956 if (r != ARCHIVE_OK) {
957 lafe_errc(1, archive_errno(a),
958 "%s", archive_error_string(a));
960 if (archive_match_path_excluded(cpio->matching, entry))
962 if (cpio->option_rename) {
963 destpath = cpio_rename(archive_entry_pathname(entry));
964 archive_entry_set_pathname(entry, destpath);
966 destpath = archive_entry_pathname(entry);
967 if (destpath == NULL)
970 fprintf(stderr, "%s\n", destpath);
972 fprintf(stderr, ".");
973 if (cpio->uid_override >= 0)
974 archive_entry_set_uid(entry, cpio->uid_override);
975 if (cpio->gid_override >= 0)
976 archive_entry_set_gid(entry, cpio->gid_override);
977 r = archive_write_header(ext, entry);
978 if (r != ARCHIVE_OK) {
979 fprintf(stderr, "%s: %s\n",
980 archive_entry_pathname(entry),
981 archive_error_string(ext));
982 } else if (!archive_entry_size_is_set(entry)
983 || archive_entry_size(entry) > 0) {
984 r = extract_data(a, ext);
986 cpio->return_value = 1;
989 r = archive_read_close(a);
991 fprintf(stderr, "\n");
993 lafe_errc(1, 0, "%s", archive_error_string(a));
994 r = archive_write_close(ext);
996 lafe_errc(1, 0, "%s", archive_error_string(ext));
998 int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1000 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1001 blocks == 1 ? "block" : "blocks");
1003 archive_read_free(a);
1004 archive_write_free(ext);
1005 exit(cpio->return_value);
1009 * Exits if there's a fatal error. Returns ARCHIVE_OK
1010 * if everything is kosher.
1013 extract_data(struct archive *ar, struct archive *aw)
1021 r = archive_read_data_block(ar, &block, &size, &offset);
1022 if (r == ARCHIVE_EOF)
1023 return (ARCHIVE_OK);
1024 if (r != ARCHIVE_OK) {
1025 lafe_warnc(archive_errno(ar),
1026 "%s", archive_error_string(ar));
1029 r = (int)archive_write_data_block(aw, block, size, offset);
1030 if (r != ARCHIVE_OK) {
1031 lafe_warnc(archive_errno(aw),
1032 "%s", archive_error_string(aw));
1039 mode_list(struct cpio *cpio)
1042 struct archive_entry *entry;
1045 a = archive_read_new();
1047 lafe_errc(1, 0, "Couldn't allocate archive object");
1048 archive_read_support_filter_all(a);
1049 archive_read_support_format_all(a);
1051 if (archive_read_open_filename(a, cpio->filename,
1052 cpio->bytes_per_block))
1053 lafe_errc(1, archive_errno(a),
1054 "%s", archive_error_string(a));
1056 r = archive_read_next_header(a, &entry);
1057 if (r == ARCHIVE_EOF)
1059 if (r != ARCHIVE_OK) {
1060 lafe_errc(1, archive_errno(a),
1061 "%s", archive_error_string(a));
1063 if (archive_match_path_excluded(cpio->matching, entry))
1066 list_item_verbose(cpio, entry);
1068 fprintf(stdout, "%s\n", archive_entry_pathname(entry));
1070 r = archive_read_close(a);
1071 if (r != ARCHIVE_OK)
1072 lafe_errc(1, 0, "%s", archive_error_string(a));
1074 int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1076 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1077 blocks == 1 ? "block" : "blocks");
1079 archive_read_free(a);
1084 * Display information about the current file.
1086 * The format here roughly duplicates the output of 'ls -l'.
1087 * This is based on SUSv2, where 'tar tv' is documented as
1088 * listing additional information in an "unspecified format,"
1089 * and 'pax -l' is documented as using the same format as 'ls -l'.
1092 list_item_verbose(struct cpio *cpio, struct archive_entry *entry)
1096 char uids[16], gids[16];
1097 const char *uname, *gname;
1106 if (cpio->option_numeric_uid_gid) {
1107 /* Format numeric uid/gid for display. */
1108 strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
1110 strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
1113 /* Use uname if it's present, else lookup name from uid. */
1114 uname = archive_entry_uname(entry);
1116 uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
1117 /* Use gname if it's present, else lookup name from gid. */
1118 gname = archive_entry_gname(entry);
1120 gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
1123 /* Print device number or file size. */
1124 if (archive_entry_filetype(entry) == AE_IFCHR
1125 || archive_entry_filetype(entry) == AE_IFBLK) {
1126 snprintf(size, sizeof(size), "%lu,%lu",
1127 (unsigned long)archive_entry_rdevmajor(entry),
1128 (unsigned long)archive_entry_rdevminor(entry));
1130 strcpy(size, cpio_i64toa(archive_entry_size(entry)));
1133 /* Format the time using 'ls -l' conventions. */
1134 mtime = archive_entry_mtime(entry);
1135 #if defined(_WIN32) && !defined(__CYGWIN__)
1136 /* Windows' strftime function does not support %e format. */
1137 if (mtime - now > 365*86400/2
1138 || mtime - now < -365*86400/2)
1139 fmt = cpio->day_first ? "%d %b %Y" : "%b %d %Y";
1141 fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
1143 if (mtime - now > 365*86400/2
1144 || mtime - now < -365*86400/2)
1145 fmt = cpio->day_first ? "%e %b %Y" : "%b %e %Y";
1147 fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
1149 strftime(date, sizeof(date), fmt, localtime(&mtime));
1151 fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
1152 archive_entry_strmode(entry),
1153 archive_entry_nlink(entry),
1154 uname, gname, size, date,
1155 archive_entry_pathname(entry));
1157 /* Extra information for links. */
1158 if (archive_entry_hardlink(entry)) /* Hard link */
1159 fprintf(out, " link to %s", archive_entry_hardlink(entry));
1160 else if (archive_entry_symlink(entry)) /* Symbolic link */
1161 fprintf(out, " -> %s", archive_entry_symlink(entry));
1166 mode_pass(struct cpio *cpio, const char *destdir)
1168 struct lafe_line_reader *lr;
1172 /* Ensure target dir has a trailing '/' to simplify path surgery. */
1173 cpio->destdir = malloc(strlen(destdir) + 8);
1174 strcpy(cpio->destdir, destdir);
1175 if (destdir[strlen(destdir) - 1] != '/')
1176 strcat(cpio->destdir, "/");
1178 cpio->archive = archive_write_disk_new();
1179 if (cpio->archive == NULL)
1180 lafe_errc(1, 0, "Failed to allocate archive object");
1181 r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
1182 if (r != ARCHIVE_OK)
1183 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1184 cpio->linkresolver = archive_entry_linkresolver_new();
1185 archive_write_disk_set_standard_lookup(cpio->archive);
1187 cpio->archive_read_disk = archive_read_disk_new();
1188 if (cpio->archive_read_disk == NULL)
1189 lafe_errc(1, 0, "Failed to allocate archive object");
1190 if (cpio->option_follow_links)
1191 archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
1193 archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
1194 archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
1196 lr = lafe_line_reader("-", cpio->option_null);
1197 while ((p = lafe_line_reader_next(lr)) != NULL)
1198 file_to_archive(cpio, p);
1199 lafe_line_reader_free(lr);
1201 archive_entry_linkresolver_free(cpio->linkresolver);
1202 r = archive_write_close(cpio->archive);
1204 fprintf(stderr, "\n");
1205 if (r != ARCHIVE_OK)
1206 lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1210 (archive_filter_bytes(cpio->archive, 0) + 511)
1212 fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1213 blocks == 1 ? "block" : "blocks");
1216 archive_write_free(cpio->archive);
1220 * Prompt for a new name for this entry. Returns a pointer to the
1221 * new name or NULL if the entry should not be copied. This
1222 * implements the semantics defined in POSIX.1-1996, which specifies
1223 * that an input of '.' means the name should be unchanged. GNU cpio
1224 * treats '.' as a literal new name.
1227 cpio_rename(const char *name)
1229 static char buff[1024];
1232 #if defined(_WIN32) && !defined(__CYGWIN__)
1235 t = fopen("CONIN$", "r");
1238 to = fopen("CONOUT$", "w");
1241 fprintf(to, "%s (Enter/./(new name))? ", name);
1244 t = fopen("/dev/tty", "r+");
1247 fprintf(t, "%s (Enter/./(new name))? ", name);
1251 p = fgets(buff, sizeof(buff), t);
1254 /* End-of-file is a blank line. */
1257 while (*p == ' ' || *p == '\t')
1259 if (*p == '\n' || *p == '\0')
1262 if (*p == '.' && p[1] == '\n')
1263 /* Single period preserves original name. */
1266 /* Trim the final newline. */
1267 while (*p != '\0' && *p != '\n')
1269 /* Overwrite the final \n with a null character. */
1275 free_cache(struct name_cache *cache)
1279 if (cache != NULL) {
1280 for (i = 0; i < cache->size; i++)
1281 free(cache->cache[i].name);
1287 * Lookup uname/gname from uid/gid, return NULL if no match.
1290 lookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
1291 int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
1294 struct name_cache *cache;
1299 if (*name_cache_variable == NULL) {
1300 *name_cache_variable = malloc(sizeof(struct name_cache));
1301 if (*name_cache_variable == NULL)
1302 lafe_errc(1, ENOMEM, "No more memory");
1303 memset(*name_cache_variable, 0, sizeof(struct name_cache));
1304 (*name_cache_variable)->size = name_cache_size;
1307 cache = *name_cache_variable;
1310 slot = id % cache->size;
1311 if (cache->cache[slot].name != NULL) {
1312 if (cache->cache[slot].id == id) {
1314 return (cache->cache[slot].name);
1316 free(cache->cache[slot].name);
1317 cache->cache[slot].name = NULL;
1320 if (lookup_fn(cpio, &name, id) == 0) {
1321 if (name == NULL || name[0] == '\0') {
1322 /* If lookup failed, format it as a number. */
1323 snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
1326 cache->cache[slot].name = strdup(name);
1327 if (cache->cache[slot].name != NULL) {
1328 cache->cache[slot].id = id;
1329 return (cache->cache[slot].name);
1332 * Conveniently, NULL marks an empty slot, so
1333 * if the strdup() fails, we've just failed to
1334 * cache it. No recovery necessary.
1341 lookup_uname(struct cpio *cpio, uid_t uid)
1343 return (lookup_name(cpio, &cpio->uname_cache,
1344 &lookup_uname_helper, (id_t)uid));
1348 lookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
1350 struct passwd *pwent;
1352 (void)cpio; /* UNUSED */
1355 pwent = getpwuid((uid_t)id);
1356 if (pwent == NULL) {
1358 if (errno != 0 && errno != ENOENT)
1359 lafe_warnc(errno, "getpwuid(%s) failed",
1360 cpio_i64toa((int64_t)id));
1364 *name = pwent->pw_name;
1369 lookup_gname(struct cpio *cpio, gid_t gid)
1371 return (lookup_name(cpio, &cpio->gname_cache,
1372 &lookup_gname_helper, (id_t)gid));
1376 lookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
1378 struct group *grent;
1380 (void)cpio; /* UNUSED */
1383 grent = getgrgid((gid_t)id);
1384 if (grent == NULL) {
1387 lafe_warnc(errno, "getgrgid(%s) failed",
1388 cpio_i64toa((int64_t)id));
1392 *name = grent->gr_name;
1397 * It would be nice to just use printf() for formatting large numbers,
1398 * but the compatibility problems are a big headache. Hence the
1399 * following simple utility function.
1402 cpio_i64toa(int64_t n0)
1404 /* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
1405 * We also need 1 byte for '-' and 1 for '\0'.
1407 static char buff[22];
1408 int64_t n = n0 < 0 ? -n0 : n0;
1409 char *p = buff + sizeof(buff);
1413 *--p = '0' + (int)(n % 10);