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