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