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