1228753Smm/*-
2228753Smm * Copyright (c) 2003-2007 Tim Kientzle
3228753Smm * All rights reserved.
4228753Smm *
5228753Smm * Redistribution and use in source and binary forms, with or without
6228753Smm * modification, are permitted provided that the following conditions
7228753Smm * are met:
8228753Smm * 1. Redistributions of source code must retain the above copyright
9228753Smm *    notice, this list of conditions and the following disclaimer
10228753Smm *    in this position and unchanged.
11228753Smm * 2. Redistributions in binary form must reproduce the above copyright
12228753Smm *    notice, this list of conditions and the following disclaimer in the
13228753Smm *    documentation and/or other materials provided with the distribution.
14228753Smm *
15228753Smm * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16228753Smm * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17228753Smm * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18228753Smm * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19228753Smm * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20228753Smm * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21228753Smm * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22228753Smm * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23228753Smm * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24228753Smm * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25228753Smm */
26228753Smm
27228753Smm
28228753Smm#include "cpio_platform.h"
29228763Smm__FBSDID("$FreeBSD$");
30228753Smm
31228753Smm#include <sys/types.h>
32228753Smm#include <archive.h>
33228753Smm#include <archive_entry.h>
34228753Smm
35228753Smm#ifdef HAVE_SYS_MKDEV_H
36228753Smm#include <sys/mkdev.h>
37228753Smm#endif
38228753Smm#ifdef HAVE_SYS_STAT_H
39228753Smm#include <sys/stat.h>
40228753Smm#endif
41228753Smm#ifdef HAVE_SYS_TIME_H
42228753Smm#include <sys/time.h>
43228753Smm#endif
44228753Smm#ifdef HAVE_ERRNO_H
45228753Smm#include <errno.h>
46228753Smm#endif
47228753Smm#ifdef HAVE_FCNTL_H
48228753Smm#include <fcntl.h>
49228753Smm#endif
50228753Smm#ifdef HAVE_GRP_H
51228753Smm#include <grp.h>
52228753Smm#endif
53232153Smm#ifdef HAVE_LOCALE_H
54232153Smm#include <locale.h>
55232153Smm#endif
56228753Smm#ifdef HAVE_PWD_H
57228753Smm#include <pwd.h>
58228753Smm#endif
59232153Smm#ifdef HAVE_SIGNAL_H
60232153Smm#include <signal.h>
61232153Smm#endif
62228753Smm#ifdef HAVE_STDARG_H
63228753Smm#include <stdarg.h>
64228753Smm#endif
65228753Smm#ifdef HAVE_STDINT_H
66228753Smm#include <stdint.h>
67228753Smm#endif
68228753Smm#include <stdio.h>
69228753Smm#ifdef HAVE_STDLIB_H
70228753Smm#include <stdlib.h>
71228753Smm#endif
72228753Smm#ifdef HAVE_STRING_H
73228753Smm#include <string.h>
74228753Smm#endif
75228753Smm#ifdef HAVE_UNISTD_H
76228753Smm#include <unistd.h>
77228753Smm#endif
78228753Smm#ifdef HAVE_TIME_H
79228753Smm#include <time.h>
80228753Smm#endif
81228753Smm
82228753Smm#include "cpio.h"
83228753Smm#include "err.h"
84228753Smm#include "line_reader.h"
85228753Smm
86228753Smm/* Fixed size of uname/gname caches. */
87228753Smm#define	name_cache_size 101
88228753Smm
89228753Smm#ifndef O_BINARY
90228753Smm#define O_BINARY 0
91228753Smm#endif
92228753Smm
93228753Smmstruct name_cache {
94228753Smm	int	probes;
95228753Smm	int	hits;
96228753Smm	size_t	size;
97228753Smm	struct {
98228753Smm		id_t id;
99228753Smm		char *name;
100228753Smm	} cache[name_cache_size];
101228753Smm};
102228753Smm
103228753Smmstatic int	extract_data(struct archive *, struct archive *);
104228753Smmconst char *	cpio_i64toa(int64_t);
105228753Smmstatic const char *cpio_rename(const char *name);
106228753Smmstatic int	entry_to_archive(struct cpio *, struct archive_entry *);
107228753Smmstatic int	file_to_archive(struct cpio *, const char *);
108228753Smmstatic void	free_cache(struct name_cache *cache);
109228753Smmstatic void	list_item_verbose(struct cpio *, struct archive_entry *);
110228753Smmstatic void	long_help(void);
111228753Smmstatic const char *lookup_gname(struct cpio *, gid_t gid);
112228753Smmstatic int	lookup_gname_helper(struct cpio *,
113228753Smm		    const char **name, id_t gid);
114228753Smmstatic const char *lookup_uname(struct cpio *, uid_t uid);
115228753Smmstatic int	lookup_uname_helper(struct cpio *,
116228753Smm		    const char **name, id_t uid);
117228753Smmstatic void	mode_in(struct cpio *);
118228753Smmstatic void	mode_list(struct cpio *);
119228753Smmstatic void	mode_out(struct cpio *);
120228753Smmstatic void	mode_pass(struct cpio *, const char *);
121232153Smmstatic const char *remove_leading_slash(const char *);
122228753Smmstatic int	restore_time(struct cpio *, struct archive_entry *,
123228753Smm		    const char *, int fd);
124228753Smmstatic void	usage(void);
125228753Smmstatic void	version(void);
126228753Smm
127228753Smmint
128228753Smmmain(int argc, char *argv[])
129228753Smm{
130228753Smm	static char buff[16384];
131228753Smm	struct cpio _cpio; /* Allocated on stack. */
132228753Smm	struct cpio *cpio;
133228753Smm	const char *errmsg;
134228753Smm	int uid, gid;
135228753Smm	int opt;
136228753Smm
137228753Smm	cpio = &_cpio;
138228753Smm	memset(cpio, 0, sizeof(*cpio));
139228753Smm	cpio->buff = buff;
140228753Smm	cpio->buff_size = sizeof(buff);
141228753Smm
142232153Smm#if defined(HAVE_SIGACTION) && defined(SIGPIPE)
143232153Smm	{ /* Ignore SIGPIPE signals. */
144232153Smm		struct sigaction sa;
145232153Smm		sigemptyset(&sa.sa_mask);
146232153Smm		sa.sa_flags = 0;
147232153Smm		sa.sa_handler = SIG_IGN;
148232153Smm		sigaction(SIGPIPE, &sa, NULL);
149232153Smm	}
150232153Smm#endif
151232153Smm
152228753Smm	/* Need lafe_progname before calling lafe_warnc. */
153228753Smm	if (*argv == NULL)
154228753Smm		lafe_progname = "bsdcpio";
155228753Smm	else {
156228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
157228753Smm		lafe_progname = strrchr(*argv, '\\');
158232153Smm		if (strrchr(*argv, '/') > lafe_progname)
159232153Smm#endif
160228753Smm		lafe_progname = strrchr(*argv, '/');
161228753Smm		if (lafe_progname != NULL)
162228753Smm			lafe_progname++;
163228753Smm		else
164228753Smm			lafe_progname = *argv;
165228753Smm	}
166232153Smm#if HAVE_SETLOCALE
167232153Smm	if (setlocale(LC_ALL, "") == NULL)
168232153Smm		lafe_warnc(0, "Failed to set default locale");
169232153Smm#endif
170228753Smm
171228753Smm	cpio->uid_override = -1;
172228753Smm	cpio->gid_override = -1;
173228753Smm	cpio->argv = argv;
174228753Smm	cpio->argc = argc;
175228753Smm	cpio->mode = '\0';
176228753Smm	cpio->verbose = 0;
177228753Smm	cpio->compress = '\0';
178228753Smm	cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
179228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
180228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
181228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
182301046Sglebius	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
183228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
184228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
185228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
186228753Smm#if !defined(_WIN32) && !defined(__CYGWIN__)
187228753Smm	if (geteuid() == 0)
188228753Smm		cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
189228753Smm#endif
190228753Smm	cpio->bytes_per_block = 512;
191228753Smm	cpio->filename = NULL;
192228753Smm
193238856Smm	cpio->matching = archive_match_new();
194238856Smm	if (cpio->matching == NULL)
195238856Smm		lafe_errc(1, 0, "Out of memory");
196238856Smm
197228753Smm	while ((opt = cpio_getopt(cpio)) != -1) {
198228753Smm		switch (opt) {
199228753Smm		case '0': /* GNU convention: --null, -0 */
200228753Smm			cpio->option_null = 1;
201228753Smm			break;
202228753Smm		case 'A': /* NetBSD/OpenBSD */
203228753Smm			cpio->option_append = 1;
204228753Smm			break;
205228753Smm		case 'a': /* POSIX 1997 */
206228753Smm			cpio->option_atime_restore = 1;
207228753Smm			break;
208228753Smm		case 'B': /* POSIX 1997 */
209228753Smm			cpio->bytes_per_block = 5120;
210228753Smm			break;
211248616Smm		case OPTION_B64ENCODE:
212248616Smm			cpio->add_filter = opt;
213248616Smm			break;
214228753Smm		case 'C': /* NetBSD/OpenBSD */
215232153Smm			cpio->bytes_per_block = atoi(cpio->argument);
216228753Smm			if (cpio->bytes_per_block <= 0)
217232153Smm				lafe_errc(1, 0, "Invalid blocksize %s", cpio->argument);
218228753Smm			break;
219228753Smm		case 'c': /* POSIX 1997 */
220228753Smm			cpio->format = "odc";
221228753Smm			break;
222228753Smm		case 'd': /* POSIX 1997 */
223228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
224228753Smm			break;
225228753Smm		case 'E': /* NetBSD/OpenBSD */
226238856Smm			if (archive_match_include_pattern_from_file(
227238856Smm			    cpio->matching, cpio->argument,
228238856Smm			    cpio->option_null) != ARCHIVE_OK)
229238856Smm				lafe_errc(1, 0, "Error : %s",
230238856Smm				    archive_error_string(cpio->matching));
231228753Smm			break;
232228753Smm		case 'F': /* NetBSD/OpenBSD/GNU cpio */
233232153Smm			cpio->filename = cpio->argument;
234228753Smm			break;
235228753Smm		case 'f': /* POSIX 1997 */
236238856Smm			if (archive_match_exclude_pattern(cpio->matching,
237238856Smm			    cpio->argument) != ARCHIVE_OK)
238238856Smm				lafe_errc(1, 0, "Error : %s",
239238856Smm				    archive_error_string(cpio->matching));
240228753Smm			break;
241248616Smm		case OPTION_GRZIP:
242248616Smm			cpio->compress = opt;
243248616Smm			break;
244228753Smm		case 'H': /* GNU cpio (also --format) */
245232153Smm			cpio->format = cpio->argument;
246228753Smm			break;
247228753Smm		case 'h':
248228753Smm			long_help();
249228753Smm			break;
250228753Smm		case 'I': /* NetBSD/OpenBSD */
251232153Smm			cpio->filename = cpio->argument;
252228753Smm			break;
253228753Smm		case 'i': /* POSIX 1997 */
254228753Smm			if (cpio->mode != '\0')
255228753Smm				lafe_errc(1, 0,
256228753Smm				    "Cannot use both -i and -%c", cpio->mode);
257228753Smm			cpio->mode = opt;
258228753Smm			break;
259228753Smm		case 'J': /* GNU tar, others */
260228753Smm			cpio->compress = opt;
261228753Smm			break;
262228753Smm		case 'j': /* GNU tar, others */
263228753Smm			cpio->compress = opt;
264228753Smm			break;
265228753Smm		case OPTION_INSECURE:
266228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
267228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
268301046Sglebius			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
269228753Smm			break;
270228753Smm		case 'L': /* GNU cpio */
271228753Smm			cpio->option_follow_links = 1;
272228753Smm			break;
273228753Smm		case 'l': /* POSIX 1997 */
274228753Smm			cpio->option_link = 1;
275228753Smm			break;
276248616Smm		case OPTION_LRZIP:
277228753Smm		case OPTION_LZMA: /* GNU tar, others */
278248616Smm		case OPTION_LZOP: /* GNU tar, others */
279228753Smm			cpio->compress = opt;
280228753Smm			break;
281228753Smm		case 'm': /* POSIX 1997 */
282228753Smm			cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
283228753Smm			break;
284228753Smm		case 'n': /* GNU cpio */
285228753Smm			cpio->option_numeric_uid_gid = 1;
286228753Smm			break;
287228753Smm		case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
288228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
289228753Smm			break;
290228753Smm		case 'O': /* GNU cpio */
291232153Smm			cpio->filename = cpio->argument;
292228753Smm			break;
293228753Smm		case 'o': /* POSIX 1997 */
294228753Smm			if (cpio->mode != '\0')
295228753Smm				lafe_errc(1, 0,
296228753Smm				    "Cannot use both -o and -%c", cpio->mode);
297228753Smm			cpio->mode = opt;
298228753Smm			break;
299228753Smm		case 'p': /* POSIX 1997 */
300228753Smm			if (cpio->mode != '\0')
301228753Smm				lafe_errc(1, 0,
302228753Smm				    "Cannot use both -p and -%c", cpio->mode);
303228753Smm			cpio->mode = opt;
304228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
305301046Sglebius			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
306228753Smm			break;
307228753Smm		case OPTION_PRESERVE_OWNER:
308228753Smm			cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
309228753Smm			break;
310228753Smm		case OPTION_QUIET: /* GNU cpio */
311228753Smm			cpio->quiet = 1;
312228753Smm			break;
313228753Smm		case 'R': /* GNU cpio, also --owner */
314228777Smm			/* TODO: owner_parse should return uname/gname
315228777Smm			 * also; use that to set [ug]name_override. */
316232153Smm			errmsg = owner_parse(cpio->argument, &uid, &gid);
317228753Smm			if (errmsg) {
318228753Smm				lafe_warnc(-1, "%s", errmsg);
319228753Smm				usage();
320228753Smm			}
321228777Smm			if (uid != -1) {
322228753Smm				cpio->uid_override = uid;
323228777Smm				cpio->uname_override = NULL;
324228777Smm			}
325228777Smm			if (gid != -1) {
326228753Smm				cpio->gid_override = gid;
327228777Smm				cpio->gname_override = NULL;
328228777Smm			}
329228753Smm			break;
330228753Smm		case 'r': /* POSIX 1997 */
331228753Smm			cpio->option_rename = 1;
332228753Smm			break;
333228753Smm		case 't': /* POSIX 1997 */
334228753Smm			cpio->option_list = 1;
335228753Smm			break;
336228753Smm		case 'u': /* POSIX 1997 */
337228753Smm			cpio->extract_flags
338228753Smm			    &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
339228753Smm			break;
340248616Smm		case OPTION_UUENCODE:
341248616Smm			cpio->add_filter = opt;
342248616Smm			break;
343228753Smm		case 'v': /* POSIX 1997 */
344228753Smm			cpio->verbose++;
345228753Smm			break;
346232153Smm		case 'V': /* GNU cpio */
347232153Smm			cpio->dot++;
348232153Smm			break;
349228753Smm		case OPTION_VERSION: /* GNU convention */
350228753Smm			version();
351228753Smm			break;
352228753Smm#if 0
353228753Smm	        /*
354228753Smm		 * cpio_getopt() handles -W specially, so it's not
355228753Smm		 * available here.
356228753Smm		 */
357228753Smm		case 'W': /* Obscure, but useful GNU convention. */
358228753Smm			break;
359228753Smm#endif
360228753Smm		case 'y': /* tar convention */
361228753Smm			cpio->compress = opt;
362228753Smm			break;
363228753Smm		case 'Z': /* tar convention */
364228753Smm			cpio->compress = opt;
365228753Smm			break;
366228753Smm		case 'z': /* tar convention */
367228753Smm			cpio->compress = opt;
368228753Smm			break;
369228753Smm		default:
370228753Smm			usage();
371228753Smm		}
372228753Smm	}
373228753Smm
374228753Smm	/*
375228753Smm	 * Sanity-check args, error out on nonsensical combinations.
376228753Smm	 */
377228753Smm	/* -t implies -i if no mode was specified. */
378228753Smm	if (cpio->option_list && cpio->mode == '\0')
379228753Smm		cpio->mode = 'i';
380228753Smm	/* -t requires -i */
381228753Smm	if (cpio->option_list && cpio->mode != 'i')
382228753Smm		lafe_errc(1, 0, "Option -t requires -i");
383228753Smm	/* -n requires -it */
384228753Smm	if (cpio->option_numeric_uid_gid && !cpio->option_list)
385228753Smm		lafe_errc(1, 0, "Option -n requires -it");
386228753Smm	/* Can only specify format when writing */
387228753Smm	if (cpio->format != NULL && cpio->mode != 'o')
388228753Smm		lafe_errc(1, 0, "Option --format requires -o");
389228753Smm	/* -l requires -p */
390228753Smm	if (cpio->option_link && cpio->mode != 'p')
391228753Smm		lafe_errc(1, 0, "Option -l requires -p");
392232153Smm	/* -v overrides -V */
393232153Smm	if (cpio->dot && cpio->verbose)
394232153Smm		cpio->dot = 0;
395228753Smm	/* TODO: Flag other nonsensical combinations. */
396228753Smm
397228753Smm	switch (cpio->mode) {
398228753Smm	case 'o':
399228753Smm		/* TODO: Implement old binary format in libarchive,
400228753Smm		   use that here. */
401228753Smm		if (cpio->format == NULL)
402228753Smm			cpio->format = "odc"; /* Default format */
403228753Smm
404228753Smm		mode_out(cpio);
405228753Smm		break;
406228753Smm	case 'i':
407228753Smm		while (*cpio->argv != NULL) {
408238856Smm			if (archive_match_include_pattern(cpio->matching,
409238856Smm			    *cpio->argv) != ARCHIVE_OK)
410238856Smm				lafe_errc(1, 0, "Error : %s",
411238856Smm				    archive_error_string(cpio->matching));
412228753Smm			--cpio->argc;
413228753Smm			++cpio->argv;
414228753Smm		}
415228753Smm		if (cpio->option_list)
416228753Smm			mode_list(cpio);
417228753Smm		else
418228753Smm			mode_in(cpio);
419228753Smm		break;
420228753Smm	case 'p':
421228753Smm		if (*cpio->argv == NULL || **cpio->argv == '\0')
422228753Smm			lafe_errc(1, 0,
423228753Smm			    "-p mode requires a target directory");
424228753Smm		mode_pass(cpio, *cpio->argv);
425228753Smm		break;
426228753Smm	default:
427228753Smm		lafe_errc(1, 0,
428228753Smm		    "Must specify at least one of -i, -o, or -p");
429228753Smm	}
430228753Smm
431238856Smm	archive_match_free(cpio->matching);
432228753Smm	free_cache(cpio->gname_cache);
433228753Smm	free_cache(cpio->uname_cache);
434248616Smm	free(cpio->destdir);
435228753Smm	return (cpio->return_value);
436228753Smm}
437228753Smm
438228753Smmstatic void
439228753Smmusage(void)
440228753Smm{
441228753Smm	const char	*p;
442228753Smm
443228753Smm	p = lafe_progname;
444228753Smm
445228753Smm	fprintf(stderr, "Brief Usage:\n");
446228753Smm	fprintf(stderr, "  List:    %s -it < archive\n", p);
447228753Smm	fprintf(stderr, "  Extract: %s -i < archive\n", p);
448228753Smm	fprintf(stderr, "  Create:  %s -o < filenames > archive\n", p);
449228753Smm	fprintf(stderr, "  Help:    %s --help\n", p);
450228753Smm	exit(1);
451228753Smm}
452228753Smm
453228753Smmstatic const char *long_help_msg =
454228753Smm	"First option must be a mode specifier:\n"
455228753Smm	"  -i Input  -o Output  -p Pass\n"
456228753Smm	"Common Options:\n"
457232153Smm	"  -v Verbose filenames     -V  one dot per file\n"
458228753Smm	"Create: %p -o [options]  < [list of files] > [archive]\n"
459228753Smm	"  -J,-y,-z,--lzma  Compress archive with xz/bzip2/gzip/lzma\n"
460228753Smm	"  --format {odc|newc|ustar}  Select archive format\n"
461228753Smm	"List: %p -it < [archive]\n"
462228753Smm	"Extract: %p -i [options] < [archive]\n";
463228753Smm
464228753Smm
465228753Smm/*
466228753Smm * Note that the word 'bsdcpio' will always appear in the first line
467228753Smm * of output.
468228753Smm *
469228753Smm * In particular, /bin/sh scripts that need to test for the presence
470228753Smm * of bsdcpio can use the following template:
471228753Smm *
472228753Smm * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
473228753Smm *          echo bsdcpio; else echo not bsdcpio; fi
474228753Smm */
475228753Smmstatic void
476228753Smmlong_help(void)
477228753Smm{
478228753Smm	const char	*prog;
479228753Smm	const char	*p;
480228753Smm
481228753Smm	prog = lafe_progname;
482228753Smm
483228753Smm	fflush(stderr);
484228753Smm
485228753Smm	p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
486228753Smm	printf("%s%s: manipulate archive files\n", prog, p);
487228753Smm
488228753Smm	for (p = long_help_msg; *p != '\0'; p++) {
489228753Smm		if (*p == '%') {
490228753Smm			if (p[1] == 'p') {
491228753Smm				fputs(prog, stdout);
492228753Smm				p++;
493228753Smm			} else
494228753Smm				putchar('%');
495228753Smm		} else
496228753Smm			putchar(*p);
497228753Smm	}
498228753Smm	version();
499228753Smm}
500228753Smm
501228753Smmstatic void
502228753Smmversion(void)
503228753Smm{
504228753Smm	fprintf(stdout,"bsdcpio %s -- %s\n",
505228753Smm	    BSDCPIO_VERSION_STRING,
506232153Smm	    archive_version_string());
507228753Smm	exit(0);
508228753Smm}
509228753Smm
510228753Smmstatic void
511228753Smmmode_out(struct cpio *cpio)
512228753Smm{
513228753Smm	struct archive_entry *entry, *spare;
514228753Smm	struct lafe_line_reader *lr;
515228753Smm	const char *p;
516228753Smm	int r;
517228753Smm
518228753Smm	if (cpio->option_append)
519228753Smm		lafe_errc(1, 0, "Append mode not yet supported.");
520228753Smm
521228753Smm	cpio->archive_read_disk = archive_read_disk_new();
522228753Smm	if (cpio->archive_read_disk == NULL)
523228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
524228753Smm	if (cpio->option_follow_links)
525228753Smm		archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
526228753Smm	else
527228753Smm		archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
528228753Smm	archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
529228753Smm
530228753Smm	cpio->archive = archive_write_new();
531228753Smm	if (cpio->archive == NULL)
532228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
533228753Smm	switch (cpio->compress) {
534248616Smm	case OPTION_GRZIP:
535248616Smm		r = archive_write_add_filter_grzip(cpio->archive);
536248616Smm		break;
537228753Smm	case 'J':
538248616Smm		r = archive_write_add_filter_xz(cpio->archive);
539228753Smm		break;
540248616Smm	case OPTION_LRZIP:
541248616Smm		r = archive_write_add_filter_lrzip(cpio->archive);
542248616Smm		break;
543228753Smm	case OPTION_LZMA:
544248616Smm		r = archive_write_add_filter_lzma(cpio->archive);
545228753Smm		break;
546248616Smm	case OPTION_LZOP:
547248616Smm		r = archive_write_add_filter_lzop(cpio->archive);
548248616Smm		break;
549228753Smm	case 'j': case 'y':
550248616Smm		r = archive_write_add_filter_bzip2(cpio->archive);
551228753Smm		break;
552228753Smm	case 'z':
553248616Smm		r = archive_write_add_filter_gzip(cpio->archive);
554228753Smm		break;
555228753Smm	case 'Z':
556248616Smm		r = archive_write_add_filter_compress(cpio->archive);
557228753Smm		break;
558228753Smm	default:
559248616Smm		r = archive_write_add_filter_none(cpio->archive);
560228753Smm		break;
561228753Smm	}
562228753Smm	if (r < ARCHIVE_WARN)
563228753Smm		lafe_errc(1, 0, "Requested compression not available");
564248616Smm	switch (cpio->add_filter) {
565248616Smm	case 0:
566248616Smm		r = ARCHIVE_OK;
567248616Smm		break;
568248616Smm	case OPTION_B64ENCODE:
569248616Smm		r = archive_write_add_filter_b64encode(cpio->archive);
570248616Smm		break;
571248616Smm	case OPTION_UUENCODE:
572248616Smm		r = archive_write_add_filter_uuencode(cpio->archive);
573248616Smm		break;
574248616Smm	}
575248616Smm	if (r < ARCHIVE_WARN)
576248616Smm		lafe_errc(1, 0, "Requested filter not available");
577228753Smm	r = archive_write_set_format_by_name(cpio->archive, cpio->format);
578228753Smm	if (r != ARCHIVE_OK)
579228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
580228753Smm	archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
581228753Smm	cpio->linkresolver = archive_entry_linkresolver_new();
582228753Smm	archive_entry_linkresolver_set_strategy(cpio->linkresolver,
583228753Smm	    archive_format(cpio->archive));
584228753Smm
585228753Smm	/*
586228753Smm	 * The main loop:  Copy each file into the output archive.
587228753Smm	 */
588248616Smm	r = archive_write_open_filename(cpio->archive, cpio->filename);
589228753Smm	if (r != ARCHIVE_OK)
590228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
591228753Smm	lr = lafe_line_reader("-", cpio->option_null);
592228753Smm	while ((p = lafe_line_reader_next(lr)) != NULL)
593228753Smm		file_to_archive(cpio, p);
594228753Smm	lafe_line_reader_free(lr);
595228753Smm
596228753Smm	/*
597228753Smm	 * The hardlink detection may have queued up a couple of entries
598228753Smm	 * that can now be flushed.
599228753Smm	 */
600228753Smm	entry = NULL;
601228753Smm	archive_entry_linkify(cpio->linkresolver, &entry, &spare);
602228753Smm	while (entry != NULL) {
603228753Smm		entry_to_archive(cpio, entry);
604228753Smm		archive_entry_free(entry);
605228753Smm		entry = NULL;
606228753Smm		archive_entry_linkify(cpio->linkresolver, &entry, &spare);
607228753Smm	}
608228753Smm
609228753Smm	r = archive_write_close(cpio->archive);
610232153Smm	if (cpio->dot)
611232153Smm		fprintf(stderr, "\n");
612228753Smm	if (r != ARCHIVE_OK)
613228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
614228753Smm
615228753Smm	if (!cpio->quiet) {
616228753Smm		int64_t blocks =
617248616Smm			(archive_filter_bytes(cpio->archive, 0) + 511)
618228753Smm			/ 512;
619228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
620228753Smm		    blocks == 1 ? "block" : "blocks");
621228753Smm	}
622232153Smm	archive_write_free(cpio->archive);
623228753Smm}
624228753Smm
625232153Smmstatic const char *
626232153Smmremove_leading_slash(const char *p)
627232153Smm{
628232153Smm	const char *rp;
629232153Smm
630232153Smm	/* Remove leading "//./" or "//?/" or "//?/UNC/"
631232153Smm	 * (absolute path prefixes used by Windows API) */
632232153Smm	if ((p[0] == '/' || p[0] == '\\') &&
633232153Smm	    (p[1] == '/' || p[1] == '\\') &&
634232153Smm	    (p[2] == '.' || p[2] == '?') &&
635232153Smm	    (p[3] == '/' || p[3] == '\\'))
636232153Smm	{
637232153Smm		if (p[2] == '?' &&
638232153Smm		    (p[4] == 'U' || p[4] == 'u') &&
639232153Smm		    (p[5] == 'N' || p[5] == 'n') &&
640232153Smm		    (p[6] == 'C' || p[6] == 'c') &&
641232153Smm		    (p[7] == '/' || p[7] == '\\'))
642232153Smm			p += 8;
643232153Smm		else
644232153Smm			p += 4;
645232153Smm	}
646232153Smm	do {
647232153Smm		rp = p;
648232153Smm		/* Remove leading drive letter from archives created
649232153Smm		 * on Windows. */
650232153Smm		if (((p[0] >= 'a' && p[0] <= 'z') ||
651232153Smm		     (p[0] >= 'A' && p[0] <= 'Z')) &&
652232153Smm			 p[1] == ':') {
653232153Smm			p += 2;
654232153Smm		}
655232153Smm		/* Remove leading "/../", "//", etc. */
656232153Smm		while (p[0] == '/' || p[0] == '\\') {
657232153Smm			if (p[1] == '.' && p[2] == '.' &&
658232153Smm				(p[3] == '/' || p[3] == '\\')) {
659232153Smm				p += 3; /* Remove "/..", leave "/"
660232153Smm					 * for next pass. */
661232153Smm			} else
662232153Smm				p += 1; /* Remove "/". */
663232153Smm		}
664232153Smm	} while (rp != p);
665232153Smm	return (p);
666232153Smm}
667232153Smm
668228753Smm/*
669228753Smm * This is used by both out mode (to copy objects from disk into
670228753Smm * an archive) and pass mode (to copy objects from disk to
671228753Smm * an archive_write_disk "archive").
672228753Smm */
673228753Smmstatic int
674228753Smmfile_to_archive(struct cpio *cpio, const char *srcpath)
675228753Smm{
676228753Smm	const char *destpath;
677228753Smm	struct archive_entry *entry, *spare;
678228753Smm	size_t len;
679228753Smm	int r;
680228753Smm
681228753Smm	/*
682228753Smm	 * Create an archive_entry describing the source file.
683228753Smm	 *
684228753Smm	 */
685228753Smm	entry = archive_entry_new();
686228753Smm	if (entry == NULL)
687228753Smm		lafe_errc(1, 0, "Couldn't allocate entry");
688228753Smm	archive_entry_copy_sourcepath(entry, srcpath);
689228753Smm	r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
690228753Smm	    entry, -1, NULL);
691228753Smm	if (r < ARCHIVE_FAILED)
692228753Smm		lafe_errc(1, 0, "%s",
693228753Smm		    archive_error_string(cpio->archive_read_disk));
694228753Smm	if (r < ARCHIVE_OK)
695228753Smm		lafe_warnc(0, "%s",
696228753Smm		    archive_error_string(cpio->archive_read_disk));
697228753Smm	if (r <= ARCHIVE_FAILED) {
698228753Smm		cpio->return_value = 1;
699228753Smm		return (r);
700228753Smm	}
701228753Smm
702228777Smm	if (cpio->uid_override >= 0) {
703228753Smm		archive_entry_set_uid(entry, cpio->uid_override);
704228777Smm		archive_entry_set_uname(entry, cpio->uname_override);
705228777Smm	}
706228777Smm	if (cpio->gid_override >= 0) {
707228753Smm		archive_entry_set_gid(entry, cpio->gid_override);
708228777Smm		archive_entry_set_gname(entry, cpio->gname_override);
709228777Smm	}
710228753Smm
711228753Smm	/*
712228753Smm	 * Generate a destination path for this entry.
713228753Smm	 * "destination path" is the name to which it will be copied in
714228753Smm	 * pass mode or the name that will go into the archive in
715228753Smm	 * output mode.
716228753Smm	 */
717228753Smm	destpath = srcpath;
718228753Smm	if (cpio->destdir) {
719228753Smm		len = strlen(cpio->destdir) + strlen(srcpath) + 8;
720228753Smm		if (len >= cpio->pass_destpath_alloc) {
721228753Smm			while (len >= cpio->pass_destpath_alloc) {
722228753Smm				cpio->pass_destpath_alloc += 512;
723228753Smm				cpio->pass_destpath_alloc *= 2;
724228753Smm			}
725228753Smm			free(cpio->pass_destpath);
726228753Smm			cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
727228753Smm			if (cpio->pass_destpath == NULL)
728228753Smm				lafe_errc(1, ENOMEM,
729228753Smm				    "Can't allocate path buffer");
730228753Smm		}
731228753Smm		strcpy(cpio->pass_destpath, cpio->destdir);
732232153Smm		strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
733228753Smm		destpath = cpio->pass_destpath;
734228753Smm	}
735228753Smm	if (cpio->option_rename)
736228753Smm		destpath = cpio_rename(destpath);
737228753Smm	if (destpath == NULL)
738228753Smm		return (0);
739228753Smm	archive_entry_copy_pathname(entry, destpath);
740228753Smm
741228753Smm	/*
742228753Smm	 * If we're trying to preserve hardlinks, match them here.
743228753Smm	 */
744228753Smm	spare = NULL;
745228753Smm	if (cpio->linkresolver != NULL
746228753Smm	    && archive_entry_filetype(entry) != AE_IFDIR) {
747228753Smm		archive_entry_linkify(cpio->linkresolver, &entry, &spare);
748228753Smm	}
749228753Smm
750228753Smm	if (entry != NULL) {
751228753Smm		r = entry_to_archive(cpio, entry);
752228753Smm		archive_entry_free(entry);
753228753Smm		if (spare != NULL) {
754228753Smm			if (r == 0)
755228753Smm				r = entry_to_archive(cpio, spare);
756228753Smm			archive_entry_free(spare);
757228753Smm		}
758228753Smm	}
759228753Smm	return (r);
760228753Smm}
761228753Smm
762228753Smmstatic int
763228753Smmentry_to_archive(struct cpio *cpio, struct archive_entry *entry)
764228753Smm{
765228753Smm	const char *destpath = archive_entry_pathname(entry);
766228753Smm	const char *srcpath = archive_entry_sourcepath(entry);
767228753Smm	int fd = -1;
768228753Smm	ssize_t bytes_read;
769228753Smm	int r;
770228753Smm
771228753Smm	/* Print out the destination name to the user. */
772228753Smm	if (cpio->verbose)
773228753Smm		fprintf(stderr,"%s", destpath);
774232153Smm	if (cpio->dot)
775232153Smm		fprintf(stderr, ".");
776228753Smm
777228753Smm	/*
778228753Smm	 * Option_link only makes sense in pass mode and for
779228753Smm	 * regular files.  Also note: if a link operation fails
780228753Smm	 * because of cross-device restrictions, we'll fall back
781228753Smm	 * to copy mode for that entry.
782228753Smm	 *
783228753Smm	 * TODO: Test other cpio implementations to see if they
784228753Smm	 * hard-link anything other than regular files here.
785228753Smm	 */
786228753Smm	if (cpio->option_link
787228753Smm	    && archive_entry_filetype(entry) == AE_IFREG)
788228753Smm	{
789228753Smm		struct archive_entry *t;
790228753Smm		/* Save the original entry in case we need it later. */
791228753Smm		t = archive_entry_clone(entry);
792228753Smm		if (t == NULL)
793228753Smm			lafe_errc(1, ENOMEM, "Can't create link");
794228753Smm		/* Note: link(2) doesn't create parent directories,
795228753Smm		 * so we use archive_write_header() instead as a
796228753Smm		 * convenience. */
797228753Smm		archive_entry_set_hardlink(t, srcpath);
798228753Smm		/* This is a straight link that carries no data. */
799228753Smm		archive_entry_set_size(t, 0);
800228753Smm		r = archive_write_header(cpio->archive, t);
801228753Smm		archive_entry_free(t);
802228753Smm		if (r != ARCHIVE_OK)
803228753Smm			lafe_warnc(archive_errno(cpio->archive),
804228753Smm			    "%s", archive_error_string(cpio->archive));
805228753Smm		if (r == ARCHIVE_FATAL)
806228753Smm			exit(1);
807228753Smm#ifdef EXDEV
808228753Smm		if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
809228753Smm			/* Cross-device link:  Just fall through and use
810228753Smm			 * the original entry to copy the file over. */
811228753Smm			lafe_warnc(0, "Copying file instead");
812228753Smm		} else
813228753Smm#endif
814228753Smm		return (0);
815228753Smm	}
816228753Smm
817228753Smm	/*
818228753Smm	 * Make sure we can open the file (if necessary) before
819228753Smm	 * trying to write the header.
820228753Smm	 */
821228753Smm	if (archive_entry_filetype(entry) == AE_IFREG) {
822228753Smm		if (archive_entry_size(entry) > 0) {
823228753Smm			fd = open(srcpath, O_RDONLY | O_BINARY);
824228753Smm			if (fd < 0) {
825228753Smm				lafe_warnc(errno,
826228753Smm				    "%s: could not open file", srcpath);
827228753Smm				goto cleanup;
828228753Smm			}
829228753Smm		}
830228753Smm	} else {
831228753Smm		archive_entry_set_size(entry, 0);
832228753Smm	}
833228753Smm
834228753Smm	r = archive_write_header(cpio->archive, entry);
835228753Smm
836228753Smm	if (r != ARCHIVE_OK)
837228753Smm		lafe_warnc(archive_errno(cpio->archive),
838228753Smm		    "%s: %s",
839228753Smm		    srcpath,
840228753Smm		    archive_error_string(cpio->archive));
841228753Smm
842228753Smm	if (r == ARCHIVE_FATAL)
843228753Smm		exit(1);
844228753Smm
845232153Smm	if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
846248616Smm		bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size);
847228753Smm		while (bytes_read > 0) {
848248616Smm			ssize_t bytes_write;
849248616Smm			bytes_write = archive_write_data(cpio->archive,
850228753Smm			    cpio->buff, bytes_read);
851248616Smm			if (bytes_write < 0)
852228753Smm				lafe_errc(1, archive_errno(cpio->archive),
853228753Smm				    "%s", archive_error_string(cpio->archive));
854248616Smm			if (bytes_write < bytes_read) {
855228753Smm				lafe_warnc(0,
856248616Smm				    "Truncated write; file may have "
857248616Smm				    "grown while being archived.");
858228753Smm			}
859248616Smm			bytes_read = read(fd, cpio->buff,
860248616Smm			    (unsigned)cpio->buff_size);
861228753Smm		}
862228753Smm	}
863228753Smm
864228753Smm	fd = restore_time(cpio, entry, srcpath, fd);
865228753Smm
866228753Smmcleanup:
867228753Smm	if (cpio->verbose)
868228753Smm		fprintf(stderr,"\n");
869228753Smm	if (fd >= 0)
870228753Smm		close(fd);
871228753Smm	return (0);
872228753Smm}
873228753Smm
874228753Smmstatic int
875228753Smmrestore_time(struct cpio *cpio, struct archive_entry *entry,
876228753Smm    const char *name, int fd)
877228753Smm{
878228753Smm#ifndef HAVE_UTIMES
879228753Smm	static int warned = 0;
880228753Smm
881228753Smm	(void)cpio; /* UNUSED */
882228753Smm	(void)entry; /* UNUSED */
883228753Smm	(void)name; /* UNUSED */
884228753Smm
885228753Smm	if (!warned)
886228753Smm		lafe_warnc(0, "Can't restore access times on this platform");
887228753Smm	warned = 1;
888228753Smm	return (fd);
889228753Smm#else
890228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
891228753Smm	struct __timeval times[2];
892228753Smm#else
893228753Smm	struct timeval times[2];
894228753Smm#endif
895228753Smm
896228753Smm	if (!cpio->option_atime_restore)
897228753Smm		return (fd);
898228753Smm
899228753Smm        times[1].tv_sec = archive_entry_mtime(entry);
900228753Smm        times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
901228753Smm
902228753Smm        times[0].tv_sec = archive_entry_atime(entry);
903228753Smm        times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
904228753Smm
905228753Smm#if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
906228753Smm        if (fd >= 0 && futimes(fd, times) == 0)
907228753Smm		return (fd);
908228753Smm#endif
909228753Smm	/*
910228753Smm	 * Some platform cannot restore access times if the file descriptor
911228753Smm	 * is still opened.
912228753Smm	 */
913228753Smm	if (fd >= 0) {
914228753Smm		close(fd);
915228753Smm		fd = -1;
916228753Smm	}
917228753Smm
918228753Smm#ifdef HAVE_LUTIMES
919228753Smm        if (lutimes(name, times) != 0)
920228753Smm#else
921228753Smm        if ((AE_IFLNK != archive_entry_filetype(entry))
922228753Smm			&& utimes(name, times) != 0)
923228753Smm#endif
924228753Smm                lafe_warnc(errno, "Can't update time for %s", name);
925228753Smm#endif
926228753Smm	return (fd);
927228753Smm}
928228753Smm
929228753Smm
930228753Smmstatic void
931228753Smmmode_in(struct cpio *cpio)
932228753Smm{
933228753Smm	struct archive *a;
934228753Smm	struct archive_entry *entry;
935228753Smm	struct archive *ext;
936228753Smm	const char *destpath;
937228753Smm	int r;
938228753Smm
939228753Smm	ext = archive_write_disk_new();
940228753Smm	if (ext == NULL)
941228753Smm		lafe_errc(1, 0, "Couldn't allocate restore object");
942228753Smm	r = archive_write_disk_set_options(ext, cpio->extract_flags);
943228753Smm	if (r != ARCHIVE_OK)
944228753Smm		lafe_errc(1, 0, "%s", archive_error_string(ext));
945228753Smm	a = archive_read_new();
946228753Smm	if (a == NULL)
947228753Smm		lafe_errc(1, 0, "Couldn't allocate archive object");
948232153Smm	archive_read_support_filter_all(a);
949228753Smm	archive_read_support_format_all(a);
950228753Smm
951248616Smm	if (archive_read_open_filename(a, cpio->filename,
952248616Smm					cpio->bytes_per_block))
953228753Smm		lafe_errc(1, archive_errno(a),
954228753Smm		    "%s", archive_error_string(a));
955228753Smm	for (;;) {
956228753Smm		r = archive_read_next_header(a, &entry);
957228753Smm		if (r == ARCHIVE_EOF)
958228753Smm			break;
959228753Smm		if (r != ARCHIVE_OK) {
960228753Smm			lafe_errc(1, archive_errno(a),
961228753Smm			    "%s", archive_error_string(a));
962228753Smm		}
963238856Smm		if (archive_match_path_excluded(cpio->matching, entry))
964228753Smm			continue;
965228753Smm		if (cpio->option_rename) {
966228753Smm			destpath = cpio_rename(archive_entry_pathname(entry));
967228753Smm			archive_entry_set_pathname(entry, destpath);
968228753Smm		} else
969228753Smm			destpath = archive_entry_pathname(entry);
970228753Smm		if (destpath == NULL)
971228753Smm			continue;
972228753Smm		if (cpio->verbose)
973232153Smm			fprintf(stderr, "%s\n", destpath);
974232153Smm		if (cpio->dot)
975232153Smm			fprintf(stderr, ".");
976228753Smm		if (cpio->uid_override >= 0)
977228753Smm			archive_entry_set_uid(entry, cpio->uid_override);
978228753Smm		if (cpio->gid_override >= 0)
979228753Smm			archive_entry_set_gid(entry, cpio->gid_override);
980228753Smm		r = archive_write_header(ext, entry);
981228753Smm		if (r != ARCHIVE_OK) {
982228753Smm			fprintf(stderr, "%s: %s\n",
983228753Smm			    archive_entry_pathname(entry),
984228753Smm			    archive_error_string(ext));
985232153Smm		} else if (!archive_entry_size_is_set(entry)
986232153Smm		    || archive_entry_size(entry) > 0) {
987228753Smm			r = extract_data(a, ext);
988228753Smm			if (r != ARCHIVE_OK)
989228753Smm				cpio->return_value = 1;
990228753Smm		}
991228753Smm	}
992228753Smm	r = archive_read_close(a);
993232153Smm	if (cpio->dot)
994232153Smm		fprintf(stderr, "\n");
995228753Smm	if (r != ARCHIVE_OK)
996228753Smm		lafe_errc(1, 0, "%s", archive_error_string(a));
997228753Smm	r = archive_write_close(ext);
998228753Smm	if (r != ARCHIVE_OK)
999228753Smm		lafe_errc(1, 0, "%s", archive_error_string(ext));
1000228753Smm	if (!cpio->quiet) {
1001248616Smm		int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1002228753Smm			      / 512;
1003228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1004228753Smm		    blocks == 1 ? "block" : "blocks");
1005228753Smm	}
1006232153Smm	archive_read_free(a);
1007232153Smm	archive_write_free(ext);
1008228753Smm	exit(cpio->return_value);
1009228753Smm}
1010228753Smm
1011228753Smm/*
1012228753Smm * Exits if there's a fatal error.  Returns ARCHIVE_OK
1013228753Smm * if everything is kosher.
1014228753Smm */
1015228753Smmstatic int
1016228753Smmextract_data(struct archive *ar, struct archive *aw)
1017228753Smm{
1018228753Smm	int r;
1019228753Smm	size_t size;
1020228753Smm	const void *block;
1021232153Smm	int64_t offset;
1022228753Smm
1023228753Smm	for (;;) {
1024228753Smm		r = archive_read_data_block(ar, &block, &size, &offset);
1025228753Smm		if (r == ARCHIVE_EOF)
1026228753Smm			return (ARCHIVE_OK);
1027228753Smm		if (r != ARCHIVE_OK) {
1028228753Smm			lafe_warnc(archive_errno(ar),
1029228753Smm			    "%s", archive_error_string(ar));
1030228753Smm			exit(1);
1031228753Smm		}
1032248616Smm		r = (int)archive_write_data_block(aw, block, size, offset);
1033228753Smm		if (r != ARCHIVE_OK) {
1034228753Smm			lafe_warnc(archive_errno(aw),
1035228753Smm			    "%s", archive_error_string(aw));
1036228753Smm			return (r);
1037228753Smm		}
1038228753Smm	}
1039228753Smm}
1040228753Smm
1041228753Smmstatic void
1042228753Smmmode_list(struct cpio *cpio)
1043228753Smm{
1044228753Smm	struct archive *a;
1045228753Smm	struct archive_entry *entry;
1046228753Smm	int r;
1047228753Smm
1048228753Smm	a = archive_read_new();
1049228753Smm	if (a == NULL)
1050228753Smm		lafe_errc(1, 0, "Couldn't allocate archive object");
1051232153Smm	archive_read_support_filter_all(a);
1052228753Smm	archive_read_support_format_all(a);
1053228753Smm
1054248616Smm	if (archive_read_open_filename(a, cpio->filename,
1055248616Smm					cpio->bytes_per_block))
1056228753Smm		lafe_errc(1, archive_errno(a),
1057228753Smm		    "%s", archive_error_string(a));
1058228753Smm	for (;;) {
1059228753Smm		r = archive_read_next_header(a, &entry);
1060228753Smm		if (r == ARCHIVE_EOF)
1061228753Smm			break;
1062228753Smm		if (r != ARCHIVE_OK) {
1063228753Smm			lafe_errc(1, archive_errno(a),
1064228753Smm			    "%s", archive_error_string(a));
1065228753Smm		}
1066238856Smm		if (archive_match_path_excluded(cpio->matching, entry))
1067228753Smm			continue;
1068228753Smm		if (cpio->verbose)
1069228753Smm			list_item_verbose(cpio, entry);
1070228753Smm		else
1071228753Smm			fprintf(stdout, "%s\n", archive_entry_pathname(entry));
1072228753Smm	}
1073228753Smm	r = archive_read_close(a);
1074228753Smm	if (r != ARCHIVE_OK)
1075228753Smm		lafe_errc(1, 0, "%s", archive_error_string(a));
1076228753Smm	if (!cpio->quiet) {
1077248616Smm		int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1078228753Smm			      / 512;
1079228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1080228753Smm		    blocks == 1 ? "block" : "blocks");
1081228753Smm	}
1082232153Smm	archive_read_free(a);
1083228753Smm	exit(0);
1084228753Smm}
1085228753Smm
1086228753Smm/*
1087228753Smm * Display information about the current file.
1088228753Smm *
1089228753Smm * The format here roughly duplicates the output of 'ls -l'.
1090228753Smm * This is based on SUSv2, where 'tar tv' is documented as
1091228753Smm * listing additional information in an "unspecified format,"
1092228753Smm * and 'pax -l' is documented as using the same format as 'ls -l'.
1093228753Smm */
1094228753Smmstatic void
1095228753Smmlist_item_verbose(struct cpio *cpio, struct archive_entry *entry)
1096228753Smm{
1097228753Smm	char			 size[32];
1098228753Smm	char			 date[32];
1099228753Smm	char			 uids[16], gids[16];
1100228753Smm	const char 		*uname, *gname;
1101228753Smm	FILE			*out = stdout;
1102228753Smm	const char		*fmt;
1103228753Smm	time_t			 mtime;
1104228753Smm	static time_t		 now;
1105228753Smm
1106228753Smm	if (!now)
1107228753Smm		time(&now);
1108228753Smm
1109228753Smm	if (cpio->option_numeric_uid_gid) {
1110228753Smm		/* Format numeric uid/gid for display. */
1111228753Smm		strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
1112228753Smm		uname = uids;
1113228753Smm		strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
1114228753Smm		gname = gids;
1115228753Smm	} else {
1116228753Smm		/* Use uname if it's present, else lookup name from uid. */
1117228753Smm		uname = archive_entry_uname(entry);
1118228753Smm		if (uname == NULL)
1119232153Smm			uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
1120228753Smm		/* Use gname if it's present, else lookup name from gid. */
1121228753Smm		gname = archive_entry_gname(entry);
1122228753Smm		if (gname == NULL)
1123232153Smm			gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
1124228753Smm	}
1125228753Smm
1126228753Smm	/* Print device number or file size. */
1127228753Smm	if (archive_entry_filetype(entry) == AE_IFCHR
1128228753Smm	    || archive_entry_filetype(entry) == AE_IFBLK) {
1129228753Smm		snprintf(size, sizeof(size), "%lu,%lu",
1130228753Smm		    (unsigned long)archive_entry_rdevmajor(entry),
1131228753Smm		    (unsigned long)archive_entry_rdevminor(entry));
1132228753Smm	} else {
1133228753Smm		strcpy(size, cpio_i64toa(archive_entry_size(entry)));
1134228753Smm	}
1135228753Smm
1136228753Smm	/* Format the time using 'ls -l' conventions. */
1137228753Smm	mtime = archive_entry_mtime(entry);
1138228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1139228753Smm	/* Windows' strftime function does not support %e format. */
1140228753Smm	if (mtime - now > 365*86400/2
1141228753Smm		|| mtime - now < -365*86400/2)
1142228753Smm		fmt = cpio->day_first ? "%d %b  %Y" : "%b %d  %Y";
1143228753Smm	else
1144228753Smm		fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
1145228753Smm#else
1146228753Smm	if (abs(mtime - now) > (365/2)*86400)
1147228753Smm		fmt = cpio->day_first ? "%e %b  %Y" : "%b %e  %Y";
1148228753Smm	else
1149228753Smm		fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
1150228753Smm#endif
1151228753Smm	strftime(date, sizeof(date), fmt, localtime(&mtime));
1152228753Smm
1153228753Smm	fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
1154228753Smm	    archive_entry_strmode(entry),
1155228753Smm	    archive_entry_nlink(entry),
1156228753Smm	    uname, gname, size, date,
1157228753Smm	    archive_entry_pathname(entry));
1158228753Smm
1159228753Smm	/* Extra information for links. */
1160228753Smm	if (archive_entry_hardlink(entry)) /* Hard link */
1161228753Smm		fprintf(out, " link to %s", archive_entry_hardlink(entry));
1162228753Smm	else if (archive_entry_symlink(entry)) /* Symbolic link */
1163228753Smm		fprintf(out, " -> %s", archive_entry_symlink(entry));
1164228753Smm	fprintf(out, "\n");
1165228753Smm}
1166228753Smm
1167228753Smmstatic void
1168228753Smmmode_pass(struct cpio *cpio, const char *destdir)
1169228753Smm{
1170228753Smm	struct lafe_line_reader *lr;
1171228753Smm	const char *p;
1172228753Smm	int r;
1173228753Smm
1174228753Smm	/* Ensure target dir has a trailing '/' to simplify path surgery. */
1175228753Smm	cpio->destdir = malloc(strlen(destdir) + 8);
1176228753Smm	strcpy(cpio->destdir, destdir);
1177228753Smm	if (destdir[strlen(destdir) - 1] != '/')
1178228753Smm		strcat(cpio->destdir, "/");
1179228753Smm
1180228753Smm	cpio->archive = archive_write_disk_new();
1181228753Smm	if (cpio->archive == NULL)
1182228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
1183228753Smm	r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
1184228753Smm	if (r != ARCHIVE_OK)
1185228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1186228753Smm	cpio->linkresolver = archive_entry_linkresolver_new();
1187228753Smm	archive_write_disk_set_standard_lookup(cpio->archive);
1188228753Smm
1189228753Smm	cpio->archive_read_disk = archive_read_disk_new();
1190228753Smm	if (cpio->archive_read_disk == NULL)
1191228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
1192228753Smm	if (cpio->option_follow_links)
1193228753Smm		archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
1194228753Smm	else
1195228753Smm		archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
1196228753Smm	archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
1197228753Smm
1198228753Smm	lr = lafe_line_reader("-", cpio->option_null);
1199228753Smm	while ((p = lafe_line_reader_next(lr)) != NULL)
1200228753Smm		file_to_archive(cpio, p);
1201228753Smm	lafe_line_reader_free(lr);
1202228753Smm
1203228753Smm	archive_entry_linkresolver_free(cpio->linkresolver);
1204228753Smm	r = archive_write_close(cpio->archive);
1205232153Smm	if (cpio->dot)
1206232153Smm		fprintf(stderr, "\n");
1207228753Smm	if (r != ARCHIVE_OK)
1208228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1209228753Smm
1210228753Smm	if (!cpio->quiet) {
1211228753Smm		int64_t blocks =
1212248616Smm			(archive_filter_bytes(cpio->archive, 0) + 511)
1213228753Smm			/ 512;
1214228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1215228753Smm		    blocks == 1 ? "block" : "blocks");
1216228753Smm	}
1217228753Smm
1218232153Smm	archive_write_free(cpio->archive);
1219228753Smm}
1220228753Smm
1221228753Smm/*
1222228753Smm * Prompt for a new name for this entry.  Returns a pointer to the
1223228753Smm * new name or NULL if the entry should not be copied.  This
1224228753Smm * implements the semantics defined in POSIX.1-1996, which specifies
1225228753Smm * that an input of '.' means the name should be unchanged.  GNU cpio
1226228753Smm * treats '.' as a literal new name.
1227228753Smm */
1228228753Smmstatic const char *
1229228753Smmcpio_rename(const char *name)
1230228753Smm{
1231228753Smm	static char buff[1024];
1232228753Smm	FILE *t;
1233228753Smm	char *p, *ret;
1234232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1235232153Smm	FILE *to;
1236228753Smm
1237232153Smm	t = fopen("CONIN$", "r");
1238232153Smm	if (t == NULL)
1239232153Smm		return (name);
1240232153Smm	to = fopen("CONOUT$", "w");
1241232153Smm	if (to == NULL)
1242232153Smm		return (name);
1243232153Smm	fprintf(to, "%s (Enter/./(new name))? ", name);
1244232153Smm	fclose(to);
1245232153Smm#else
1246228753Smm	t = fopen("/dev/tty", "r+");
1247228753Smm	if (t == NULL)
1248228753Smm		return (name);
1249228753Smm	fprintf(t, "%s (Enter/./(new name))? ", name);
1250228753Smm	fflush(t);
1251232153Smm#endif
1252228753Smm
1253228753Smm	p = fgets(buff, sizeof(buff), t);
1254228753Smm	fclose(t);
1255228753Smm	if (p == NULL)
1256228753Smm		/* End-of-file is a blank line. */
1257228753Smm		return (NULL);
1258228753Smm
1259228753Smm	while (*p == ' ' || *p == '\t')
1260228753Smm		++p;
1261228753Smm	if (*p == '\n' || *p == '\0')
1262228753Smm		/* Empty line. */
1263228753Smm		return (NULL);
1264228753Smm	if (*p == '.' && p[1] == '\n')
1265228753Smm		/* Single period preserves original name. */
1266228753Smm		return (name);
1267228753Smm	ret = p;
1268228753Smm	/* Trim the final newline. */
1269228753Smm	while (*p != '\0' && *p != '\n')
1270228753Smm		++p;
1271228753Smm	/* Overwrite the final \n with a null character. */
1272228753Smm	*p = '\0';
1273228753Smm	return (ret);
1274228753Smm}
1275228753Smm
1276228753Smmstatic void
1277228753Smmfree_cache(struct name_cache *cache)
1278228753Smm{
1279228753Smm	size_t i;
1280228753Smm
1281228753Smm	if (cache != NULL) {
1282228753Smm		for (i = 0; i < cache->size; i++)
1283228753Smm			free(cache->cache[i].name);
1284228753Smm		free(cache);
1285228753Smm	}
1286228753Smm}
1287228753Smm
1288228753Smm/*
1289228753Smm * Lookup uname/gname from uid/gid, return NULL if no match.
1290228753Smm */
1291228753Smmstatic const char *
1292228753Smmlookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
1293228753Smm    int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
1294228753Smm{
1295228753Smm	char asnum[16];
1296228753Smm	struct name_cache	*cache;
1297228753Smm	const char *name;
1298228753Smm	int slot;
1299228753Smm
1300228753Smm
1301228753Smm	if (*name_cache_variable == NULL) {
1302228753Smm		*name_cache_variable = malloc(sizeof(struct name_cache));
1303228753Smm		if (*name_cache_variable == NULL)
1304228753Smm			lafe_errc(1, ENOMEM, "No more memory");
1305228753Smm		memset(*name_cache_variable, 0, sizeof(struct name_cache));
1306228753Smm		(*name_cache_variable)->size = name_cache_size;
1307228753Smm	}
1308228753Smm
1309228753Smm	cache = *name_cache_variable;
1310228753Smm	cache->probes++;
1311228753Smm
1312228753Smm	slot = id % cache->size;
1313228753Smm	if (cache->cache[slot].name != NULL) {
1314228753Smm		if (cache->cache[slot].id == id) {
1315228753Smm			cache->hits++;
1316228753Smm			return (cache->cache[slot].name);
1317228753Smm		}
1318228753Smm		free(cache->cache[slot].name);
1319228753Smm		cache->cache[slot].name = NULL;
1320228753Smm	}
1321228753Smm
1322228753Smm	if (lookup_fn(cpio, &name, id) == 0) {
1323228753Smm		if (name == NULL || name[0] == '\0') {
1324228753Smm			/* If lookup failed, format it as a number. */
1325228753Smm			snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
1326228753Smm			name = asnum;
1327228753Smm		}
1328228753Smm		cache->cache[slot].name = strdup(name);
1329228753Smm		if (cache->cache[slot].name != NULL) {
1330228753Smm			cache->cache[slot].id = id;
1331228753Smm			return (cache->cache[slot].name);
1332228753Smm		}
1333228753Smm		/*
1334228753Smm		 * Conveniently, NULL marks an empty slot, so
1335228753Smm		 * if the strdup() fails, we've just failed to
1336228753Smm		 * cache it.  No recovery necessary.
1337228753Smm		 */
1338228753Smm	}
1339228753Smm	return (NULL);
1340228753Smm}
1341228753Smm
1342228753Smmstatic const char *
1343228753Smmlookup_uname(struct cpio *cpio, uid_t uid)
1344228753Smm{
1345228753Smm	return (lookup_name(cpio, &cpio->uname_cache,
1346228753Smm		    &lookup_uname_helper, (id_t)uid));
1347228753Smm}
1348228753Smm
1349228753Smmstatic int
1350228753Smmlookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
1351228753Smm{
1352228753Smm	struct passwd	*pwent;
1353228753Smm
1354228753Smm	(void)cpio; /* UNUSED */
1355228753Smm
1356228753Smm	errno = 0;
1357228753Smm	pwent = getpwuid((uid_t)id);
1358228753Smm	if (pwent == NULL) {
1359228753Smm		*name = NULL;
1360228753Smm		if (errno != 0 && errno != ENOENT)
1361238856Smm			lafe_warnc(errno, "getpwuid(%s) failed",
1362238856Smm			    cpio_i64toa((int64_t)id));
1363228753Smm		return (errno);
1364228753Smm	}
1365228753Smm
1366228753Smm	*name = pwent->pw_name;
1367228753Smm	return (0);
1368228753Smm}
1369228753Smm
1370228753Smmstatic const char *
1371228753Smmlookup_gname(struct cpio *cpio, gid_t gid)
1372228753Smm{
1373228753Smm	return (lookup_name(cpio, &cpio->gname_cache,
1374228753Smm		    &lookup_gname_helper, (id_t)gid));
1375228753Smm}
1376228753Smm
1377228753Smmstatic int
1378228753Smmlookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
1379228753Smm{
1380228753Smm	struct group	*grent;
1381228753Smm
1382228753Smm	(void)cpio; /* UNUSED */
1383228753Smm
1384228753Smm	errno = 0;
1385228753Smm	grent = getgrgid((gid_t)id);
1386228753Smm	if (grent == NULL) {
1387228753Smm		*name = NULL;
1388228753Smm		if (errno != 0)
1389238856Smm			lafe_warnc(errno, "getgrgid(%s) failed",
1390238856Smm			    cpio_i64toa((int64_t)id));
1391228753Smm		return (errno);
1392228753Smm	}
1393228753Smm
1394228753Smm	*name = grent->gr_name;
1395228753Smm	return (0);
1396228753Smm}
1397228753Smm
1398228753Smm/*
1399228753Smm * It would be nice to just use printf() for formatting large numbers,
1400228753Smm * but the compatibility problems are a big headache.  Hence the
1401228753Smm * following simple utility function.
1402228753Smm */
1403228753Smmconst char *
1404228753Smmcpio_i64toa(int64_t n0)
1405228753Smm{
1406232153Smm	/* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
1407232153Smm	 * We also need 1 byte for '-' and 1 for '\0'.
1408232153Smm	 */
1409228753Smm	static char buff[22];
1410228753Smm	int64_t n = n0 < 0 ? -n0 : n0;
1411228753Smm	char *p = buff + sizeof(buff);
1412228753Smm
1413228753Smm	*--p = '\0';
1414228753Smm	do {
1415228753Smm		*--p = '0' + (int)(n % 10);
1416228753Smm		n /= 10;
1417228753Smm	} while (n > 0);
1418228753Smm	if (n0 < 0)
1419228753Smm		*--p = '-';
1420228753Smm	return p;
1421228753Smm}
1422