xref: /freebsd/contrib/libarchive/cpio/cpio.c (revision 13ea0450a9c8742119d36f3bf8f47accdce46e54)
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
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.
14  *
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.
25  */
26 
27 
28 #include "cpio_platform.h"
29 __FBSDID("$FreeBSD$");
30 
31 #include <sys/types.h>
32 #include <archive.h>
33 #include <archive_entry.h>
34 
35 #ifdef HAVE_SYS_MKDEV_H
36 #include <sys/mkdev.h>
37 #endif
38 #ifdef HAVE_SYS_STAT_H
39 #include <sys/stat.h>
40 #endif
41 #ifdef HAVE_SYS_TIME_H
42 #include <sys/time.h>
43 #endif
44 #ifdef HAVE_ERRNO_H
45 #include <errno.h>
46 #endif
47 #ifdef HAVE_FCNTL_H
48 #include <fcntl.h>
49 #endif
50 #ifdef HAVE_GRP_H
51 #include <grp.h>
52 #endif
53 #ifdef HAVE_LOCALE_H
54 #include <locale.h>
55 #endif
56 #ifdef HAVE_PWD_H
57 #include <pwd.h>
58 #endif
59 #ifdef HAVE_SIGNAL_H
60 #include <signal.h>
61 #endif
62 #ifdef HAVE_STDARG_H
63 #include <stdarg.h>
64 #endif
65 #ifdef HAVE_STDINT_H
66 #include <stdint.h>
67 #endif
68 #include <stdio.h>
69 #ifdef HAVE_STDLIB_H
70 #include <stdlib.h>
71 #endif
72 #ifdef HAVE_STRING_H
73 #include <string.h>
74 #endif
75 #ifdef HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
78 #ifdef HAVE_TIME_H
79 #include <time.h>
80 #endif
81 
82 #include "cpio.h"
83 #include "err.h"
84 #include "line_reader.h"
85 #include "passphrase.h"
86 
87 /* Fixed size of uname/gname caches. */
88 #define	name_cache_size 101
89 
90 #ifndef O_BINARY
91 #define O_BINARY 0
92 #endif
93 
94 struct name_cache {
95 	int	probes;
96 	int	hits;
97 	size_t	size;
98 	struct {
99 		id_t id;
100 		char *name;
101 	} cache[name_cache_size];
102 };
103 
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) __LA_DEAD;
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 *) __LA_DEAD;
119 static void	mode_list(struct cpio *) __LA_DEAD;
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) __LA_DEAD;
126 static void	version(void) __LA_DEAD;
127 static const char * passphrase_callback(struct archive *, void *);
128 static void	passphrase_free(char *);
129 
130 int
131 main(int argc, char *argv[])
132 {
133 	static char buff[16384];
134 	struct cpio _cpio; /* Allocated on stack. */
135 	struct cpio *cpio;
136 	const char *errmsg;
137 	char *tptr;
138 	int uid, gid;
139 	int opt, t;
140 
141 	cpio = &_cpio;
142 	memset(cpio, 0, sizeof(*cpio));
143 	cpio->buff = buff;
144 	cpio->buff_size = sizeof(buff);
145 
146 #if defined(HAVE_SIGACTION) && defined(SIGPIPE)
147 	{ /* Ignore SIGPIPE signals. */
148 		struct sigaction sa;
149 		sigemptyset(&sa.sa_mask);
150 		sa.sa_flags = 0;
151 		sa.sa_handler = SIG_IGN;
152 		sigaction(SIGPIPE, &sa, NULL);
153 	}
154 #endif
155 
156 	/* Set lafe_progname before calling lafe_warnc. */
157 	lafe_setprogname(*argv, "bsdcpio");
158 
159 #if HAVE_SETLOCALE
160 	if (setlocale(LC_ALL, "") == NULL)
161 		lafe_warnc(0, "Failed to set default locale");
162 #endif
163 
164 	cpio->uid_override = -1;
165 	cpio->gid_override = -1;
166 	cpio->argv = argv;
167 	cpio->argc = argc;
168 	cpio->mode = '\0';
169 	cpio->verbose = 0;
170 	cpio->compress = '\0';
171 	cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
172 	cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
173 	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
174 	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
175 	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
176 	cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
177 	cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
178 	cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
179 #if !defined(_WIN32) && !defined(__CYGWIN__)
180 	if (geteuid() == 0)
181 		cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
182 #endif
183 	cpio->bytes_per_block = 512;
184 	cpio->filename = NULL;
185 
186 	cpio->matching = archive_match_new();
187 	if (cpio->matching == NULL)
188 		lafe_errc(1, 0, "Out of memory");
189 
190 	while ((opt = cpio_getopt(cpio)) != -1) {
191 		switch (opt) {
192 		case '0': /* GNU convention: --null, -0 */
193 			cpio->option_null = 1;
194 			break;
195 		case 'A': /* NetBSD/OpenBSD */
196 			cpio->option_append = 1;
197 			break;
198 		case 'a': /* POSIX 1997 */
199 			cpio->option_atime_restore = 1;
200 			break;
201 		case 'B': /* POSIX 1997 */
202 			cpio->bytes_per_block = 5120;
203 			break;
204 		case OPTION_B64ENCODE:
205 			cpio->add_filter = opt;
206 			break;
207 		case 'C': /* NetBSD/OpenBSD */
208 			errno = 0;
209 			tptr = NULL;
210 			t = (int)strtol(cpio->argument, &tptr, 10);
211 			if (errno || t <= 0 || *(cpio->argument) == '\0' ||
212 			    tptr == NULL || *tptr != '\0') {
213 				lafe_errc(1, 0, "Invalid blocksize: %s",
214 				    cpio->argument);
215 			}
216 			cpio->bytes_per_block = t;
217 			break;
218 		case 'c': /* POSIX 1997 */
219 			cpio->format = "odc";
220 			break;
221 		case 'd': /* POSIX 1997 */
222 			cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
223 			break;
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));
230 			break;
231 		case 'F': /* NetBSD/OpenBSD/GNU cpio */
232 			cpio->filename = cpio->argument;
233 			break;
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));
239 			break;
240 		case OPTION_GRZIP:
241 			cpio->compress = opt;
242 			break;
243 		case 'H': /* GNU cpio (also --format) */
244 			cpio->format = cpio->argument;
245 			break;
246 		case 'h':
247 			long_help();
248 			break;
249 		case 'I': /* NetBSD/OpenBSD */
250 			cpio->filename = cpio->argument;
251 			break;
252 		case 'i': /* POSIX 1997 */
253 			if (cpio->mode != '\0')
254 				lafe_errc(1, 0,
255 				    "Cannot use both -i and -%c", cpio->mode);
256 			cpio->mode = opt;
257 			break;
258 		case 'J': /* GNU tar, others */
259 			cpio->compress = opt;
260 			break;
261 		case 'j': /* GNU tar, others */
262 			cpio->compress = opt;
263 			break;
264 		case OPTION_INSECURE:
265 			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
266 			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
267 			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
268 			break;
269 		case 'L': /* GNU cpio */
270 			cpio->option_follow_links = 1;
271 			break;
272 		case 'l': /* POSIX 1997 */
273 			cpio->option_link = 1;
274 			break;
275 		case OPTION_LRZIP:
276 		case OPTION_LZ4:
277 		case OPTION_LZMA: /* GNU tar, others */
278 		case OPTION_LZOP: /* GNU tar, others */
279 		case OPTION_ZSTD:
280 			cpio->compress = opt;
281 			break;
282 		case 'm': /* POSIX 1997 */
283 			cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
284 			break;
285 		case 'n': /* GNU cpio */
286 			cpio->option_numeric_uid_gid = 1;
287 			break;
288 		case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
289 			cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
290 			break;
291 		case 'O': /* GNU cpio */
292 			cpio->filename = cpio->argument;
293 			break;
294 		case 'o': /* POSIX 1997 */
295 			if (cpio->mode != '\0')
296 				lafe_errc(1, 0,
297 				    "Cannot use both -o and -%c", cpio->mode);
298 			cpio->mode = opt;
299 			break;
300 		case 'p': /* POSIX 1997 */
301 			if (cpio->mode != '\0')
302 				lafe_errc(1, 0,
303 				    "Cannot use both -p and -%c", cpio->mode);
304 			cpio->mode = opt;
305 			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
306 			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
307 			break;
308 		case OPTION_PASSPHRASE:
309 			cpio->passphrase = cpio->argument;
310 			break;
311 		case OPTION_PRESERVE_OWNER:
312 			cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
313 			break;
314 		case OPTION_QUIET: /* GNU cpio */
315 			cpio->quiet = 1;
316 			break;
317 		case 'R': /* GNU cpio, also --owner */
318 			/* TODO: owner_parse should return uname/gname
319 			 * also; use that to set [ug]name_override. */
320 			errmsg = owner_parse(cpio->argument, &uid, &gid);
321 			if (errmsg) {
322 				lafe_warnc(-1, "%s", errmsg);
323 				usage();
324 			}
325 			if (uid != -1) {
326 				cpio->uid_override = uid;
327 				cpio->uname_override = NULL;
328 			}
329 			if (gid != -1) {
330 				cpio->gid_override = gid;
331 				cpio->gname_override = NULL;
332 			}
333 			break;
334 		case 'r': /* POSIX 1997 */
335 			cpio->option_rename = 1;
336 			break;
337 		case 't': /* POSIX 1997 */
338 			cpio->option_list = 1;
339 			break;
340 		case 'u': /* POSIX 1997 */
341 			cpio->extract_flags
342 			    &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
343 			break;
344 		case OPTION_UUENCODE:
345 			cpio->add_filter = opt;
346 			break;
347 		case 'v': /* POSIX 1997 */
348 			cpio->verbose++;
349 			break;
350 		case 'V': /* GNU cpio */
351 			cpio->dot++;
352 			break;
353 		case OPTION_VERSION: /* GNU convention */
354 			version();
355 			break;
356 #if 0
357 	        /*
358 		 * cpio_getopt() handles -W specially, so it's not
359 		 * available here.
360 		 */
361 		case 'W': /* Obscure, but useful GNU convention. */
362 			break;
363 #endif
364 		case 'y': /* tar convention */
365 			cpio->compress = opt;
366 			break;
367 		case 'Z': /* tar convention */
368 			cpio->compress = opt;
369 			break;
370 		case 'z': /* tar convention */
371 			cpio->compress = opt;
372 			break;
373 		default:
374 			usage();
375 		}
376 	}
377 
378 	/*
379 	 * Sanity-check args, error out on nonsensical combinations.
380 	 */
381 	/* -t implies -i if no mode was specified. */
382 	if (cpio->option_list && cpio->mode == '\0')
383 		cpio->mode = 'i';
384 	/* -t requires -i */
385 	if (cpio->option_list && cpio->mode != 'i')
386 		lafe_errc(1, 0, "Option -t requires -i");
387 	/* -n requires -it */
388 	if (cpio->option_numeric_uid_gid && !cpio->option_list)
389 		lafe_errc(1, 0, "Option -n requires -it");
390 	/* Can only specify format when writing */
391 	if (cpio->format != NULL && cpio->mode != 'o')
392 		lafe_errc(1, 0, "Option --format requires -o");
393 	/* -l requires -p */
394 	if (cpio->option_link && cpio->mode != 'p')
395 		lafe_errc(1, 0, "Option -l requires -p");
396 	/* -v overrides -V */
397 	if (cpio->dot && cpio->verbose)
398 		cpio->dot = 0;
399 	/* TODO: Flag other nonsensical combinations. */
400 
401 	switch (cpio->mode) {
402 	case 'o':
403 		/* TODO: Implement old binary format in libarchive,
404 		   use that here. */
405 		if (cpio->format == NULL)
406 			cpio->format = "odc"; /* Default format */
407 
408 		mode_out(cpio);
409 		break;
410 	case 'i':
411 		while (*cpio->argv != NULL) {
412 			if (archive_match_include_pattern(cpio->matching,
413 			    *cpio->argv) != ARCHIVE_OK)
414 				lafe_errc(1, 0, "Error : %s",
415 				    archive_error_string(cpio->matching));
416 			--cpio->argc;
417 			++cpio->argv;
418 		}
419 		if (cpio->option_list)
420 			mode_list(cpio);
421 		else
422 			mode_in(cpio);
423 		break;
424 	case 'p':
425 		if (*cpio->argv == NULL || **cpio->argv == '\0')
426 			lafe_errc(1, 0,
427 			    "-p mode requires a target directory");
428 		mode_pass(cpio, *cpio->argv);
429 		break;
430 	default:
431 		lafe_errc(1, 0,
432 		    "Must specify at least one of -i, -o, or -p");
433 	}
434 
435 	archive_match_free(cpio->matching);
436 	free_cache(cpio->gname_cache);
437 	free_cache(cpio->uname_cache);
438 	free(cpio->destdir);
439 	passphrase_free(cpio->ppbuff);
440 	return (cpio->return_value);
441 }
442 
443 static void
444 usage(void)
445 {
446 	const char	*p;
447 
448 	p = lafe_getprogname();
449 
450 	fprintf(stderr, "Brief Usage:\n");
451 	fprintf(stderr, "  List:    %s -it < archive\n", p);
452 	fprintf(stderr, "  Extract: %s -i < archive\n", p);
453 	fprintf(stderr, "  Create:  %s -o < filenames > archive\n", p);
454 	fprintf(stderr, "  Help:    %s --help\n", p);
455 	exit(1);
456 }
457 
458 static const char *long_help_msg =
459 	"First option must be a mode specifier:\n"
460 	"  -i Input  -o Output  -p Pass\n"
461 	"Common Options:\n"
462 	"  -v Verbose filenames     -V  one dot per file\n"
463 	"Create: %p -o [options]  < [list of files] > [archive]\n"
464 	"  -J,-y,-z,--lzma  Compress archive with xz/bzip2/gzip/lzma\n"
465 	"  --format {odc|newc|ustar}  Select archive format\n"
466 	"List: %p -it < [archive]\n"
467 	"Extract: %p -i [options] < [archive]\n";
468 
469 
470 /*
471  * Note that the word 'bsdcpio' will always appear in the first line
472  * of output.
473  *
474  * In particular, /bin/sh scripts that need to test for the presence
475  * of bsdcpio can use the following template:
476  *
477  * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
478  *          echo bsdcpio; else echo not bsdcpio; fi
479  */
480 static void
481 long_help(void)
482 {
483 	const char	*prog;
484 	const char	*p;
485 
486 	prog = lafe_getprogname();
487 
488 	fflush(stderr);
489 
490 	p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
491 	printf("%s%s: manipulate archive files\n", prog, p);
492 
493 	for (p = long_help_msg; *p != '\0'; p++) {
494 		if (*p == '%') {
495 			if (p[1] == 'p') {
496 				fputs(prog, stdout);
497 				p++;
498 			} else
499 				putchar('%');
500 		} else
501 			putchar(*p);
502 	}
503 	version();
504 }
505 
506 static void
507 version(void)
508 {
509 	fprintf(stdout,"bsdcpio %s - %s \n",
510 	    BSDCPIO_VERSION_STRING,
511 	    archive_version_details());
512 	exit(0);
513 }
514 
515 static void
516 mode_out(struct cpio *cpio)
517 {
518 	struct archive_entry *entry, *spare;
519 	struct lafe_line_reader *lr;
520 	const char *p;
521 	int r;
522 
523 	if (cpio->option_append)
524 		lafe_errc(1, 0, "Append mode not yet supported.");
525 
526 	cpio->archive_read_disk = archive_read_disk_new();
527 	if (cpio->archive_read_disk == NULL)
528 		lafe_errc(1, 0, "Failed to allocate archive object");
529 	if (cpio->option_follow_links)
530 		archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
531 	else
532 		archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
533 	archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
534 
535 	cpio->archive = archive_write_new();
536 	if (cpio->archive == NULL)
537 		lafe_errc(1, 0, "Failed to allocate archive object");
538 	switch (cpio->compress) {
539 	case OPTION_GRZIP:
540 		r = archive_write_add_filter_grzip(cpio->archive);
541 		break;
542 	case 'J':
543 		r = archive_write_add_filter_xz(cpio->archive);
544 		break;
545 	case OPTION_LRZIP:
546 		r = archive_write_add_filter_lrzip(cpio->archive);
547 		break;
548 	case OPTION_LZ4:
549 		r = archive_write_add_filter_lz4(cpio->archive);
550 		break;
551 	case OPTION_LZMA:
552 		r = archive_write_add_filter_lzma(cpio->archive);
553 		break;
554 	case OPTION_LZOP:
555 		r = archive_write_add_filter_lzop(cpio->archive);
556 		break;
557 	case OPTION_ZSTD:
558 		r = archive_write_add_filter_zstd(cpio->archive);
559 		break;
560 	case 'j': case 'y':
561 		r = archive_write_add_filter_bzip2(cpio->archive);
562 		break;
563 	case 'z':
564 		r = archive_write_add_filter_gzip(cpio->archive);
565 		break;
566 	case 'Z':
567 		r = archive_write_add_filter_compress(cpio->archive);
568 		break;
569 	default:
570 		r = archive_write_add_filter_none(cpio->archive);
571 		break;
572 	}
573 	if (r < ARCHIVE_WARN)
574 		lafe_errc(1, 0, "Requested compression not available");
575 	switch (cpio->add_filter) {
576 	case 0:
577 		r = ARCHIVE_OK;
578 		break;
579 	case OPTION_B64ENCODE:
580 		r = archive_write_add_filter_b64encode(cpio->archive);
581 		break;
582 	case OPTION_UUENCODE:
583 		r = archive_write_add_filter_uuencode(cpio->archive);
584 		break;
585 	}
586 	if (r < ARCHIVE_WARN)
587 		lafe_errc(1, 0, "Requested filter not available");
588 	r = archive_write_set_format_by_name(cpio->archive, cpio->format);
589 	if (r != ARCHIVE_OK)
590 		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
591 	archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
592 	cpio->linkresolver = archive_entry_linkresolver_new();
593 	archive_entry_linkresolver_set_strategy(cpio->linkresolver,
594 	    archive_format(cpio->archive));
595 	if (cpio->passphrase != NULL)
596 		r = archive_write_set_passphrase(cpio->archive,
597 			cpio->passphrase);
598 	else
599 		r = archive_write_set_passphrase_callback(cpio->archive, cpio,
600 			&passphrase_callback);
601 	if (r != ARCHIVE_OK)
602 		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
603 
604 	/*
605 	 * The main loop:  Copy each file into the output archive.
606 	 */
607 	r = archive_write_open_filename(cpio->archive, cpio->filename);
608 	if (r != ARCHIVE_OK)
609 		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
610 	lr = lafe_line_reader("-", cpio->option_null);
611 	while ((p = lafe_line_reader_next(lr)) != NULL)
612 		file_to_archive(cpio, p);
613 	lafe_line_reader_free(lr);
614 
615 	/*
616 	 * The hardlink detection may have queued up a couple of entries
617 	 * that can now be flushed.
618 	 */
619 	entry = NULL;
620 	archive_entry_linkify(cpio->linkresolver, &entry, &spare);
621 	while (entry != NULL) {
622 		entry_to_archive(cpio, entry);
623 		archive_entry_free(entry);
624 		entry = NULL;
625 		archive_entry_linkify(cpio->linkresolver, &entry, &spare);
626 	}
627 
628 	r = archive_write_close(cpio->archive);
629 	if (cpio->dot)
630 		fprintf(stderr, "\n");
631 	if (r != ARCHIVE_OK)
632 		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
633 
634 	if (!cpio->quiet) {
635 		int64_t blocks =
636 			(archive_filter_bytes(cpio->archive, 0) + 511)
637 			/ 512;
638 		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
639 		    blocks == 1 ? "block" : "blocks");
640 	}
641 	archive_write_free(cpio->archive);
642 	archive_entry_linkresolver_free(cpio->linkresolver);
643 }
644 
645 static const char *
646 remove_leading_slash(const char *p)
647 {
648 	const char *rp;
649 
650 	/* Remove leading "//./" or "//?/" or "//?/UNC/"
651 	 * (absolute path prefixes used by Windows API) */
652 	if ((p[0] == '/' || p[0] == '\\') &&
653 	    (p[1] == '/' || p[1] == '\\') &&
654 	    (p[2] == '.' || p[2] == '?') &&
655 	    (p[3] == '/' || p[3] == '\\'))
656 	{
657 		if (p[2] == '?' &&
658 		    (p[4] == 'U' || p[4] == 'u') &&
659 		    (p[5] == 'N' || p[5] == 'n') &&
660 		    (p[6] == 'C' || p[6] == 'c') &&
661 		    (p[7] == '/' || p[7] == '\\'))
662 			p += 8;
663 		else
664 			p += 4;
665 	}
666 	do {
667 		rp = p;
668 		/* Remove leading drive letter from archives created
669 		 * on Windows. */
670 		if (((p[0] >= 'a' && p[0] <= 'z') ||
671 		     (p[0] >= 'A' && p[0] <= 'Z')) &&
672 			 p[1] == ':') {
673 			p += 2;
674 		}
675 		/* Remove leading "/../", "//", etc. */
676 		while (p[0] == '/' || p[0] == '\\') {
677 			if (p[1] == '.' && p[2] == '.' &&
678 				(p[3] == '/' || p[3] == '\\')) {
679 				p += 3; /* Remove "/..", leave "/"
680 					 * for next pass. */
681 			} else
682 				p += 1; /* Remove "/". */
683 		}
684 	} while (rp != p);
685 	return (p);
686 }
687 
688 /*
689  * This is used by both out mode (to copy objects from disk into
690  * an archive) and pass mode (to copy objects from disk to
691  * an archive_write_disk "archive").
692  */
693 static int
694 file_to_archive(struct cpio *cpio, const char *srcpath)
695 {
696 	const char *destpath;
697 	struct archive_entry *entry, *spare;
698 	size_t len;
699 	int r;
700 
701 	/*
702 	 * Create an archive_entry describing the source file.
703 	 *
704 	 */
705 	entry = archive_entry_new();
706 	if (entry == NULL)
707 		lafe_errc(1, 0, "Couldn't allocate entry");
708 	archive_entry_copy_sourcepath(entry, srcpath);
709 	r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
710 	    entry, -1, NULL);
711 	if (r < ARCHIVE_FAILED)
712 		lafe_errc(1, 0, "%s",
713 		    archive_error_string(cpio->archive_read_disk));
714 	if (r < ARCHIVE_OK)
715 		lafe_warnc(0, "%s",
716 		    archive_error_string(cpio->archive_read_disk));
717 	if (r <= ARCHIVE_FAILED) {
718 		archive_entry_free(entry);
719 		cpio->return_value = 1;
720 		return (r);
721 	}
722 
723 	if (cpio->uid_override >= 0) {
724 		archive_entry_set_uid(entry, cpio->uid_override);
725 		archive_entry_set_uname(entry, cpio->uname_override);
726 	}
727 	if (cpio->gid_override >= 0) {
728 		archive_entry_set_gid(entry, cpio->gid_override);
729 		archive_entry_set_gname(entry, cpio->gname_override);
730 	}
731 
732 	/*
733 	 * Generate a destination path for this entry.
734 	 * "destination path" is the name to which it will be copied in
735 	 * pass mode or the name that will go into the archive in
736 	 * output mode.
737 	 */
738 	destpath = srcpath;
739 	if (cpio->destdir) {
740 		len = strlen(cpio->destdir) + strlen(srcpath) + 8;
741 		if (len >= cpio->pass_destpath_alloc) {
742 			while (len >= cpio->pass_destpath_alloc) {
743 				cpio->pass_destpath_alloc += 512;
744 				cpio->pass_destpath_alloc *= 2;
745 			}
746 			free(cpio->pass_destpath);
747 			cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
748 			if (cpio->pass_destpath == NULL)
749 				lafe_errc(1, ENOMEM,
750 				    "Can't allocate path buffer");
751 		}
752 		strcpy(cpio->pass_destpath, cpio->destdir);
753 		strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
754 		destpath = cpio->pass_destpath;
755 	}
756 	if (cpio->option_rename)
757 		destpath = cpio_rename(destpath);
758 	if (destpath == NULL) {
759 		archive_entry_free(entry);
760 		return (0);
761 	}
762 	archive_entry_copy_pathname(entry, destpath);
763 
764 	/*
765 	 * If we're trying to preserve hardlinks, match them here.
766 	 */
767 	spare = NULL;
768 	if (cpio->linkresolver != NULL
769 	    && archive_entry_filetype(entry) != AE_IFDIR) {
770 		archive_entry_linkify(cpio->linkresolver, &entry, &spare);
771 	}
772 
773 	if (entry != NULL) {
774 		r = entry_to_archive(cpio, entry);
775 		archive_entry_free(entry);
776 		if (spare != NULL) {
777 			if (r == 0)
778 				r = entry_to_archive(cpio, spare);
779 			archive_entry_free(spare);
780 		}
781 	}
782 	return (r);
783 }
784 
785 static int
786 entry_to_archive(struct cpio *cpio, struct archive_entry *entry)
787 {
788 	const char *destpath = archive_entry_pathname(entry);
789 	const char *srcpath = archive_entry_sourcepath(entry);
790 	int fd = -1;
791 	ssize_t bytes_read;
792 	int r;
793 
794 	/* Print out the destination name to the user. */
795 	if (cpio->verbose)
796 		fprintf(stderr,"%s", destpath);
797 	if (cpio->dot)
798 		fprintf(stderr, ".");
799 
800 	/*
801 	 * Option_link only makes sense in pass mode and for
802 	 * regular files.  Also note: if a link operation fails
803 	 * because of cross-device restrictions, we'll fall back
804 	 * to copy mode for that entry.
805 	 *
806 	 * TODO: Test other cpio implementations to see if they
807 	 * hard-link anything other than regular files here.
808 	 */
809 	if (cpio->option_link
810 	    && archive_entry_filetype(entry) == AE_IFREG)
811 	{
812 		struct archive_entry *t;
813 		/* Save the original entry in case we need it later. */
814 		t = archive_entry_clone(entry);
815 		if (t == NULL)
816 			lafe_errc(1, ENOMEM, "Can't create link");
817 		/* Note: link(2) doesn't create parent directories,
818 		 * so we use archive_write_header() instead as a
819 		 * convenience. */
820 		archive_entry_set_hardlink(t, srcpath);
821 		/* This is a straight link that carries no data. */
822 		archive_entry_set_size(t, 0);
823 		r = archive_write_header(cpio->archive, t);
824 		archive_entry_free(t);
825 		if (r != ARCHIVE_OK)
826 			lafe_warnc(archive_errno(cpio->archive),
827 			    "%s", archive_error_string(cpio->archive));
828 		if (r == ARCHIVE_FATAL)
829 			exit(1);
830 #ifdef EXDEV
831 		if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
832 			/* Cross-device link:  Just fall through and use
833 			 * the original entry to copy the file over. */
834 			lafe_warnc(0, "Copying file instead");
835 		} else
836 #endif
837 		return (0);
838 	}
839 
840 	/*
841 	 * Make sure we can open the file (if necessary) before
842 	 * trying to write the header.
843 	 */
844 	if (archive_entry_filetype(entry) == AE_IFREG) {
845 		if (archive_entry_size(entry) > 0) {
846 			fd = open(srcpath, O_RDONLY | O_BINARY);
847 			if (fd < 0) {
848 				lafe_warnc(errno,
849 				    "%s: could not open file", srcpath);
850 				goto cleanup;
851 			}
852 		}
853 	} else {
854 		archive_entry_set_size(entry, 0);
855 	}
856 
857 	r = archive_write_header(cpio->archive, entry);
858 
859 	if (r != ARCHIVE_OK)
860 		lafe_warnc(archive_errno(cpio->archive),
861 		    "%s: %s",
862 		    srcpath,
863 		    archive_error_string(cpio->archive));
864 
865 	if (r == ARCHIVE_FATAL)
866 		exit(1);
867 
868 	if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
869 		bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size);
870 		while (bytes_read > 0) {
871 			ssize_t bytes_write;
872 			bytes_write = archive_write_data(cpio->archive,
873 			    cpio->buff, bytes_read);
874 			if (bytes_write < 0)
875 				lafe_errc(1, archive_errno(cpio->archive),
876 				    "%s", archive_error_string(cpio->archive));
877 			if (bytes_write < bytes_read) {
878 				lafe_warnc(0,
879 				    "Truncated write; file may have "
880 				    "grown while being archived.");
881 			}
882 			bytes_read = read(fd, cpio->buff,
883 			    (unsigned)cpio->buff_size);
884 		}
885 	}
886 
887 	fd = restore_time(cpio, entry, srcpath, fd);
888 
889 cleanup:
890 	if (cpio->verbose)
891 		fprintf(stderr,"\n");
892 	if (fd >= 0)
893 		close(fd);
894 	return (0);
895 }
896 
897 static int
898 restore_time(struct cpio *cpio, struct archive_entry *entry,
899     const char *name, int fd)
900 {
901 #ifndef HAVE_UTIMES
902 	static int warned = 0;
903 
904 	(void)cpio; /* UNUSED */
905 	(void)entry; /* UNUSED */
906 	(void)name; /* UNUSED */
907 
908 	if (!warned)
909 		lafe_warnc(0, "Can't restore access times on this platform");
910 	warned = 1;
911 	return (fd);
912 #else
913 #if defined(_WIN32) && !defined(__CYGWIN__)
914 	struct __timeval times[2];
915 #else
916 	struct timeval times[2];
917 #endif
918 
919 	if (!cpio->option_atime_restore)
920 		return (fd);
921 
922         times[1].tv_sec = archive_entry_mtime(entry);
923         times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
924 
925         times[0].tv_sec = archive_entry_atime(entry);
926         times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
927 
928 #if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
929         if (fd >= 0 && futimes(fd, times) == 0)
930 		return (fd);
931 #endif
932 	/*
933 	 * Some platform cannot restore access times if the file descriptor
934 	 * is still opened.
935 	 */
936 	if (fd >= 0) {
937 		close(fd);
938 		fd = -1;
939 	}
940 
941 #ifdef HAVE_LUTIMES
942         if (lutimes(name, times) != 0)
943 #else
944         if ((AE_IFLNK != archive_entry_filetype(entry))
945 			&& utimes(name, times) != 0)
946 #endif
947                 lafe_warnc(errno, "Can't update time for %s", name);
948 #endif
949 	return (fd);
950 }
951 
952 
953 static void
954 mode_in(struct cpio *cpio)
955 {
956 	struct archive *a;
957 	struct archive_entry *entry;
958 	struct archive *ext;
959 	const char *destpath;
960 	int r;
961 
962 	ext = archive_write_disk_new();
963 	if (ext == NULL)
964 		lafe_errc(1, 0, "Couldn't allocate restore object");
965 	r = archive_write_disk_set_options(ext, cpio->extract_flags);
966 	if (r != ARCHIVE_OK)
967 		lafe_errc(1, 0, "%s", archive_error_string(ext));
968 	a = archive_read_new();
969 	if (a == NULL)
970 		lafe_errc(1, 0, "Couldn't allocate archive object");
971 	archive_read_support_filter_all(a);
972 	archive_read_support_format_all(a);
973 	if (cpio->passphrase != NULL)
974 		r = archive_read_add_passphrase(a, cpio->passphrase);
975 	else
976 		r = archive_read_set_passphrase_callback(a, cpio,
977 			&passphrase_callback);
978 	if (r != ARCHIVE_OK)
979 		lafe_errc(1, 0, "%s", archive_error_string(a));
980 
981 	if (archive_read_open_filename(a, cpio->filename,
982 					cpio->bytes_per_block))
983 		lafe_errc(1, archive_errno(a),
984 		    "%s", archive_error_string(a));
985 	for (;;) {
986 		r = archive_read_next_header(a, &entry);
987 		if (r == ARCHIVE_EOF)
988 			break;
989 		if (r != ARCHIVE_OK) {
990 			lafe_errc(1, archive_errno(a),
991 			    "%s", archive_error_string(a));
992 		}
993 		if (archive_match_path_excluded(cpio->matching, entry))
994 			continue;
995 		if (cpio->option_rename) {
996 			destpath = cpio_rename(archive_entry_pathname(entry));
997 			archive_entry_set_pathname(entry, destpath);
998 		} else
999 			destpath = archive_entry_pathname(entry);
1000 		if (destpath == NULL)
1001 			continue;
1002 		if (cpio->verbose)
1003 			fprintf(stderr, "%s\n", destpath);
1004 		if (cpio->dot)
1005 			fprintf(stderr, ".");
1006 		if (cpio->uid_override >= 0)
1007 			archive_entry_set_uid(entry, cpio->uid_override);
1008 		if (cpio->gid_override >= 0)
1009 			archive_entry_set_gid(entry, cpio->gid_override);
1010 		r = archive_write_header(ext, entry);
1011 		if (r != ARCHIVE_OK) {
1012 			fprintf(stderr, "%s: %s\n",
1013 			    archive_entry_pathname(entry),
1014 			    archive_error_string(ext));
1015 		} else if (!archive_entry_size_is_set(entry)
1016 		    || archive_entry_size(entry) > 0) {
1017 			r = extract_data(a, ext);
1018 			if (r != ARCHIVE_OK)
1019 				cpio->return_value = 1;
1020 		}
1021 	}
1022 	r = archive_read_close(a);
1023 	if (cpio->dot)
1024 		fprintf(stderr, "\n");
1025 	if (r != ARCHIVE_OK)
1026 		lafe_errc(1, 0, "%s", archive_error_string(a));
1027 	r = archive_write_close(ext);
1028 	if (r != ARCHIVE_OK)
1029 		lafe_errc(1, 0, "%s", archive_error_string(ext));
1030 	if (!cpio->quiet) {
1031 		int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1032 			      / 512;
1033 		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1034 		    blocks == 1 ? "block" : "blocks");
1035 	}
1036 	archive_read_free(a);
1037 	archive_write_free(ext);
1038 	exit(cpio->return_value);
1039 }
1040 
1041 /*
1042  * Exits if there's a fatal error.  Returns ARCHIVE_OK
1043  * if everything is kosher.
1044  */
1045 static int
1046 extract_data(struct archive *ar, struct archive *aw)
1047 {
1048 	int r;
1049 	size_t size;
1050 	const void *block;
1051 	int64_t offset;
1052 
1053 	for (;;) {
1054 		r = archive_read_data_block(ar, &block, &size, &offset);
1055 		if (r == ARCHIVE_EOF)
1056 			return (ARCHIVE_OK);
1057 		if (r != ARCHIVE_OK) {
1058 			lafe_warnc(archive_errno(ar),
1059 			    "%s", archive_error_string(ar));
1060 			exit(1);
1061 		}
1062 		r = (int)archive_write_data_block(aw, block, size, offset);
1063 		if (r != ARCHIVE_OK) {
1064 			lafe_warnc(archive_errno(aw),
1065 			    "%s", archive_error_string(aw));
1066 			return (r);
1067 		}
1068 	}
1069 }
1070 
1071 static void
1072 mode_list(struct cpio *cpio)
1073 {
1074 	struct archive *a;
1075 	struct archive_entry *entry;
1076 	int r;
1077 
1078 	a = archive_read_new();
1079 	if (a == NULL)
1080 		lafe_errc(1, 0, "Couldn't allocate archive object");
1081 	archive_read_support_filter_all(a);
1082 	archive_read_support_format_all(a);
1083 	if (cpio->passphrase != NULL)
1084 		r = archive_read_add_passphrase(a, cpio->passphrase);
1085 	else
1086 		r = archive_read_set_passphrase_callback(a, cpio,
1087 			&passphrase_callback);
1088 	if (r != ARCHIVE_OK)
1089 		lafe_errc(1, 0, "%s", archive_error_string(a));
1090 
1091 	if (archive_read_open_filename(a, cpio->filename,
1092 					cpio->bytes_per_block))
1093 		lafe_errc(1, archive_errno(a),
1094 		    "%s", archive_error_string(a));
1095 	for (;;) {
1096 		r = archive_read_next_header(a, &entry);
1097 		if (r == ARCHIVE_EOF)
1098 			break;
1099 		if (r != ARCHIVE_OK) {
1100 			lafe_errc(1, archive_errno(a),
1101 			    "%s", archive_error_string(a));
1102 		}
1103 		if (archive_match_path_excluded(cpio->matching, entry))
1104 			continue;
1105 		if (cpio->verbose)
1106 			list_item_verbose(cpio, entry);
1107 		else
1108 			fprintf(stdout, "%s\n", archive_entry_pathname(entry));
1109 	}
1110 	r = archive_read_close(a);
1111 	if (r != ARCHIVE_OK)
1112 		lafe_errc(1, 0, "%s", archive_error_string(a));
1113 	if (!cpio->quiet) {
1114 		int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1115 			      / 512;
1116 		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1117 		    blocks == 1 ? "block" : "blocks");
1118 	}
1119 	archive_read_free(a);
1120 	exit(0);
1121 }
1122 
1123 /*
1124  * Display information about the current file.
1125  *
1126  * The format here roughly duplicates the output of 'ls -l'.
1127  * This is based on SUSv2, where 'tar tv' is documented as
1128  * listing additional information in an "unspecified format,"
1129  * and 'pax -l' is documented as using the same format as 'ls -l'.
1130  */
1131 static void
1132 list_item_verbose(struct cpio *cpio, struct archive_entry *entry)
1133 {
1134 	char			 size[32];
1135 	char			 date[32];
1136 	char			 uids[16], gids[16];
1137 	const char 		*uname, *gname;
1138 	FILE			*out = stdout;
1139 	const char		*fmt;
1140 	time_t			 mtime;
1141 	static time_t		 now;
1142 
1143 	if (!now)
1144 		time(&now);
1145 
1146 	if (cpio->option_numeric_uid_gid) {
1147 		/* Format numeric uid/gid for display. */
1148 		strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
1149 		uname = uids;
1150 		strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
1151 		gname = gids;
1152 	} else {
1153 		/* Use uname if it's present, else lookup name from uid. */
1154 		uname = archive_entry_uname(entry);
1155 		if (uname == NULL)
1156 			uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
1157 		/* Use gname if it's present, else lookup name from gid. */
1158 		gname = archive_entry_gname(entry);
1159 		if (gname == NULL)
1160 			gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
1161 	}
1162 
1163 	/* Print device number or file size. */
1164 	if (archive_entry_filetype(entry) == AE_IFCHR
1165 	    || archive_entry_filetype(entry) == AE_IFBLK) {
1166 		snprintf(size, sizeof(size), "%lu,%lu",
1167 		    (unsigned long)archive_entry_rdevmajor(entry),
1168 		    (unsigned long)archive_entry_rdevminor(entry));
1169 	} else {
1170 		strcpy(size, cpio_i64toa(archive_entry_size(entry)));
1171 	}
1172 
1173 	/* Format the time using 'ls -l' conventions. */
1174 	mtime = archive_entry_mtime(entry);
1175 #if defined(_WIN32) && !defined(__CYGWIN__)
1176 	/* Windows' strftime function does not support %e format. */
1177 	if (mtime - now > 365*86400/2
1178 		|| mtime - now < -365*86400/2)
1179 		fmt = cpio->day_first ? "%d %b  %Y" : "%b %d  %Y";
1180 	else
1181 		fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
1182 #else
1183 	if (mtime - now > 365*86400/2
1184 		|| mtime - now < -365*86400/2)
1185 		fmt = cpio->day_first ? "%e %b  %Y" : "%b %e  %Y";
1186 	else
1187 		fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
1188 #endif
1189 	strftime(date, sizeof(date), fmt, localtime(&mtime));
1190 
1191 	fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
1192 	    archive_entry_strmode(entry),
1193 	    archive_entry_nlink(entry),
1194 	    uname, gname, size, date,
1195 	    archive_entry_pathname(entry));
1196 
1197 	/* Extra information for links. */
1198 	if (archive_entry_hardlink(entry)) /* Hard link */
1199 		fprintf(out, " link to %s", archive_entry_hardlink(entry));
1200 	else if (archive_entry_symlink(entry)) /* Symbolic link */
1201 		fprintf(out, " -> %s", archive_entry_symlink(entry));
1202 	fprintf(out, "\n");
1203 }
1204 
1205 static void
1206 mode_pass(struct cpio *cpio, const char *destdir)
1207 {
1208 	struct lafe_line_reader *lr;
1209 	const char *p;
1210 	int r;
1211 	size_t destdir_len;
1212 
1213 	/* Ensure target dir has a trailing '/' to simplify path surgery. */
1214 	destdir_len = strlen(destdir);
1215 	cpio->destdir = malloc(destdir_len + 8);
1216 	memcpy(cpio->destdir, destdir, destdir_len);
1217 	if (destdir_len == 0 || destdir[destdir_len - 1] != '/')
1218 		cpio->destdir[destdir_len++] = '/';
1219 	cpio->destdir[destdir_len++] = '\0';
1220 
1221 	cpio->archive = archive_write_disk_new();
1222 	if (cpio->archive == NULL)
1223 		lafe_errc(1, 0, "Failed to allocate archive object");
1224 	r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
1225 	if (r != ARCHIVE_OK)
1226 		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1227 	cpio->linkresolver = archive_entry_linkresolver_new();
1228 	archive_write_disk_set_standard_lookup(cpio->archive);
1229 
1230 	cpio->archive_read_disk = archive_read_disk_new();
1231 	if (cpio->archive_read_disk == NULL)
1232 		lafe_errc(1, 0, "Failed to allocate archive object");
1233 	if (cpio->option_follow_links)
1234 		archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
1235 	else
1236 		archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
1237 	archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
1238 
1239 	lr = lafe_line_reader("-", cpio->option_null);
1240 	while ((p = lafe_line_reader_next(lr)) != NULL)
1241 		file_to_archive(cpio, p);
1242 	lafe_line_reader_free(lr);
1243 
1244 	archive_entry_linkresolver_free(cpio->linkresolver);
1245 	r = archive_write_close(cpio->archive);
1246 	if (cpio->dot)
1247 		fprintf(stderr, "\n");
1248 	if (r != ARCHIVE_OK)
1249 		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1250 
1251 	if (!cpio->quiet) {
1252 		int64_t blocks =
1253 			(archive_filter_bytes(cpio->archive, 0) + 511)
1254 			/ 512;
1255 		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1256 		    blocks == 1 ? "block" : "blocks");
1257 	}
1258 
1259 	archive_write_free(cpio->archive);
1260 	free(cpio->pass_destpath);
1261 }
1262 
1263 /*
1264  * Prompt for a new name for this entry.  Returns a pointer to the
1265  * new name or NULL if the entry should not be copied.  This
1266  * implements the semantics defined in POSIX.1-1996, which specifies
1267  * that an input of '.' means the name should be unchanged.  GNU cpio
1268  * treats '.' as a literal new name.
1269  */
1270 static const char *
1271 cpio_rename(const char *name)
1272 {
1273 	static char buff[1024];
1274 	FILE *t;
1275 	char *p, *ret;
1276 #if defined(_WIN32) && !defined(__CYGWIN__)
1277 	FILE *to;
1278 
1279 	t = fopen("CONIN$", "r");
1280 	if (t == NULL)
1281 		return (name);
1282 	to = fopen("CONOUT$", "w");
1283 	if (to == NULL) {
1284 		fclose(t);
1285 		return (name);
1286 	}
1287 	fprintf(to, "%s (Enter/./(new name))? ", name);
1288 	fclose(to);
1289 #else
1290 	t = fopen("/dev/tty", "r+");
1291 	if (t == NULL)
1292 		return (name);
1293 	fprintf(t, "%s (Enter/./(new name))? ", name);
1294 	fflush(t);
1295 #endif
1296 
1297 	p = fgets(buff, sizeof(buff), t);
1298 	fclose(t);
1299 	if (p == NULL)
1300 		/* End-of-file is a blank line. */
1301 		return (NULL);
1302 
1303 	while (*p == ' ' || *p == '\t')
1304 		++p;
1305 	if (*p == '\n' || *p == '\0')
1306 		/* Empty line. */
1307 		return (NULL);
1308 	if (*p == '.' && p[1] == '\n')
1309 		/* Single period preserves original name. */
1310 		return (name);
1311 	ret = p;
1312 	/* Trim the final newline. */
1313 	while (*p != '\0' && *p != '\n')
1314 		++p;
1315 	/* Overwrite the final \n with a null character. */
1316 	*p = '\0';
1317 	return (ret);
1318 }
1319 
1320 static void
1321 free_cache(struct name_cache *cache)
1322 {
1323 	size_t i;
1324 
1325 	if (cache != NULL) {
1326 		for (i = 0; i < cache->size; i++)
1327 			free(cache->cache[i].name);
1328 		free(cache);
1329 	}
1330 }
1331 
1332 /*
1333  * Lookup uname/gname from uid/gid, return NULL if no match.
1334  */
1335 static const char *
1336 lookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
1337     int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
1338 {
1339 	char asnum[16];
1340 	struct name_cache	*cache;
1341 	const char *name;
1342 	int slot;
1343 
1344 
1345 	if (*name_cache_variable == NULL) {
1346 		*name_cache_variable = calloc(1, sizeof(struct name_cache));
1347 		if (*name_cache_variable == NULL)
1348 			lafe_errc(1, ENOMEM, "No more memory");
1349 		(*name_cache_variable)->size = name_cache_size;
1350 	}
1351 
1352 	cache = *name_cache_variable;
1353 	cache->probes++;
1354 
1355 	slot = id % cache->size;
1356 	if (cache->cache[slot].name != NULL) {
1357 		if (cache->cache[slot].id == id) {
1358 			cache->hits++;
1359 			return (cache->cache[slot].name);
1360 		}
1361 		free(cache->cache[slot].name);
1362 		cache->cache[slot].name = NULL;
1363 	}
1364 
1365 	if (lookup_fn(cpio, &name, id)) {
1366 		/* If lookup failed, format it as a number. */
1367 		snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
1368 		name = asnum;
1369 	}
1370 
1371 	cache->cache[slot].name = strdup(name);
1372 	if (cache->cache[slot].name != NULL) {
1373 		cache->cache[slot].id = id;
1374 		return (cache->cache[slot].name);
1375 	}
1376 
1377 	/*
1378 	 * Conveniently, NULL marks an empty slot, so
1379 	 * if the strdup() fails, we've just failed to
1380 	 * cache it.  No recovery necessary.
1381 	 */
1382 	return (NULL);
1383 }
1384 
1385 static const char *
1386 lookup_uname(struct cpio *cpio, uid_t uid)
1387 {
1388 	return (lookup_name(cpio, &cpio->uname_cache,
1389 		    &lookup_uname_helper, (id_t)uid));
1390 }
1391 
1392 static int
1393 lookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
1394 {
1395 	struct passwd	*pwent;
1396 
1397 	(void)cpio; /* UNUSED */
1398 
1399 	errno = 0;
1400 	pwent = getpwuid((uid_t)id);
1401 	if (pwent == NULL) {
1402 		if (errno && errno != ENOENT)
1403 			lafe_warnc(errno, "getpwuid(%s) failed",
1404 			    cpio_i64toa((int64_t)id));
1405 		return 1;
1406 	}
1407 
1408 	*name = pwent->pw_name;
1409 	return 0;
1410 }
1411 
1412 static const char *
1413 lookup_gname(struct cpio *cpio, gid_t gid)
1414 {
1415 	return (lookup_name(cpio, &cpio->gname_cache,
1416 		    &lookup_gname_helper, (id_t)gid));
1417 }
1418 
1419 static int
1420 lookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
1421 {
1422 	struct group	*grent;
1423 
1424 	(void)cpio; /* UNUSED */
1425 
1426 	errno = 0;
1427 	grent = getgrgid((gid_t)id);
1428 	if (grent == NULL) {
1429 		if (errno && errno != ENOENT)
1430 			lafe_warnc(errno, "getgrgid(%s) failed",
1431 			    cpio_i64toa((int64_t)id));
1432 		return 1;
1433 	}
1434 
1435 	*name = grent->gr_name;
1436 	return 0;
1437 }
1438 
1439 /*
1440  * It would be nice to just use printf() for formatting large numbers,
1441  * but the compatibility problems are a big headache.  Hence the
1442  * following simple utility function.
1443  */
1444 const char *
1445 cpio_i64toa(int64_t n0)
1446 {
1447 	/* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
1448 	 * We also need 1 byte for '-' and 1 for '\0'.
1449 	 */
1450 	static char buff[22];
1451 	int64_t n = n0 < 0 ? -n0 : n0;
1452 	char *p = buff + sizeof(buff);
1453 
1454 	*--p = '\0';
1455 	do {
1456 		*--p = '0' + (int)(n % 10);
1457 		n /= 10;
1458 	} while (n > 0);
1459 	if (n0 < 0)
1460 		*--p = '-';
1461 	return p;
1462 }
1463 
1464 #define PPBUFF_SIZE 1024
1465 static const char *
1466 passphrase_callback(struct archive *a, void *_client_data)
1467 {
1468 	struct cpio *cpio = (struct cpio *)_client_data;
1469 	(void)a; /* UNUSED */
1470 
1471 	if (cpio->ppbuff == NULL) {
1472 		cpio->ppbuff = malloc(PPBUFF_SIZE);
1473 		if (cpio->ppbuff == NULL)
1474 			lafe_errc(1, errno, "Out of memory");
1475 	}
1476 	return lafe_readpassphrase("Enter passphrase:",
1477 		cpio->ppbuff, PPBUFF_SIZE);
1478 }
1479 
1480 static void
1481 passphrase_free(char *ppbuff)
1482 {
1483 	if (ppbuff != NULL) {
1484 		memset(ppbuff, 0, PPBUFF_SIZE);
1485 		free(ppbuff);
1486 	}
1487 }
1488