cpio.c revision 337351
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: stable/11/contrib/libarchive/cpio/cpio.c 337351 2018-08-05 14:35:30Z mm $");
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"
85299529Smm#include "passphrase.h"
86228753Smm
87228753Smm/* Fixed size of uname/gname caches. */
88228753Smm#define	name_cache_size 101
89228753Smm
90228753Smm#ifndef O_BINARY
91228753Smm#define O_BINARY 0
92228753Smm#endif
93228753Smm
94228753Smmstruct name_cache {
95228753Smm	int	probes;
96228753Smm	int	hits;
97228753Smm	size_t	size;
98228753Smm	struct {
99228753Smm		id_t id;
100228753Smm		char *name;
101228753Smm	} cache[name_cache_size];
102228753Smm};
103228753Smm
104228753Smmstatic int	extract_data(struct archive *, struct archive *);
105228753Smmconst char *	cpio_i64toa(int64_t);
106228753Smmstatic const char *cpio_rename(const char *name);
107228753Smmstatic int	entry_to_archive(struct cpio *, struct archive_entry *);
108228753Smmstatic int	file_to_archive(struct cpio *, const char *);
109228753Smmstatic void	free_cache(struct name_cache *cache);
110228753Smmstatic void	list_item_verbose(struct cpio *, struct archive_entry *);
111315432Smmstatic void	long_help(void) __LA_DEAD;
112228753Smmstatic const char *lookup_gname(struct cpio *, gid_t gid);
113228753Smmstatic int	lookup_gname_helper(struct cpio *,
114228753Smm		    const char **name, id_t gid);
115228753Smmstatic const char *lookup_uname(struct cpio *, uid_t uid);
116228753Smmstatic int	lookup_uname_helper(struct cpio *,
117228753Smm		    const char **name, id_t uid);
118315432Smmstatic void	mode_in(struct cpio *) __LA_DEAD;
119315432Smmstatic void	mode_list(struct cpio *) __LA_DEAD;
120228753Smmstatic void	mode_out(struct cpio *);
121228753Smmstatic void	mode_pass(struct cpio *, const char *);
122232153Smmstatic const char *remove_leading_slash(const char *);
123228753Smmstatic int	restore_time(struct cpio *, struct archive_entry *,
124228753Smm		    const char *, int fd);
125315432Smmstatic void	usage(void) __LA_DEAD;
126315432Smmstatic void	version(void) __LA_DEAD;
127299529Smmstatic const char * passphrase_callback(struct archive *, void *);
128299529Smmstatic void	passphrase_free(char *);
129228753Smm
130228753Smmint
131228753Smmmain(int argc, char *argv[])
132228753Smm{
133228753Smm	static char buff[16384];
134228753Smm	struct cpio _cpio; /* Allocated on stack. */
135228753Smm	struct cpio *cpio;
136228753Smm	const char *errmsg;
137228753Smm	int uid, gid;
138228753Smm	int opt;
139228753Smm
140228753Smm	cpio = &_cpio;
141228753Smm	memset(cpio, 0, sizeof(*cpio));
142228753Smm	cpio->buff = buff;
143228753Smm	cpio->buff_size = sizeof(buff);
144228753Smm
145232153Smm#if defined(HAVE_SIGACTION) && defined(SIGPIPE)
146232153Smm	{ /* Ignore SIGPIPE signals. */
147232153Smm		struct sigaction sa;
148232153Smm		sigemptyset(&sa.sa_mask);
149232153Smm		sa.sa_flags = 0;
150232153Smm		sa.sa_handler = SIG_IGN;
151232153Smm		sigaction(SIGPIPE, &sa, NULL);
152232153Smm	}
153232153Smm#endif
154232153Smm
155299529Smm	/* Set lafe_progname before calling lafe_warnc. */
156299529Smm	lafe_setprogname(*argv, "bsdcpio");
157299529Smm
158232153Smm#if HAVE_SETLOCALE
159232153Smm	if (setlocale(LC_ALL, "") == NULL)
160232153Smm		lafe_warnc(0, "Failed to set default locale");
161232153Smm#endif
162228753Smm
163228753Smm	cpio->uid_override = -1;
164228753Smm	cpio->gid_override = -1;
165228753Smm	cpio->argv = argv;
166228753Smm	cpio->argc = argc;
167228753Smm	cpio->mode = '\0';
168228753Smm	cpio->verbose = 0;
169228753Smm	cpio->compress = '\0';
170228753Smm	cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
171228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
172228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
173228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
174299896Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
175228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
176228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
177228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
178228753Smm#if !defined(_WIN32) && !defined(__CYGWIN__)
179228753Smm	if (geteuid() == 0)
180228753Smm		cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
181228753Smm#endif
182228753Smm	cpio->bytes_per_block = 512;
183228753Smm	cpio->filename = NULL;
184228753Smm
185238856Smm	cpio->matching = archive_match_new();
186238856Smm	if (cpio->matching == NULL)
187238856Smm		lafe_errc(1, 0, "Out of memory");
188238856Smm
189228753Smm	while ((opt = cpio_getopt(cpio)) != -1) {
190228753Smm		switch (opt) {
191228753Smm		case '0': /* GNU convention: --null, -0 */
192228753Smm			cpio->option_null = 1;
193228753Smm			break;
194228753Smm		case 'A': /* NetBSD/OpenBSD */
195228753Smm			cpio->option_append = 1;
196228753Smm			break;
197228753Smm		case 'a': /* POSIX 1997 */
198228753Smm			cpio->option_atime_restore = 1;
199228753Smm			break;
200228753Smm		case 'B': /* POSIX 1997 */
201228753Smm			cpio->bytes_per_block = 5120;
202228753Smm			break;
203248616Smm		case OPTION_B64ENCODE:
204248616Smm			cpio->add_filter = opt;
205248616Smm			break;
206228753Smm		case 'C': /* NetBSD/OpenBSD */
207232153Smm			cpio->bytes_per_block = atoi(cpio->argument);
208228753Smm			if (cpio->bytes_per_block <= 0)
209232153Smm				lafe_errc(1, 0, "Invalid blocksize %s", cpio->argument);
210228753Smm			break;
211228753Smm		case 'c': /* POSIX 1997 */
212228753Smm			cpio->format = "odc";
213228753Smm			break;
214228753Smm		case 'd': /* POSIX 1997 */
215228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
216228753Smm			break;
217228753Smm		case 'E': /* NetBSD/OpenBSD */
218238856Smm			if (archive_match_include_pattern_from_file(
219238856Smm			    cpio->matching, cpio->argument,
220238856Smm			    cpio->option_null) != ARCHIVE_OK)
221238856Smm				lafe_errc(1, 0, "Error : %s",
222238856Smm				    archive_error_string(cpio->matching));
223228753Smm			break;
224228753Smm		case 'F': /* NetBSD/OpenBSD/GNU cpio */
225232153Smm			cpio->filename = cpio->argument;
226228753Smm			break;
227228753Smm		case 'f': /* POSIX 1997 */
228238856Smm			if (archive_match_exclude_pattern(cpio->matching,
229238856Smm			    cpio->argument) != ARCHIVE_OK)
230238856Smm				lafe_errc(1, 0, "Error : %s",
231238856Smm				    archive_error_string(cpio->matching));
232228753Smm			break;
233248616Smm		case OPTION_GRZIP:
234248616Smm			cpio->compress = opt;
235248616Smm			break;
236228753Smm		case 'H': /* GNU cpio (also --format) */
237232153Smm			cpio->format = cpio->argument;
238228753Smm			break;
239228753Smm		case 'h':
240228753Smm			long_help();
241228753Smm			break;
242228753Smm		case 'I': /* NetBSD/OpenBSD */
243232153Smm			cpio->filename = cpio->argument;
244228753Smm			break;
245228753Smm		case 'i': /* POSIX 1997 */
246228753Smm			if (cpio->mode != '\0')
247228753Smm				lafe_errc(1, 0,
248228753Smm				    "Cannot use both -i and -%c", cpio->mode);
249228753Smm			cpio->mode = opt;
250228753Smm			break;
251228753Smm		case 'J': /* GNU tar, others */
252228753Smm			cpio->compress = opt;
253228753Smm			break;
254228753Smm		case 'j': /* GNU tar, others */
255228753Smm			cpio->compress = opt;
256228753Smm			break;
257228753Smm		case OPTION_INSECURE:
258228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
259228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
260299896Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
261228753Smm			break;
262228753Smm		case 'L': /* GNU cpio */
263228753Smm			cpio->option_follow_links = 1;
264228753Smm			break;
265228753Smm		case 'l': /* POSIX 1997 */
266228753Smm			cpio->option_link = 1;
267228753Smm			break;
268248616Smm		case OPTION_LRZIP:
269299529Smm		case OPTION_LZ4:
270228753Smm		case OPTION_LZMA: /* GNU tar, others */
271248616Smm		case OPTION_LZOP: /* GNU tar, others */
272324417Smm		case OPTION_ZSTD:
273228753Smm			cpio->compress = opt;
274228753Smm			break;
275228753Smm		case 'm': /* POSIX 1997 */
276228753Smm			cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
277228753Smm			break;
278228753Smm		case 'n': /* GNU cpio */
279228753Smm			cpio->option_numeric_uid_gid = 1;
280228753Smm			break;
281228753Smm		case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
282228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
283228753Smm			break;
284228753Smm		case 'O': /* GNU cpio */
285232153Smm			cpio->filename = cpio->argument;
286228753Smm			break;
287228753Smm		case 'o': /* POSIX 1997 */
288228753Smm			if (cpio->mode != '\0')
289228753Smm				lafe_errc(1, 0,
290228753Smm				    "Cannot use both -o and -%c", cpio->mode);
291228753Smm			cpio->mode = opt;
292228753Smm			break;
293228753Smm		case 'p': /* POSIX 1997 */
294228753Smm			if (cpio->mode != '\0')
295228753Smm				lafe_errc(1, 0,
296228753Smm				    "Cannot use both -p and -%c", cpio->mode);
297228753Smm			cpio->mode = opt;
298228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
299299896Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
300228753Smm			break;
301299529Smm		case OPTION_PASSPHRASE:
302299529Smm			cpio->passphrase = cpio->argument;
303299529Smm			break;
304228753Smm		case OPTION_PRESERVE_OWNER:
305228753Smm			cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
306228753Smm			break;
307228753Smm		case OPTION_QUIET: /* GNU cpio */
308228753Smm			cpio->quiet = 1;
309228753Smm			break;
310228753Smm		case 'R': /* GNU cpio, also --owner */
311228777Smm			/* TODO: owner_parse should return uname/gname
312228777Smm			 * also; use that to set [ug]name_override. */
313232153Smm			errmsg = owner_parse(cpio->argument, &uid, &gid);
314228753Smm			if (errmsg) {
315228753Smm				lafe_warnc(-1, "%s", errmsg);
316228753Smm				usage();
317228753Smm			}
318228777Smm			if (uid != -1) {
319228753Smm				cpio->uid_override = uid;
320228777Smm				cpio->uname_override = NULL;
321228777Smm			}
322228777Smm			if (gid != -1) {
323228753Smm				cpio->gid_override = gid;
324228777Smm				cpio->gname_override = NULL;
325228777Smm			}
326228753Smm			break;
327228753Smm		case 'r': /* POSIX 1997 */
328228753Smm			cpio->option_rename = 1;
329228753Smm			break;
330228753Smm		case 't': /* POSIX 1997 */
331228753Smm			cpio->option_list = 1;
332228753Smm			break;
333228753Smm		case 'u': /* POSIX 1997 */
334228753Smm			cpio->extract_flags
335228753Smm			    &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
336228753Smm			break;
337248616Smm		case OPTION_UUENCODE:
338248616Smm			cpio->add_filter = opt;
339248616Smm			break;
340228753Smm		case 'v': /* POSIX 1997 */
341228753Smm			cpio->verbose++;
342228753Smm			break;
343232153Smm		case 'V': /* GNU cpio */
344232153Smm			cpio->dot++;
345232153Smm			break;
346228753Smm		case OPTION_VERSION: /* GNU convention */
347228753Smm			version();
348228753Smm			break;
349228753Smm#if 0
350228753Smm	        /*
351228753Smm		 * cpio_getopt() handles -W specially, so it's not
352228753Smm		 * available here.
353228753Smm		 */
354228753Smm		case 'W': /* Obscure, but useful GNU convention. */
355228753Smm			break;
356228753Smm#endif
357228753Smm		case 'y': /* tar convention */
358228753Smm			cpio->compress = opt;
359228753Smm			break;
360228753Smm		case 'Z': /* tar convention */
361228753Smm			cpio->compress = opt;
362228753Smm			break;
363228753Smm		case 'z': /* tar convention */
364228753Smm			cpio->compress = opt;
365228753Smm			break;
366228753Smm		default:
367228753Smm			usage();
368228753Smm		}
369228753Smm	}
370228753Smm
371228753Smm	/*
372228753Smm	 * Sanity-check args, error out on nonsensical combinations.
373228753Smm	 */
374228753Smm	/* -t implies -i if no mode was specified. */
375228753Smm	if (cpio->option_list && cpio->mode == '\0')
376228753Smm		cpio->mode = 'i';
377228753Smm	/* -t requires -i */
378228753Smm	if (cpio->option_list && cpio->mode != 'i')
379228753Smm		lafe_errc(1, 0, "Option -t requires -i");
380228753Smm	/* -n requires -it */
381228753Smm	if (cpio->option_numeric_uid_gid && !cpio->option_list)
382228753Smm		lafe_errc(1, 0, "Option -n requires -it");
383228753Smm	/* Can only specify format when writing */
384228753Smm	if (cpio->format != NULL && cpio->mode != 'o')
385228753Smm		lafe_errc(1, 0, "Option --format requires -o");
386228753Smm	/* -l requires -p */
387228753Smm	if (cpio->option_link && cpio->mode != 'p')
388228753Smm		lafe_errc(1, 0, "Option -l requires -p");
389232153Smm	/* -v overrides -V */
390232153Smm	if (cpio->dot && cpio->verbose)
391232153Smm		cpio->dot = 0;
392228753Smm	/* TODO: Flag other nonsensical combinations. */
393228753Smm
394228753Smm	switch (cpio->mode) {
395228753Smm	case 'o':
396228753Smm		/* TODO: Implement old binary format in libarchive,
397228753Smm		   use that here. */
398228753Smm		if (cpio->format == NULL)
399228753Smm			cpio->format = "odc"; /* Default format */
400228753Smm
401228753Smm		mode_out(cpio);
402228753Smm		break;
403228753Smm	case 'i':
404228753Smm		while (*cpio->argv != NULL) {
405238856Smm			if (archive_match_include_pattern(cpio->matching,
406238856Smm			    *cpio->argv) != ARCHIVE_OK)
407238856Smm				lafe_errc(1, 0, "Error : %s",
408238856Smm				    archive_error_string(cpio->matching));
409228753Smm			--cpio->argc;
410228753Smm			++cpio->argv;
411228753Smm		}
412228753Smm		if (cpio->option_list)
413228753Smm			mode_list(cpio);
414228753Smm		else
415228753Smm			mode_in(cpio);
416228753Smm		break;
417228753Smm	case 'p':
418228753Smm		if (*cpio->argv == NULL || **cpio->argv == '\0')
419228753Smm			lafe_errc(1, 0,
420228753Smm			    "-p mode requires a target directory");
421228753Smm		mode_pass(cpio, *cpio->argv);
422228753Smm		break;
423228753Smm	default:
424228753Smm		lafe_errc(1, 0,
425228753Smm		    "Must specify at least one of -i, -o, or -p");
426228753Smm	}
427228753Smm
428238856Smm	archive_match_free(cpio->matching);
429228753Smm	free_cache(cpio->gname_cache);
430228753Smm	free_cache(cpio->uname_cache);
431248616Smm	free(cpio->destdir);
432299529Smm	passphrase_free(cpio->ppbuff);
433228753Smm	return (cpio->return_value);
434228753Smm}
435228753Smm
436228753Smmstatic void
437228753Smmusage(void)
438228753Smm{
439228753Smm	const char	*p;
440228753Smm
441299529Smm	p = lafe_getprogname();
442228753Smm
443228753Smm	fprintf(stderr, "Brief Usage:\n");
444228753Smm	fprintf(stderr, "  List:    %s -it < archive\n", p);
445228753Smm	fprintf(stderr, "  Extract: %s -i < archive\n", p);
446228753Smm	fprintf(stderr, "  Create:  %s -o < filenames > archive\n", p);
447228753Smm	fprintf(stderr, "  Help:    %s --help\n", p);
448228753Smm	exit(1);
449228753Smm}
450228753Smm
451228753Smmstatic const char *long_help_msg =
452228753Smm	"First option must be a mode specifier:\n"
453228753Smm	"  -i Input  -o Output  -p Pass\n"
454228753Smm	"Common Options:\n"
455232153Smm	"  -v Verbose filenames     -V  one dot per file\n"
456228753Smm	"Create: %p -o [options]  < [list of files] > [archive]\n"
457228753Smm	"  -J,-y,-z,--lzma  Compress archive with xz/bzip2/gzip/lzma\n"
458228753Smm	"  --format {odc|newc|ustar}  Select archive format\n"
459228753Smm	"List: %p -it < [archive]\n"
460228753Smm	"Extract: %p -i [options] < [archive]\n";
461228753Smm
462228753Smm
463228753Smm/*
464228753Smm * Note that the word 'bsdcpio' will always appear in the first line
465228753Smm * of output.
466228753Smm *
467228753Smm * In particular, /bin/sh scripts that need to test for the presence
468228753Smm * of bsdcpio can use the following template:
469228753Smm *
470228753Smm * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
471228753Smm *          echo bsdcpio; else echo not bsdcpio; fi
472228753Smm */
473228753Smmstatic void
474228753Smmlong_help(void)
475228753Smm{
476228753Smm	const char	*prog;
477228753Smm	const char	*p;
478228753Smm
479299529Smm	prog = lafe_getprogname();
480228753Smm
481228753Smm	fflush(stderr);
482228753Smm
483228753Smm	p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
484228753Smm	printf("%s%s: manipulate archive files\n", prog, p);
485228753Smm
486228753Smm	for (p = long_help_msg; *p != '\0'; p++) {
487228753Smm		if (*p == '%') {
488228753Smm			if (p[1] == 'p') {
489228753Smm				fputs(prog, stdout);
490228753Smm				p++;
491228753Smm			} else
492228753Smm				putchar('%');
493228753Smm		} else
494228753Smm			putchar(*p);
495228753Smm	}
496228753Smm	version();
497228753Smm}
498228753Smm
499228753Smmstatic void
500228753Smmversion(void)
501228753Smm{
502337351Smm	fprintf(stdout,"bsdcpio %s - %s \n",
503228753Smm	    BSDCPIO_VERSION_STRING,
504299529Smm	    archive_version_details());
505228753Smm	exit(0);
506228753Smm}
507228753Smm
508228753Smmstatic void
509228753Smmmode_out(struct cpio *cpio)
510228753Smm{
511228753Smm	struct archive_entry *entry, *spare;
512228753Smm	struct lafe_line_reader *lr;
513228753Smm	const char *p;
514228753Smm	int r;
515228753Smm
516228753Smm	if (cpio->option_append)
517228753Smm		lafe_errc(1, 0, "Append mode not yet supported.");
518228753Smm
519228753Smm	cpio->archive_read_disk = archive_read_disk_new();
520228753Smm	if (cpio->archive_read_disk == NULL)
521228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
522228753Smm	if (cpio->option_follow_links)
523228753Smm		archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
524228753Smm	else
525228753Smm		archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
526228753Smm	archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
527228753Smm
528228753Smm	cpio->archive = archive_write_new();
529228753Smm	if (cpio->archive == NULL)
530228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
531228753Smm	switch (cpio->compress) {
532248616Smm	case OPTION_GRZIP:
533248616Smm		r = archive_write_add_filter_grzip(cpio->archive);
534248616Smm		break;
535228753Smm	case 'J':
536248616Smm		r = archive_write_add_filter_xz(cpio->archive);
537228753Smm		break;
538248616Smm	case OPTION_LRZIP:
539248616Smm		r = archive_write_add_filter_lrzip(cpio->archive);
540248616Smm		break;
541299529Smm	case OPTION_LZ4:
542299529Smm		r = archive_write_add_filter_lz4(cpio->archive);
543299529Smm		break;
544228753Smm	case OPTION_LZMA:
545248616Smm		r = archive_write_add_filter_lzma(cpio->archive);
546228753Smm		break;
547248616Smm	case OPTION_LZOP:
548248616Smm		r = archive_write_add_filter_lzop(cpio->archive);
549248616Smm		break;
550324417Smm	case OPTION_ZSTD:
551324417Smm		r = archive_write_add_filter_zstd(cpio->archive);
552324417Smm		break;
553228753Smm	case 'j': case 'y':
554248616Smm		r = archive_write_add_filter_bzip2(cpio->archive);
555228753Smm		break;
556228753Smm	case 'z':
557248616Smm		r = archive_write_add_filter_gzip(cpio->archive);
558228753Smm		break;
559228753Smm	case 'Z':
560248616Smm		r = archive_write_add_filter_compress(cpio->archive);
561228753Smm		break;
562228753Smm	default:
563248616Smm		r = archive_write_add_filter_none(cpio->archive);
564228753Smm		break;
565228753Smm	}
566228753Smm	if (r < ARCHIVE_WARN)
567228753Smm		lafe_errc(1, 0, "Requested compression not available");
568248616Smm	switch (cpio->add_filter) {
569248616Smm	case 0:
570248616Smm		r = ARCHIVE_OK;
571248616Smm		break;
572248616Smm	case OPTION_B64ENCODE:
573248616Smm		r = archive_write_add_filter_b64encode(cpio->archive);
574248616Smm		break;
575248616Smm	case OPTION_UUENCODE:
576248616Smm		r = archive_write_add_filter_uuencode(cpio->archive);
577248616Smm		break;
578248616Smm	}
579248616Smm	if (r < ARCHIVE_WARN)
580248616Smm		lafe_errc(1, 0, "Requested filter not available");
581228753Smm	r = archive_write_set_format_by_name(cpio->archive, cpio->format);
582228753Smm	if (r != ARCHIVE_OK)
583228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
584228753Smm	archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
585228753Smm	cpio->linkresolver = archive_entry_linkresolver_new();
586228753Smm	archive_entry_linkresolver_set_strategy(cpio->linkresolver,
587228753Smm	    archive_format(cpio->archive));
588299529Smm	if (cpio->passphrase != NULL)
589299529Smm		r = archive_write_set_passphrase(cpio->archive,
590299529Smm			cpio->passphrase);
591299529Smm	else
592299529Smm		r = archive_write_set_passphrase_callback(cpio->archive, cpio,
593299529Smm			&passphrase_callback);
594299529Smm	if (r != ARCHIVE_OK)
595299529Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
596228753Smm
597228753Smm	/*
598228753Smm	 * The main loop:  Copy each file into the output archive.
599228753Smm	 */
600248616Smm	r = archive_write_open_filename(cpio->archive, cpio->filename);
601228753Smm	if (r != ARCHIVE_OK)
602228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
603228753Smm	lr = lafe_line_reader("-", cpio->option_null);
604228753Smm	while ((p = lafe_line_reader_next(lr)) != NULL)
605228753Smm		file_to_archive(cpio, p);
606228753Smm	lafe_line_reader_free(lr);
607228753Smm
608228753Smm	/*
609228753Smm	 * The hardlink detection may have queued up a couple of entries
610228753Smm	 * that can now be flushed.
611228753Smm	 */
612228753Smm	entry = NULL;
613228753Smm	archive_entry_linkify(cpio->linkresolver, &entry, &spare);
614228753Smm	while (entry != NULL) {
615228753Smm		entry_to_archive(cpio, entry);
616228753Smm		archive_entry_free(entry);
617228753Smm		entry = NULL;
618228753Smm		archive_entry_linkify(cpio->linkresolver, &entry, &spare);
619228753Smm	}
620228753Smm
621228753Smm	r = archive_write_close(cpio->archive);
622232153Smm	if (cpio->dot)
623232153Smm		fprintf(stderr, "\n");
624228753Smm	if (r != ARCHIVE_OK)
625228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
626228753Smm
627228753Smm	if (!cpio->quiet) {
628228753Smm		int64_t blocks =
629248616Smm			(archive_filter_bytes(cpio->archive, 0) + 511)
630228753Smm			/ 512;
631228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
632228753Smm		    blocks == 1 ? "block" : "blocks");
633228753Smm	}
634232153Smm	archive_write_free(cpio->archive);
635318482Smm	archive_entry_linkresolver_free(cpio->linkresolver);
636228753Smm}
637228753Smm
638232153Smmstatic const char *
639232153Smmremove_leading_slash(const char *p)
640232153Smm{
641232153Smm	const char *rp;
642232153Smm
643232153Smm	/* Remove leading "//./" or "//?/" or "//?/UNC/"
644232153Smm	 * (absolute path prefixes used by Windows API) */
645232153Smm	if ((p[0] == '/' || p[0] == '\\') &&
646232153Smm	    (p[1] == '/' || p[1] == '\\') &&
647232153Smm	    (p[2] == '.' || p[2] == '?') &&
648232153Smm	    (p[3] == '/' || p[3] == '\\'))
649232153Smm	{
650232153Smm		if (p[2] == '?' &&
651232153Smm		    (p[4] == 'U' || p[4] == 'u') &&
652232153Smm		    (p[5] == 'N' || p[5] == 'n') &&
653232153Smm		    (p[6] == 'C' || p[6] == 'c') &&
654232153Smm		    (p[7] == '/' || p[7] == '\\'))
655232153Smm			p += 8;
656232153Smm		else
657232153Smm			p += 4;
658232153Smm	}
659232153Smm	do {
660232153Smm		rp = p;
661232153Smm		/* Remove leading drive letter from archives created
662232153Smm		 * on Windows. */
663232153Smm		if (((p[0] >= 'a' && p[0] <= 'z') ||
664232153Smm		     (p[0] >= 'A' && p[0] <= 'Z')) &&
665232153Smm			 p[1] == ':') {
666232153Smm			p += 2;
667232153Smm		}
668232153Smm		/* Remove leading "/../", "//", etc. */
669232153Smm		while (p[0] == '/' || p[0] == '\\') {
670232153Smm			if (p[1] == '.' && p[2] == '.' &&
671232153Smm				(p[3] == '/' || p[3] == '\\')) {
672232153Smm				p += 3; /* Remove "/..", leave "/"
673232153Smm					 * for next pass. */
674232153Smm			} else
675232153Smm				p += 1; /* Remove "/". */
676232153Smm		}
677232153Smm	} while (rp != p);
678232153Smm	return (p);
679232153Smm}
680232153Smm
681228753Smm/*
682228753Smm * This is used by both out mode (to copy objects from disk into
683228753Smm * an archive) and pass mode (to copy objects from disk to
684228753Smm * an archive_write_disk "archive").
685228753Smm */
686228753Smmstatic int
687228753Smmfile_to_archive(struct cpio *cpio, const char *srcpath)
688228753Smm{
689228753Smm	const char *destpath;
690228753Smm	struct archive_entry *entry, *spare;
691228753Smm	size_t len;
692228753Smm	int r;
693228753Smm
694228753Smm	/*
695228753Smm	 * Create an archive_entry describing the source file.
696228753Smm	 *
697228753Smm	 */
698228753Smm	entry = archive_entry_new();
699228753Smm	if (entry == NULL)
700228753Smm		lafe_errc(1, 0, "Couldn't allocate entry");
701228753Smm	archive_entry_copy_sourcepath(entry, srcpath);
702228753Smm	r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
703228753Smm	    entry, -1, NULL);
704228753Smm	if (r < ARCHIVE_FAILED)
705228753Smm		lafe_errc(1, 0, "%s",
706228753Smm		    archive_error_string(cpio->archive_read_disk));
707228753Smm	if (r < ARCHIVE_OK)
708228753Smm		lafe_warnc(0, "%s",
709228753Smm		    archive_error_string(cpio->archive_read_disk));
710228753Smm	if (r <= ARCHIVE_FAILED) {
711313570Smm		archive_entry_free(entry);
712228753Smm		cpio->return_value = 1;
713228753Smm		return (r);
714228753Smm	}
715228753Smm
716228777Smm	if (cpio->uid_override >= 0) {
717228753Smm		archive_entry_set_uid(entry, cpio->uid_override);
718228777Smm		archive_entry_set_uname(entry, cpio->uname_override);
719228777Smm	}
720228777Smm	if (cpio->gid_override >= 0) {
721228753Smm		archive_entry_set_gid(entry, cpio->gid_override);
722228777Smm		archive_entry_set_gname(entry, cpio->gname_override);
723228777Smm	}
724228753Smm
725228753Smm	/*
726228753Smm	 * Generate a destination path for this entry.
727228753Smm	 * "destination path" is the name to which it will be copied in
728228753Smm	 * pass mode or the name that will go into the archive in
729228753Smm	 * output mode.
730228753Smm	 */
731228753Smm	destpath = srcpath;
732228753Smm	if (cpio->destdir) {
733228753Smm		len = strlen(cpio->destdir) + strlen(srcpath) + 8;
734228753Smm		if (len >= cpio->pass_destpath_alloc) {
735228753Smm			while (len >= cpio->pass_destpath_alloc) {
736228753Smm				cpio->pass_destpath_alloc += 512;
737228753Smm				cpio->pass_destpath_alloc *= 2;
738228753Smm			}
739228753Smm			free(cpio->pass_destpath);
740228753Smm			cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
741228753Smm			if (cpio->pass_destpath == NULL)
742228753Smm				lafe_errc(1, ENOMEM,
743228753Smm				    "Can't allocate path buffer");
744228753Smm		}
745228753Smm		strcpy(cpio->pass_destpath, cpio->destdir);
746232153Smm		strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
747228753Smm		destpath = cpio->pass_destpath;
748228753Smm	}
749228753Smm	if (cpio->option_rename)
750228753Smm		destpath = cpio_rename(destpath);
751228753Smm	if (destpath == NULL)
752228753Smm		return (0);
753228753Smm	archive_entry_copy_pathname(entry, destpath);
754228753Smm
755228753Smm	/*
756228753Smm	 * If we're trying to preserve hardlinks, match them here.
757228753Smm	 */
758228753Smm	spare = NULL;
759228753Smm	if (cpio->linkresolver != NULL
760228753Smm	    && archive_entry_filetype(entry) != AE_IFDIR) {
761228753Smm		archive_entry_linkify(cpio->linkresolver, &entry, &spare);
762228753Smm	}
763228753Smm
764228753Smm	if (entry != NULL) {
765228753Smm		r = entry_to_archive(cpio, entry);
766228753Smm		archive_entry_free(entry);
767228753Smm		if (spare != NULL) {
768228753Smm			if (r == 0)
769228753Smm				r = entry_to_archive(cpio, spare);
770228753Smm			archive_entry_free(spare);
771228753Smm		}
772228753Smm	}
773228753Smm	return (r);
774228753Smm}
775228753Smm
776228753Smmstatic int
777228753Smmentry_to_archive(struct cpio *cpio, struct archive_entry *entry)
778228753Smm{
779228753Smm	const char *destpath = archive_entry_pathname(entry);
780228753Smm	const char *srcpath = archive_entry_sourcepath(entry);
781228753Smm	int fd = -1;
782228753Smm	ssize_t bytes_read;
783228753Smm	int r;
784228753Smm
785228753Smm	/* Print out the destination name to the user. */
786228753Smm	if (cpio->verbose)
787228753Smm		fprintf(stderr,"%s", destpath);
788232153Smm	if (cpio->dot)
789232153Smm		fprintf(stderr, ".");
790228753Smm
791228753Smm	/*
792228753Smm	 * Option_link only makes sense in pass mode and for
793228753Smm	 * regular files.  Also note: if a link operation fails
794228753Smm	 * because of cross-device restrictions, we'll fall back
795228753Smm	 * to copy mode for that entry.
796228753Smm	 *
797228753Smm	 * TODO: Test other cpio implementations to see if they
798228753Smm	 * hard-link anything other than regular files here.
799228753Smm	 */
800228753Smm	if (cpio->option_link
801228753Smm	    && archive_entry_filetype(entry) == AE_IFREG)
802228753Smm	{
803228753Smm		struct archive_entry *t;
804228753Smm		/* Save the original entry in case we need it later. */
805228753Smm		t = archive_entry_clone(entry);
806228753Smm		if (t == NULL)
807228753Smm			lafe_errc(1, ENOMEM, "Can't create link");
808228753Smm		/* Note: link(2) doesn't create parent directories,
809228753Smm		 * so we use archive_write_header() instead as a
810228753Smm		 * convenience. */
811228753Smm		archive_entry_set_hardlink(t, srcpath);
812228753Smm		/* This is a straight link that carries no data. */
813228753Smm		archive_entry_set_size(t, 0);
814228753Smm		r = archive_write_header(cpio->archive, t);
815228753Smm		archive_entry_free(t);
816228753Smm		if (r != ARCHIVE_OK)
817228753Smm			lafe_warnc(archive_errno(cpio->archive),
818228753Smm			    "%s", archive_error_string(cpio->archive));
819228753Smm		if (r == ARCHIVE_FATAL)
820228753Smm			exit(1);
821228753Smm#ifdef EXDEV
822228753Smm		if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
823228753Smm			/* Cross-device link:  Just fall through and use
824228753Smm			 * the original entry to copy the file over. */
825228753Smm			lafe_warnc(0, "Copying file instead");
826228753Smm		} else
827228753Smm#endif
828228753Smm		return (0);
829228753Smm	}
830228753Smm
831228753Smm	/*
832228753Smm	 * Make sure we can open the file (if necessary) before
833228753Smm	 * trying to write the header.
834228753Smm	 */
835228753Smm	if (archive_entry_filetype(entry) == AE_IFREG) {
836228753Smm		if (archive_entry_size(entry) > 0) {
837228753Smm			fd = open(srcpath, O_RDONLY | O_BINARY);
838228753Smm			if (fd < 0) {
839228753Smm				lafe_warnc(errno,
840228753Smm				    "%s: could not open file", srcpath);
841228753Smm				goto cleanup;
842228753Smm			}
843228753Smm		}
844228753Smm	} else {
845228753Smm		archive_entry_set_size(entry, 0);
846228753Smm	}
847228753Smm
848228753Smm	r = archive_write_header(cpio->archive, entry);
849228753Smm
850228753Smm	if (r != ARCHIVE_OK)
851228753Smm		lafe_warnc(archive_errno(cpio->archive),
852228753Smm		    "%s: %s",
853228753Smm		    srcpath,
854228753Smm		    archive_error_string(cpio->archive));
855228753Smm
856228753Smm	if (r == ARCHIVE_FATAL)
857228753Smm		exit(1);
858228753Smm
859232153Smm	if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
860248616Smm		bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size);
861228753Smm		while (bytes_read > 0) {
862248616Smm			ssize_t bytes_write;
863248616Smm			bytes_write = archive_write_data(cpio->archive,
864228753Smm			    cpio->buff, bytes_read);
865248616Smm			if (bytes_write < 0)
866228753Smm				lafe_errc(1, archive_errno(cpio->archive),
867228753Smm				    "%s", archive_error_string(cpio->archive));
868248616Smm			if (bytes_write < bytes_read) {
869228753Smm				lafe_warnc(0,
870248616Smm				    "Truncated write; file may have "
871248616Smm				    "grown while being archived.");
872228753Smm			}
873248616Smm			bytes_read = read(fd, cpio->buff,
874248616Smm			    (unsigned)cpio->buff_size);
875228753Smm		}
876228753Smm	}
877228753Smm
878228753Smm	fd = restore_time(cpio, entry, srcpath, fd);
879228753Smm
880228753Smmcleanup:
881228753Smm	if (cpio->verbose)
882228753Smm		fprintf(stderr,"\n");
883228753Smm	if (fd >= 0)
884228753Smm		close(fd);
885228753Smm	return (0);
886228753Smm}
887228753Smm
888228753Smmstatic int
889228753Smmrestore_time(struct cpio *cpio, struct archive_entry *entry,
890228753Smm    const char *name, int fd)
891228753Smm{
892228753Smm#ifndef HAVE_UTIMES
893228753Smm	static int warned = 0;
894228753Smm
895228753Smm	(void)cpio; /* UNUSED */
896228753Smm	(void)entry; /* UNUSED */
897228753Smm	(void)name; /* UNUSED */
898228753Smm
899228753Smm	if (!warned)
900228753Smm		lafe_warnc(0, "Can't restore access times on this platform");
901228753Smm	warned = 1;
902228753Smm	return (fd);
903228753Smm#else
904228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
905228753Smm	struct __timeval times[2];
906228753Smm#else
907228753Smm	struct timeval times[2];
908228753Smm#endif
909228753Smm
910228753Smm	if (!cpio->option_atime_restore)
911228753Smm		return (fd);
912228753Smm
913228753Smm        times[1].tv_sec = archive_entry_mtime(entry);
914228753Smm        times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
915228753Smm
916228753Smm        times[0].tv_sec = archive_entry_atime(entry);
917228753Smm        times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
918228753Smm
919228753Smm#if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
920228753Smm        if (fd >= 0 && futimes(fd, times) == 0)
921228753Smm		return (fd);
922228753Smm#endif
923228753Smm	/*
924228753Smm	 * Some platform cannot restore access times if the file descriptor
925228753Smm	 * is still opened.
926228753Smm	 */
927228753Smm	if (fd >= 0) {
928228753Smm		close(fd);
929228753Smm		fd = -1;
930228753Smm	}
931228753Smm
932228753Smm#ifdef HAVE_LUTIMES
933228753Smm        if (lutimes(name, times) != 0)
934228753Smm#else
935228753Smm        if ((AE_IFLNK != archive_entry_filetype(entry))
936228753Smm			&& utimes(name, times) != 0)
937228753Smm#endif
938228753Smm                lafe_warnc(errno, "Can't update time for %s", name);
939228753Smm#endif
940228753Smm	return (fd);
941228753Smm}
942228753Smm
943228753Smm
944228753Smmstatic void
945228753Smmmode_in(struct cpio *cpio)
946228753Smm{
947228753Smm	struct archive *a;
948228753Smm	struct archive_entry *entry;
949228753Smm	struct archive *ext;
950228753Smm	const char *destpath;
951228753Smm	int r;
952228753Smm
953228753Smm	ext = archive_write_disk_new();
954228753Smm	if (ext == NULL)
955228753Smm		lafe_errc(1, 0, "Couldn't allocate restore object");
956228753Smm	r = archive_write_disk_set_options(ext, cpio->extract_flags);
957228753Smm	if (r != ARCHIVE_OK)
958228753Smm		lafe_errc(1, 0, "%s", archive_error_string(ext));
959228753Smm	a = archive_read_new();
960228753Smm	if (a == NULL)
961228753Smm		lafe_errc(1, 0, "Couldn't allocate archive object");
962232153Smm	archive_read_support_filter_all(a);
963228753Smm	archive_read_support_format_all(a);
964299529Smm	if (cpio->passphrase != NULL)
965299529Smm		r = archive_read_add_passphrase(a, cpio->passphrase);
966299529Smm	else
967299529Smm		r = archive_read_set_passphrase_callback(a, cpio,
968299529Smm			&passphrase_callback);
969299529Smm	if (r != ARCHIVE_OK)
970299529Smm		lafe_errc(1, 0, "%s", archive_error_string(a));
971228753Smm
972248616Smm	if (archive_read_open_filename(a, cpio->filename,
973248616Smm					cpio->bytes_per_block))
974228753Smm		lafe_errc(1, archive_errno(a),
975228753Smm		    "%s", archive_error_string(a));
976228753Smm	for (;;) {
977228753Smm		r = archive_read_next_header(a, &entry);
978228753Smm		if (r == ARCHIVE_EOF)
979228753Smm			break;
980228753Smm		if (r != ARCHIVE_OK) {
981228753Smm			lafe_errc(1, archive_errno(a),
982228753Smm			    "%s", archive_error_string(a));
983228753Smm		}
984238856Smm		if (archive_match_path_excluded(cpio->matching, entry))
985228753Smm			continue;
986228753Smm		if (cpio->option_rename) {
987228753Smm			destpath = cpio_rename(archive_entry_pathname(entry));
988228753Smm			archive_entry_set_pathname(entry, destpath);
989228753Smm		} else
990228753Smm			destpath = archive_entry_pathname(entry);
991228753Smm		if (destpath == NULL)
992228753Smm			continue;
993228753Smm		if (cpio->verbose)
994232153Smm			fprintf(stderr, "%s\n", destpath);
995232153Smm		if (cpio->dot)
996232153Smm			fprintf(stderr, ".");
997228753Smm		if (cpio->uid_override >= 0)
998228753Smm			archive_entry_set_uid(entry, cpio->uid_override);
999228753Smm		if (cpio->gid_override >= 0)
1000228753Smm			archive_entry_set_gid(entry, cpio->gid_override);
1001228753Smm		r = archive_write_header(ext, entry);
1002228753Smm		if (r != ARCHIVE_OK) {
1003228753Smm			fprintf(stderr, "%s: %s\n",
1004228753Smm			    archive_entry_pathname(entry),
1005228753Smm			    archive_error_string(ext));
1006232153Smm		} else if (!archive_entry_size_is_set(entry)
1007232153Smm		    || archive_entry_size(entry) > 0) {
1008228753Smm			r = extract_data(a, ext);
1009228753Smm			if (r != ARCHIVE_OK)
1010228753Smm				cpio->return_value = 1;
1011228753Smm		}
1012228753Smm	}
1013228753Smm	r = archive_read_close(a);
1014232153Smm	if (cpio->dot)
1015232153Smm		fprintf(stderr, "\n");
1016228753Smm	if (r != ARCHIVE_OK)
1017228753Smm		lafe_errc(1, 0, "%s", archive_error_string(a));
1018228753Smm	r = archive_write_close(ext);
1019228753Smm	if (r != ARCHIVE_OK)
1020228753Smm		lafe_errc(1, 0, "%s", archive_error_string(ext));
1021228753Smm	if (!cpio->quiet) {
1022248616Smm		int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1023228753Smm			      / 512;
1024228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1025228753Smm		    blocks == 1 ? "block" : "blocks");
1026228753Smm	}
1027232153Smm	archive_read_free(a);
1028232153Smm	archive_write_free(ext);
1029228753Smm	exit(cpio->return_value);
1030228753Smm}
1031228753Smm
1032228753Smm/*
1033228753Smm * Exits if there's a fatal error.  Returns ARCHIVE_OK
1034228753Smm * if everything is kosher.
1035228753Smm */
1036228753Smmstatic int
1037228753Smmextract_data(struct archive *ar, struct archive *aw)
1038228753Smm{
1039228753Smm	int r;
1040228753Smm	size_t size;
1041228753Smm	const void *block;
1042232153Smm	int64_t offset;
1043228753Smm
1044228753Smm	for (;;) {
1045228753Smm		r = archive_read_data_block(ar, &block, &size, &offset);
1046228753Smm		if (r == ARCHIVE_EOF)
1047228753Smm			return (ARCHIVE_OK);
1048228753Smm		if (r != ARCHIVE_OK) {
1049228753Smm			lafe_warnc(archive_errno(ar),
1050228753Smm			    "%s", archive_error_string(ar));
1051228753Smm			exit(1);
1052228753Smm		}
1053248616Smm		r = (int)archive_write_data_block(aw, block, size, offset);
1054228753Smm		if (r != ARCHIVE_OK) {
1055228753Smm			lafe_warnc(archive_errno(aw),
1056228753Smm			    "%s", archive_error_string(aw));
1057228753Smm			return (r);
1058228753Smm		}
1059228753Smm	}
1060228753Smm}
1061228753Smm
1062228753Smmstatic void
1063228753Smmmode_list(struct cpio *cpio)
1064228753Smm{
1065228753Smm	struct archive *a;
1066228753Smm	struct archive_entry *entry;
1067228753Smm	int r;
1068228753Smm
1069228753Smm	a = archive_read_new();
1070228753Smm	if (a == NULL)
1071228753Smm		lafe_errc(1, 0, "Couldn't allocate archive object");
1072232153Smm	archive_read_support_filter_all(a);
1073228753Smm	archive_read_support_format_all(a);
1074299529Smm	if (cpio->passphrase != NULL)
1075299529Smm		r = archive_read_add_passphrase(a, cpio->passphrase);
1076299529Smm	else
1077299529Smm		r = archive_read_set_passphrase_callback(a, cpio,
1078299529Smm			&passphrase_callback);
1079299529Smm	if (r != ARCHIVE_OK)
1080299529Smm		lafe_errc(1, 0, "%s", archive_error_string(a));
1081228753Smm
1082248616Smm	if (archive_read_open_filename(a, cpio->filename,
1083248616Smm					cpio->bytes_per_block))
1084228753Smm		lafe_errc(1, archive_errno(a),
1085228753Smm		    "%s", archive_error_string(a));
1086228753Smm	for (;;) {
1087228753Smm		r = archive_read_next_header(a, &entry);
1088228753Smm		if (r == ARCHIVE_EOF)
1089228753Smm			break;
1090228753Smm		if (r != ARCHIVE_OK) {
1091228753Smm			lafe_errc(1, archive_errno(a),
1092228753Smm			    "%s", archive_error_string(a));
1093228753Smm		}
1094238856Smm		if (archive_match_path_excluded(cpio->matching, entry))
1095228753Smm			continue;
1096228753Smm		if (cpio->verbose)
1097228753Smm			list_item_verbose(cpio, entry);
1098228753Smm		else
1099228753Smm			fprintf(stdout, "%s\n", archive_entry_pathname(entry));
1100228753Smm	}
1101228753Smm	r = archive_read_close(a);
1102228753Smm	if (r != ARCHIVE_OK)
1103228753Smm		lafe_errc(1, 0, "%s", archive_error_string(a));
1104228753Smm	if (!cpio->quiet) {
1105248616Smm		int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1106228753Smm			      / 512;
1107228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1108228753Smm		    blocks == 1 ? "block" : "blocks");
1109228753Smm	}
1110232153Smm	archive_read_free(a);
1111228753Smm	exit(0);
1112228753Smm}
1113228753Smm
1114228753Smm/*
1115228753Smm * Display information about the current file.
1116228753Smm *
1117228753Smm * The format here roughly duplicates the output of 'ls -l'.
1118228753Smm * This is based on SUSv2, where 'tar tv' is documented as
1119228753Smm * listing additional information in an "unspecified format,"
1120228753Smm * and 'pax -l' is documented as using the same format as 'ls -l'.
1121228753Smm */
1122228753Smmstatic void
1123228753Smmlist_item_verbose(struct cpio *cpio, struct archive_entry *entry)
1124228753Smm{
1125228753Smm	char			 size[32];
1126228753Smm	char			 date[32];
1127228753Smm	char			 uids[16], gids[16];
1128228753Smm	const char 		*uname, *gname;
1129228753Smm	FILE			*out = stdout;
1130228753Smm	const char		*fmt;
1131228753Smm	time_t			 mtime;
1132228753Smm	static time_t		 now;
1133228753Smm
1134228753Smm	if (!now)
1135228753Smm		time(&now);
1136228753Smm
1137228753Smm	if (cpio->option_numeric_uid_gid) {
1138228753Smm		/* Format numeric uid/gid for display. */
1139228753Smm		strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
1140228753Smm		uname = uids;
1141228753Smm		strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
1142228753Smm		gname = gids;
1143228753Smm	} else {
1144228753Smm		/* Use uname if it's present, else lookup name from uid. */
1145228753Smm		uname = archive_entry_uname(entry);
1146228753Smm		if (uname == NULL)
1147232153Smm			uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
1148228753Smm		/* Use gname if it's present, else lookup name from gid. */
1149228753Smm		gname = archive_entry_gname(entry);
1150228753Smm		if (gname == NULL)
1151232153Smm			gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
1152228753Smm	}
1153228753Smm
1154228753Smm	/* Print device number or file size. */
1155228753Smm	if (archive_entry_filetype(entry) == AE_IFCHR
1156228753Smm	    || archive_entry_filetype(entry) == AE_IFBLK) {
1157228753Smm		snprintf(size, sizeof(size), "%lu,%lu",
1158228753Smm		    (unsigned long)archive_entry_rdevmajor(entry),
1159228753Smm		    (unsigned long)archive_entry_rdevminor(entry));
1160228753Smm	} else {
1161228753Smm		strcpy(size, cpio_i64toa(archive_entry_size(entry)));
1162228753Smm	}
1163228753Smm
1164228753Smm	/* Format the time using 'ls -l' conventions. */
1165228753Smm	mtime = archive_entry_mtime(entry);
1166228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1167228753Smm	/* Windows' strftime function does not support %e format. */
1168228753Smm	if (mtime - now > 365*86400/2
1169228753Smm		|| mtime - now < -365*86400/2)
1170228753Smm		fmt = cpio->day_first ? "%d %b  %Y" : "%b %d  %Y";
1171228753Smm	else
1172228753Smm		fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
1173228753Smm#else
1174274846Sdim	if (mtime - now > 365*86400/2
1175274846Sdim		|| mtime - now < -365*86400/2)
1176228753Smm		fmt = cpio->day_first ? "%e %b  %Y" : "%b %e  %Y";
1177228753Smm	else
1178228753Smm		fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
1179228753Smm#endif
1180228753Smm	strftime(date, sizeof(date), fmt, localtime(&mtime));
1181228753Smm
1182228753Smm	fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
1183228753Smm	    archive_entry_strmode(entry),
1184228753Smm	    archive_entry_nlink(entry),
1185228753Smm	    uname, gname, size, date,
1186228753Smm	    archive_entry_pathname(entry));
1187228753Smm
1188228753Smm	/* Extra information for links. */
1189228753Smm	if (archive_entry_hardlink(entry)) /* Hard link */
1190228753Smm		fprintf(out, " link to %s", archive_entry_hardlink(entry));
1191228753Smm	else if (archive_entry_symlink(entry)) /* Symbolic link */
1192228753Smm		fprintf(out, " -> %s", archive_entry_symlink(entry));
1193228753Smm	fprintf(out, "\n");
1194228753Smm}
1195228753Smm
1196228753Smmstatic void
1197228753Smmmode_pass(struct cpio *cpio, const char *destdir)
1198228753Smm{
1199228753Smm	struct lafe_line_reader *lr;
1200228753Smm	const char *p;
1201228753Smm	int r;
1202318482Smm	size_t destdir_len;
1203228753Smm
1204228753Smm	/* Ensure target dir has a trailing '/' to simplify path surgery. */
1205318482Smm	destdir_len = strlen(destdir);
1206318482Smm	cpio->destdir = malloc(destdir_len + 8);
1207318482Smm	memcpy(cpio->destdir, destdir, destdir_len);
1208318482Smm	if (destdir_len == 0 || destdir[destdir_len - 1] != '/')
1209318482Smm		cpio->destdir[destdir_len++] = '/';
1210318482Smm	cpio->destdir[destdir_len++] = '\0';
1211228753Smm
1212228753Smm	cpio->archive = archive_write_disk_new();
1213228753Smm	if (cpio->archive == NULL)
1214228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
1215228753Smm	r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
1216228753Smm	if (r != ARCHIVE_OK)
1217228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1218228753Smm	cpio->linkresolver = archive_entry_linkresolver_new();
1219228753Smm	archive_write_disk_set_standard_lookup(cpio->archive);
1220228753Smm
1221228753Smm	cpio->archive_read_disk = archive_read_disk_new();
1222228753Smm	if (cpio->archive_read_disk == NULL)
1223228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
1224228753Smm	if (cpio->option_follow_links)
1225228753Smm		archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
1226228753Smm	else
1227228753Smm		archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
1228228753Smm	archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
1229228753Smm
1230228753Smm	lr = lafe_line_reader("-", cpio->option_null);
1231228753Smm	while ((p = lafe_line_reader_next(lr)) != NULL)
1232228753Smm		file_to_archive(cpio, p);
1233228753Smm	lafe_line_reader_free(lr);
1234228753Smm
1235228753Smm	archive_entry_linkresolver_free(cpio->linkresolver);
1236228753Smm	r = archive_write_close(cpio->archive);
1237232153Smm	if (cpio->dot)
1238232153Smm		fprintf(stderr, "\n");
1239228753Smm	if (r != ARCHIVE_OK)
1240228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1241228753Smm
1242228753Smm	if (!cpio->quiet) {
1243228753Smm		int64_t blocks =
1244248616Smm			(archive_filter_bytes(cpio->archive, 0) + 511)
1245228753Smm			/ 512;
1246228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1247228753Smm		    blocks == 1 ? "block" : "blocks");
1248228753Smm	}
1249228753Smm
1250232153Smm	archive_write_free(cpio->archive);
1251318482Smm	free(cpio->pass_destpath);
1252228753Smm}
1253228753Smm
1254228753Smm/*
1255228753Smm * Prompt for a new name for this entry.  Returns a pointer to the
1256228753Smm * new name or NULL if the entry should not be copied.  This
1257228753Smm * implements the semantics defined in POSIX.1-1996, which specifies
1258228753Smm * that an input of '.' means the name should be unchanged.  GNU cpio
1259228753Smm * treats '.' as a literal new name.
1260228753Smm */
1261228753Smmstatic const char *
1262228753Smmcpio_rename(const char *name)
1263228753Smm{
1264228753Smm	static char buff[1024];
1265228753Smm	FILE *t;
1266228753Smm	char *p, *ret;
1267232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1268232153Smm	FILE *to;
1269228753Smm
1270232153Smm	t = fopen("CONIN$", "r");
1271232153Smm	if (t == NULL)
1272232153Smm		return (name);
1273232153Smm	to = fopen("CONOUT$", "w");
1274299529Smm	if (to == NULL) {
1275299529Smm		fclose(t);
1276232153Smm		return (name);
1277299529Smm	}
1278232153Smm	fprintf(to, "%s (Enter/./(new name))? ", name);
1279232153Smm	fclose(to);
1280232153Smm#else
1281228753Smm	t = fopen("/dev/tty", "r+");
1282228753Smm	if (t == NULL)
1283228753Smm		return (name);
1284228753Smm	fprintf(t, "%s (Enter/./(new name))? ", name);
1285228753Smm	fflush(t);
1286232153Smm#endif
1287228753Smm
1288228753Smm	p = fgets(buff, sizeof(buff), t);
1289228753Smm	fclose(t);
1290228753Smm	if (p == NULL)
1291228753Smm		/* End-of-file is a blank line. */
1292228753Smm		return (NULL);
1293228753Smm
1294228753Smm	while (*p == ' ' || *p == '\t')
1295228753Smm		++p;
1296228753Smm	if (*p == '\n' || *p == '\0')
1297228753Smm		/* Empty line. */
1298228753Smm		return (NULL);
1299228753Smm	if (*p == '.' && p[1] == '\n')
1300228753Smm		/* Single period preserves original name. */
1301228753Smm		return (name);
1302228753Smm	ret = p;
1303228753Smm	/* Trim the final newline. */
1304228753Smm	while (*p != '\0' && *p != '\n')
1305228753Smm		++p;
1306228753Smm	/* Overwrite the final \n with a null character. */
1307228753Smm	*p = '\0';
1308228753Smm	return (ret);
1309228753Smm}
1310228753Smm
1311228753Smmstatic void
1312228753Smmfree_cache(struct name_cache *cache)
1313228753Smm{
1314228753Smm	size_t i;
1315228753Smm
1316228753Smm	if (cache != NULL) {
1317228753Smm		for (i = 0; i < cache->size; i++)
1318228753Smm			free(cache->cache[i].name);
1319228753Smm		free(cache);
1320228753Smm	}
1321228753Smm}
1322228753Smm
1323228753Smm/*
1324228753Smm * Lookup uname/gname from uid/gid, return NULL if no match.
1325228753Smm */
1326228753Smmstatic const char *
1327228753Smmlookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
1328228753Smm    int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
1329228753Smm{
1330228753Smm	char asnum[16];
1331228753Smm	struct name_cache	*cache;
1332228753Smm	const char *name;
1333228753Smm	int slot;
1334228753Smm
1335228753Smm
1336228753Smm	if (*name_cache_variable == NULL) {
1337311041Smm		*name_cache_variable = calloc(1, sizeof(struct name_cache));
1338228753Smm		if (*name_cache_variable == NULL)
1339228753Smm			lafe_errc(1, ENOMEM, "No more memory");
1340228753Smm		(*name_cache_variable)->size = name_cache_size;
1341228753Smm	}
1342228753Smm
1343228753Smm	cache = *name_cache_variable;
1344228753Smm	cache->probes++;
1345228753Smm
1346228753Smm	slot = id % cache->size;
1347228753Smm	if (cache->cache[slot].name != NULL) {
1348228753Smm		if (cache->cache[slot].id == id) {
1349228753Smm			cache->hits++;
1350228753Smm			return (cache->cache[slot].name);
1351228753Smm		}
1352228753Smm		free(cache->cache[slot].name);
1353228753Smm		cache->cache[slot].name = NULL;
1354228753Smm	}
1355228753Smm
1356316337Smm	if (lookup_fn(cpio, &name, id)) {
1357316337Smm		/* If lookup failed, format it as a number. */
1358316337Smm		snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
1359316337Smm		name = asnum;
1360228753Smm	}
1361316337Smm
1362316337Smm	cache->cache[slot].name = strdup(name);
1363316337Smm	if (cache->cache[slot].name != NULL) {
1364316337Smm		cache->cache[slot].id = id;
1365316337Smm		return (cache->cache[slot].name);
1366316337Smm	}
1367316337Smm
1368316337Smm	/*
1369316337Smm	 * Conveniently, NULL marks an empty slot, so
1370316337Smm	 * if the strdup() fails, we've just failed to
1371316337Smm	 * cache it.  No recovery necessary.
1372316337Smm	 */
1373228753Smm	return (NULL);
1374228753Smm}
1375228753Smm
1376228753Smmstatic const char *
1377228753Smmlookup_uname(struct cpio *cpio, uid_t uid)
1378228753Smm{
1379228753Smm	return (lookup_name(cpio, &cpio->uname_cache,
1380228753Smm		    &lookup_uname_helper, (id_t)uid));
1381228753Smm}
1382228753Smm
1383228753Smmstatic int
1384228753Smmlookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
1385228753Smm{
1386228753Smm	struct passwd	*pwent;
1387228753Smm
1388228753Smm	(void)cpio; /* UNUSED */
1389228753Smm
1390228753Smm	errno = 0;
1391228753Smm	pwent = getpwuid((uid_t)id);
1392228753Smm	if (pwent == NULL) {
1393316337Smm		if (errno && errno != ENOENT)
1394238856Smm			lafe_warnc(errno, "getpwuid(%s) failed",
1395238856Smm			    cpio_i64toa((int64_t)id));
1396316337Smm		return 1;
1397228753Smm	}
1398228753Smm
1399228753Smm	*name = pwent->pw_name;
1400316337Smm	return 0;
1401228753Smm}
1402228753Smm
1403228753Smmstatic const char *
1404228753Smmlookup_gname(struct cpio *cpio, gid_t gid)
1405228753Smm{
1406228753Smm	return (lookup_name(cpio, &cpio->gname_cache,
1407228753Smm		    &lookup_gname_helper, (id_t)gid));
1408228753Smm}
1409228753Smm
1410228753Smmstatic int
1411228753Smmlookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
1412228753Smm{
1413228753Smm	struct group	*grent;
1414228753Smm
1415228753Smm	(void)cpio; /* UNUSED */
1416228753Smm
1417228753Smm	errno = 0;
1418228753Smm	grent = getgrgid((gid_t)id);
1419228753Smm	if (grent == NULL) {
1420316337Smm		if (errno && errno != ENOENT)
1421238856Smm			lafe_warnc(errno, "getgrgid(%s) failed",
1422238856Smm			    cpio_i64toa((int64_t)id));
1423316337Smm		return 1;
1424228753Smm	}
1425228753Smm
1426228753Smm	*name = grent->gr_name;
1427316337Smm	return 0;
1428228753Smm}
1429228753Smm
1430228753Smm/*
1431228753Smm * It would be nice to just use printf() for formatting large numbers,
1432228753Smm * but the compatibility problems are a big headache.  Hence the
1433228753Smm * following simple utility function.
1434228753Smm */
1435228753Smmconst char *
1436228753Smmcpio_i64toa(int64_t n0)
1437228753Smm{
1438232153Smm	/* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
1439232153Smm	 * We also need 1 byte for '-' and 1 for '\0'.
1440232153Smm	 */
1441228753Smm	static char buff[22];
1442228753Smm	int64_t n = n0 < 0 ? -n0 : n0;
1443228753Smm	char *p = buff + sizeof(buff);
1444228753Smm
1445228753Smm	*--p = '\0';
1446228753Smm	do {
1447228753Smm		*--p = '0' + (int)(n % 10);
1448228753Smm		n /= 10;
1449228753Smm	} while (n > 0);
1450228753Smm	if (n0 < 0)
1451228753Smm		*--p = '-';
1452228753Smm	return p;
1453228753Smm}
1454299529Smm
1455299529Smm#define PPBUFF_SIZE 1024
1456299529Smmstatic const char *
1457299529Smmpassphrase_callback(struct archive *a, void *_client_data)
1458299529Smm{
1459299529Smm	struct cpio *cpio = (struct cpio *)_client_data;
1460299529Smm	(void)a; /* UNUSED */
1461299529Smm
1462299529Smm	if (cpio->ppbuff == NULL) {
1463299529Smm		cpio->ppbuff = malloc(PPBUFF_SIZE);
1464299529Smm		if (cpio->ppbuff == NULL)
1465299529Smm			lafe_errc(1, errno, "Out of memory");
1466299529Smm	}
1467299529Smm	return lafe_readpassphrase("Enter passphrase:",
1468299529Smm		cpio->ppbuff, PPBUFF_SIZE);
1469299529Smm}
1470299529Smm
1471299529Smmstatic void
1472299529Smmpassphrase_free(char *ppbuff)
1473299529Smm{
1474299529Smm	if (ppbuff != NULL) {
1475299529Smm		memset(ppbuff, 0, PPBUFF_SIZE);
1476299529Smm		free(ppbuff);
1477299529Smm	}
1478299529Smm}
1479