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