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