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/10/contrib/libarchive/cpio/cpio.c 358927 2020-03-13 01:06:08Z 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"
85302001Smm#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 *);
111315433Smmstatic 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);
118315433Smmstatic void	mode_in(struct cpio *) __LA_DEAD;
119315433Smmstatic 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);
125315433Smmstatic void	usage(void) __LA_DEAD;
126315433Smmstatic void	version(void) __LA_DEAD;
127302001Smmstatic const char * passphrase_callback(struct archive *, void *);
128302001Smmstatic 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;
137342361Smm	char *tptr;
138228753Smm	int uid, gid;
139342361Smm	int opt, t;
140228753Smm
141228753Smm	cpio = &_cpio;
142228753Smm	memset(cpio, 0, sizeof(*cpio));
143228753Smm	cpio->buff = buff;
144228753Smm	cpio->buff_size = sizeof(buff);
145228753Smm
146232153Smm#if defined(HAVE_SIGACTION) && defined(SIGPIPE)
147232153Smm	{ /* Ignore SIGPIPE signals. */
148232153Smm		struct sigaction sa;
149232153Smm		sigemptyset(&sa.sa_mask);
150232153Smm		sa.sa_flags = 0;
151232153Smm		sa.sa_handler = SIG_IGN;
152232153Smm		sigaction(SIGPIPE, &sa, NULL);
153232153Smm	}
154232153Smm#endif
155232153Smm
156302001Smm	/* Set lafe_progname before calling lafe_warnc. */
157302001Smm	lafe_setprogname(*argv, "bsdcpio");
158302001Smm
159232153Smm#if HAVE_SETLOCALE
160232153Smm	if (setlocale(LC_ALL, "") == NULL)
161232153Smm		lafe_warnc(0, "Failed to set default locale");
162232153Smm#endif
163228753Smm
164228753Smm	cpio->uid_override = -1;
165228753Smm	cpio->gid_override = -1;
166228753Smm	cpio->argv = argv;
167228753Smm	cpio->argc = argc;
168228753Smm	cpio->mode = '\0';
169228753Smm	cpio->verbose = 0;
170228753Smm	cpio->compress = '\0';
171228753Smm	cpio->extract_flags = ARCHIVE_EXTRACT_NO_AUTODIR;
172228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
173228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_SYMLINKS;
174228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NODOTDOT;
175300361Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
176228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_PERM;
177228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_FFLAGS;
178228753Smm	cpio->extract_flags |= ARCHIVE_EXTRACT_ACL;
179228753Smm#if !defined(_WIN32) && !defined(__CYGWIN__)
180228753Smm	if (geteuid() == 0)
181228753Smm		cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
182228753Smm#endif
183228753Smm	cpio->bytes_per_block = 512;
184228753Smm	cpio->filename = NULL;
185228753Smm
186238856Smm	cpio->matching = archive_match_new();
187238856Smm	if (cpio->matching == NULL)
188238856Smm		lafe_errc(1, 0, "Out of memory");
189238856Smm
190228753Smm	while ((opt = cpio_getopt(cpio)) != -1) {
191228753Smm		switch (opt) {
192228753Smm		case '0': /* GNU convention: --null, -0 */
193228753Smm			cpio->option_null = 1;
194228753Smm			break;
195228753Smm		case 'A': /* NetBSD/OpenBSD */
196228753Smm			cpio->option_append = 1;
197228753Smm			break;
198228753Smm		case 'a': /* POSIX 1997 */
199228753Smm			cpio->option_atime_restore = 1;
200228753Smm			break;
201228753Smm		case 'B': /* POSIX 1997 */
202228753Smm			cpio->bytes_per_block = 5120;
203228753Smm			break;
204248616Smm		case OPTION_B64ENCODE:
205248616Smm			cpio->add_filter = opt;
206248616Smm			break;
207228753Smm		case 'C': /* NetBSD/OpenBSD */
208342361Smm			errno = 0;
209342361Smm			tptr = NULL;
210342361Smm			t = (int)strtol(cpio->argument, &tptr, 10);
211342361Smm			if (errno || t <= 0 || *(cpio->argument) == '\0' ||
212342361Smm			    tptr == NULL || *tptr != '\0') {
213342361Smm				lafe_errc(1, 0, "Invalid blocksize: %s",
214342361Smm				    cpio->argument);
215342361Smm			}
216342361Smm			cpio->bytes_per_block = t;
217228753Smm			break;
218228753Smm		case 'c': /* POSIX 1997 */
219228753Smm			cpio->format = "odc";
220228753Smm			break;
221228753Smm		case 'd': /* POSIX 1997 */
222228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_NO_AUTODIR;
223228753Smm			break;
224228753Smm		case 'E': /* NetBSD/OpenBSD */
225238856Smm			if (archive_match_include_pattern_from_file(
226238856Smm			    cpio->matching, cpio->argument,
227238856Smm			    cpio->option_null) != ARCHIVE_OK)
228238856Smm				lafe_errc(1, 0, "Error : %s",
229238856Smm				    archive_error_string(cpio->matching));
230228753Smm			break;
231228753Smm		case 'F': /* NetBSD/OpenBSD/GNU cpio */
232232153Smm			cpio->filename = cpio->argument;
233228753Smm			break;
234228753Smm		case 'f': /* POSIX 1997 */
235238856Smm			if (archive_match_exclude_pattern(cpio->matching,
236238856Smm			    cpio->argument) != ARCHIVE_OK)
237238856Smm				lafe_errc(1, 0, "Error : %s",
238238856Smm				    archive_error_string(cpio->matching));
239228753Smm			break;
240248616Smm		case OPTION_GRZIP:
241248616Smm			cpio->compress = opt;
242248616Smm			break;
243228753Smm		case 'H': /* GNU cpio (also --format) */
244232153Smm			cpio->format = cpio->argument;
245228753Smm			break;
246228753Smm		case 'h':
247228753Smm			long_help();
248228753Smm			break;
249228753Smm		case 'I': /* NetBSD/OpenBSD */
250232153Smm			cpio->filename = cpio->argument;
251228753Smm			break;
252228753Smm		case 'i': /* POSIX 1997 */
253228753Smm			if (cpio->mode != '\0')
254228753Smm				lafe_errc(1, 0,
255228753Smm				    "Cannot use both -i and -%c", cpio->mode);
256228753Smm			cpio->mode = opt;
257228753Smm			break;
258228753Smm		case 'J': /* GNU tar, others */
259228753Smm			cpio->compress = opt;
260228753Smm			break;
261228753Smm		case 'j': /* GNU tar, others */
262228753Smm			cpio->compress = opt;
263228753Smm			break;
264228753Smm		case OPTION_INSECURE:
265228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_SYMLINKS;
266228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
267300361Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
268228753Smm			break;
269228753Smm		case 'L': /* GNU cpio */
270228753Smm			cpio->option_follow_links = 1;
271228753Smm			break;
272228753Smm		case 'l': /* POSIX 1997 */
273228753Smm			cpio->option_link = 1;
274228753Smm			break;
275248616Smm		case OPTION_LRZIP:
276302001Smm		case OPTION_LZ4:
277228753Smm		case OPTION_LZMA: /* GNU tar, others */
278248616Smm		case OPTION_LZOP: /* GNU tar, others */
279324418Smm		case OPTION_ZSTD:
280228753Smm			cpio->compress = opt;
281228753Smm			break;
282228753Smm		case 'm': /* POSIX 1997 */
283228753Smm			cpio->extract_flags |= ARCHIVE_EXTRACT_TIME;
284228753Smm			break;
285228753Smm		case 'n': /* GNU cpio */
286228753Smm			cpio->option_numeric_uid_gid = 1;
287228753Smm			break;
288228753Smm		case OPTION_NO_PRESERVE_OWNER: /* GNU cpio */
289228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_OWNER;
290228753Smm			break;
291228753Smm		case 'O': /* GNU cpio */
292232153Smm			cpio->filename = cpio->argument;
293228753Smm			break;
294228753Smm		case 'o': /* POSIX 1997 */
295228753Smm			if (cpio->mode != '\0')
296228753Smm				lafe_errc(1, 0,
297228753Smm				    "Cannot use both -o and -%c", cpio->mode);
298228753Smm			cpio->mode = opt;
299228753Smm			break;
300228753Smm		case 'p': /* POSIX 1997 */
301228753Smm			if (cpio->mode != '\0')
302228753Smm				lafe_errc(1, 0,
303228753Smm				    "Cannot use both -p and -%c", cpio->mode);
304228753Smm			cpio->mode = opt;
305228753Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NODOTDOT;
306300361Smm			cpio->extract_flags &= ~ARCHIVE_EXTRACT_SECURE_NOABSOLUTEPATHS;
307228753Smm			break;
308302001Smm		case OPTION_PASSPHRASE:
309302001Smm			cpio->passphrase = cpio->argument;
310302001Smm			break;
311228753Smm		case OPTION_PRESERVE_OWNER:
312228753Smm			cpio->extract_flags |= ARCHIVE_EXTRACT_OWNER;
313228753Smm			break;
314228753Smm		case OPTION_QUIET: /* GNU cpio */
315228753Smm			cpio->quiet = 1;
316228753Smm			break;
317228753Smm		case 'R': /* GNU cpio, also --owner */
318228777Smm			/* TODO: owner_parse should return uname/gname
319228777Smm			 * also; use that to set [ug]name_override. */
320232153Smm			errmsg = owner_parse(cpio->argument, &uid, &gid);
321228753Smm			if (errmsg) {
322228753Smm				lafe_warnc(-1, "%s", errmsg);
323228753Smm				usage();
324228753Smm			}
325228777Smm			if (uid != -1) {
326228753Smm				cpio->uid_override = uid;
327228777Smm				cpio->uname_override = NULL;
328228777Smm			}
329228777Smm			if (gid != -1) {
330228753Smm				cpio->gid_override = gid;
331228777Smm				cpio->gname_override = NULL;
332228777Smm			}
333228753Smm			break;
334228753Smm		case 'r': /* POSIX 1997 */
335228753Smm			cpio->option_rename = 1;
336228753Smm			break;
337228753Smm		case 't': /* POSIX 1997 */
338228753Smm			cpio->option_list = 1;
339228753Smm			break;
340228753Smm		case 'u': /* POSIX 1997 */
341228753Smm			cpio->extract_flags
342228753Smm			    &= ~ARCHIVE_EXTRACT_NO_OVERWRITE_NEWER;
343228753Smm			break;
344248616Smm		case OPTION_UUENCODE:
345248616Smm			cpio->add_filter = opt;
346248616Smm			break;
347228753Smm		case 'v': /* POSIX 1997 */
348228753Smm			cpio->verbose++;
349228753Smm			break;
350232153Smm		case 'V': /* GNU cpio */
351232153Smm			cpio->dot++;
352232153Smm			break;
353228753Smm		case OPTION_VERSION: /* GNU convention */
354228753Smm			version();
355228753Smm			break;
356228753Smm#if 0
357228753Smm	        /*
358228753Smm		 * cpio_getopt() handles -W specially, so it's not
359228753Smm		 * available here.
360228753Smm		 */
361228753Smm		case 'W': /* Obscure, but useful GNU convention. */
362228753Smm			break;
363228753Smm#endif
364228753Smm		case 'y': /* tar convention */
365228753Smm			cpio->compress = opt;
366228753Smm			break;
367228753Smm		case 'Z': /* tar convention */
368228753Smm			cpio->compress = opt;
369228753Smm			break;
370228753Smm		case 'z': /* tar convention */
371228753Smm			cpio->compress = opt;
372228753Smm			break;
373228753Smm		default:
374228753Smm			usage();
375228753Smm		}
376228753Smm	}
377228753Smm
378228753Smm	/*
379228753Smm	 * Sanity-check args, error out on nonsensical combinations.
380228753Smm	 */
381228753Smm	/* -t implies -i if no mode was specified. */
382228753Smm	if (cpio->option_list && cpio->mode == '\0')
383228753Smm		cpio->mode = 'i';
384228753Smm	/* -t requires -i */
385228753Smm	if (cpio->option_list && cpio->mode != 'i')
386228753Smm		lafe_errc(1, 0, "Option -t requires -i");
387228753Smm	/* -n requires -it */
388228753Smm	if (cpio->option_numeric_uid_gid && !cpio->option_list)
389228753Smm		lafe_errc(1, 0, "Option -n requires -it");
390228753Smm	/* Can only specify format when writing */
391228753Smm	if (cpio->format != NULL && cpio->mode != 'o')
392228753Smm		lafe_errc(1, 0, "Option --format requires -o");
393228753Smm	/* -l requires -p */
394228753Smm	if (cpio->option_link && cpio->mode != 'p')
395228753Smm		lafe_errc(1, 0, "Option -l requires -p");
396232153Smm	/* -v overrides -V */
397232153Smm	if (cpio->dot && cpio->verbose)
398232153Smm		cpio->dot = 0;
399228753Smm	/* TODO: Flag other nonsensical combinations. */
400228753Smm
401228753Smm	switch (cpio->mode) {
402228753Smm	case 'o':
403228753Smm		/* TODO: Implement old binary format in libarchive,
404228753Smm		   use that here. */
405228753Smm		if (cpio->format == NULL)
406228753Smm			cpio->format = "odc"; /* Default format */
407228753Smm
408228753Smm		mode_out(cpio);
409228753Smm		break;
410228753Smm	case 'i':
411228753Smm		while (*cpio->argv != NULL) {
412238856Smm			if (archive_match_include_pattern(cpio->matching,
413238856Smm			    *cpio->argv) != ARCHIVE_OK)
414238856Smm				lafe_errc(1, 0, "Error : %s",
415238856Smm				    archive_error_string(cpio->matching));
416228753Smm			--cpio->argc;
417228753Smm			++cpio->argv;
418228753Smm		}
419228753Smm		if (cpio->option_list)
420228753Smm			mode_list(cpio);
421228753Smm		else
422228753Smm			mode_in(cpio);
423228753Smm		break;
424228753Smm	case 'p':
425228753Smm		if (*cpio->argv == NULL || **cpio->argv == '\0')
426228753Smm			lafe_errc(1, 0,
427228753Smm			    "-p mode requires a target directory");
428228753Smm		mode_pass(cpio, *cpio->argv);
429228753Smm		break;
430228753Smm	default:
431228753Smm		lafe_errc(1, 0,
432228753Smm		    "Must specify at least one of -i, -o, or -p");
433228753Smm	}
434228753Smm
435238856Smm	archive_match_free(cpio->matching);
436228753Smm	free_cache(cpio->gname_cache);
437228753Smm	free_cache(cpio->uname_cache);
438248616Smm	free(cpio->destdir);
439302001Smm	passphrase_free(cpio->ppbuff);
440228753Smm	return (cpio->return_value);
441228753Smm}
442228753Smm
443228753Smmstatic void
444228753Smmusage(void)
445228753Smm{
446228753Smm	const char	*p;
447228753Smm
448302001Smm	p = lafe_getprogname();
449228753Smm
450228753Smm	fprintf(stderr, "Brief Usage:\n");
451228753Smm	fprintf(stderr, "  List:    %s -it < archive\n", p);
452228753Smm	fprintf(stderr, "  Extract: %s -i < archive\n", p);
453228753Smm	fprintf(stderr, "  Create:  %s -o < filenames > archive\n", p);
454228753Smm	fprintf(stderr, "  Help:    %s --help\n", p);
455228753Smm	exit(1);
456228753Smm}
457228753Smm
458228753Smmstatic const char *long_help_msg =
459228753Smm	"First option must be a mode specifier:\n"
460228753Smm	"  -i Input  -o Output  -p Pass\n"
461228753Smm	"Common Options:\n"
462232153Smm	"  -v Verbose filenames     -V  one dot per file\n"
463228753Smm	"Create: %p -o [options]  < [list of files] > [archive]\n"
464228753Smm	"  -J,-y,-z,--lzma  Compress archive with xz/bzip2/gzip/lzma\n"
465228753Smm	"  --format {odc|newc|ustar}  Select archive format\n"
466228753Smm	"List: %p -it < [archive]\n"
467228753Smm	"Extract: %p -i [options] < [archive]\n";
468228753Smm
469228753Smm
470228753Smm/*
471228753Smm * Note that the word 'bsdcpio' will always appear in the first line
472228753Smm * of output.
473228753Smm *
474228753Smm * In particular, /bin/sh scripts that need to test for the presence
475228753Smm * of bsdcpio can use the following template:
476228753Smm *
477228753Smm * if (cpio --help 2>&1 | grep bsdcpio >/dev/null 2>&1 ) then \
478228753Smm *          echo bsdcpio; else echo not bsdcpio; fi
479228753Smm */
480228753Smmstatic void
481228753Smmlong_help(void)
482228753Smm{
483228753Smm	const char	*prog;
484228753Smm	const char	*p;
485228753Smm
486302001Smm	prog = lafe_getprogname();
487228753Smm
488228753Smm	fflush(stderr);
489228753Smm
490228753Smm	p = (strcmp(prog,"bsdcpio") != 0) ? "(bsdcpio)" : "";
491228753Smm	printf("%s%s: manipulate archive files\n", prog, p);
492228753Smm
493228753Smm	for (p = long_help_msg; *p != '\0'; p++) {
494228753Smm		if (*p == '%') {
495228753Smm			if (p[1] == 'p') {
496228753Smm				fputs(prog, stdout);
497228753Smm				p++;
498228753Smm			} else
499228753Smm				putchar('%');
500228753Smm		} else
501228753Smm			putchar(*p);
502228753Smm	}
503228753Smm	version();
504228753Smm}
505228753Smm
506228753Smmstatic void
507228753Smmversion(void)
508228753Smm{
509337352Smm	fprintf(stdout,"bsdcpio %s - %s \n",
510228753Smm	    BSDCPIO_VERSION_STRING,
511302001Smm	    archive_version_details());
512228753Smm	exit(0);
513228753Smm}
514228753Smm
515228753Smmstatic void
516228753Smmmode_out(struct cpio *cpio)
517228753Smm{
518228753Smm	struct archive_entry *entry, *spare;
519228753Smm	struct lafe_line_reader *lr;
520228753Smm	const char *p;
521228753Smm	int r;
522228753Smm
523228753Smm	if (cpio->option_append)
524228753Smm		lafe_errc(1, 0, "Append mode not yet supported.");
525228753Smm
526228753Smm	cpio->archive_read_disk = archive_read_disk_new();
527228753Smm	if (cpio->archive_read_disk == NULL)
528228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
529228753Smm	if (cpio->option_follow_links)
530228753Smm		archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
531228753Smm	else
532228753Smm		archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
533228753Smm	archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
534228753Smm
535228753Smm	cpio->archive = archive_write_new();
536228753Smm	if (cpio->archive == NULL)
537228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
538228753Smm	switch (cpio->compress) {
539248616Smm	case OPTION_GRZIP:
540248616Smm		r = archive_write_add_filter_grzip(cpio->archive);
541248616Smm		break;
542228753Smm	case 'J':
543248616Smm		r = archive_write_add_filter_xz(cpio->archive);
544228753Smm		break;
545248616Smm	case OPTION_LRZIP:
546248616Smm		r = archive_write_add_filter_lrzip(cpio->archive);
547248616Smm		break;
548302001Smm	case OPTION_LZ4:
549302001Smm		r = archive_write_add_filter_lz4(cpio->archive);
550302001Smm		break;
551228753Smm	case OPTION_LZMA:
552248616Smm		r = archive_write_add_filter_lzma(cpio->archive);
553228753Smm		break;
554248616Smm	case OPTION_LZOP:
555248616Smm		r = archive_write_add_filter_lzop(cpio->archive);
556248616Smm		break;
557324418Smm	case OPTION_ZSTD:
558324418Smm		r = archive_write_add_filter_zstd(cpio->archive);
559324418Smm		break;
560228753Smm	case 'j': case 'y':
561248616Smm		r = archive_write_add_filter_bzip2(cpio->archive);
562228753Smm		break;
563228753Smm	case 'z':
564248616Smm		r = archive_write_add_filter_gzip(cpio->archive);
565228753Smm		break;
566228753Smm	case 'Z':
567248616Smm		r = archive_write_add_filter_compress(cpio->archive);
568228753Smm		break;
569228753Smm	default:
570248616Smm		r = archive_write_add_filter_none(cpio->archive);
571228753Smm		break;
572228753Smm	}
573228753Smm	if (r < ARCHIVE_WARN)
574228753Smm		lafe_errc(1, 0, "Requested compression not available");
575248616Smm	switch (cpio->add_filter) {
576248616Smm	case 0:
577248616Smm		r = ARCHIVE_OK;
578248616Smm		break;
579248616Smm	case OPTION_B64ENCODE:
580248616Smm		r = archive_write_add_filter_b64encode(cpio->archive);
581248616Smm		break;
582248616Smm	case OPTION_UUENCODE:
583248616Smm		r = archive_write_add_filter_uuencode(cpio->archive);
584248616Smm		break;
585248616Smm	}
586248616Smm	if (r < ARCHIVE_WARN)
587248616Smm		lafe_errc(1, 0, "Requested filter not available");
588228753Smm	r = archive_write_set_format_by_name(cpio->archive, cpio->format);
589228753Smm	if (r != ARCHIVE_OK)
590228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
591228753Smm	archive_write_set_bytes_per_block(cpio->archive, cpio->bytes_per_block);
592228753Smm	cpio->linkresolver = archive_entry_linkresolver_new();
593228753Smm	archive_entry_linkresolver_set_strategy(cpio->linkresolver,
594228753Smm	    archive_format(cpio->archive));
595302001Smm	if (cpio->passphrase != NULL)
596302001Smm		r = archive_write_set_passphrase(cpio->archive,
597302001Smm			cpio->passphrase);
598302001Smm	else
599302001Smm		r = archive_write_set_passphrase_callback(cpio->archive, cpio,
600302001Smm			&passphrase_callback);
601302001Smm	if (r != ARCHIVE_OK)
602302001Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
603228753Smm
604228753Smm	/*
605228753Smm	 * The main loop:  Copy each file into the output archive.
606228753Smm	 */
607248616Smm	r = archive_write_open_filename(cpio->archive, cpio->filename);
608228753Smm	if (r != ARCHIVE_OK)
609228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
610228753Smm	lr = lafe_line_reader("-", cpio->option_null);
611228753Smm	while ((p = lafe_line_reader_next(lr)) != NULL)
612228753Smm		file_to_archive(cpio, p);
613228753Smm	lafe_line_reader_free(lr);
614228753Smm
615228753Smm	/*
616228753Smm	 * The hardlink detection may have queued up a couple of entries
617228753Smm	 * that can now be flushed.
618228753Smm	 */
619228753Smm	entry = NULL;
620228753Smm	archive_entry_linkify(cpio->linkresolver, &entry, &spare);
621228753Smm	while (entry != NULL) {
622228753Smm		entry_to_archive(cpio, entry);
623228753Smm		archive_entry_free(entry);
624228753Smm		entry = NULL;
625228753Smm		archive_entry_linkify(cpio->linkresolver, &entry, &spare);
626228753Smm	}
627228753Smm
628228753Smm	r = archive_write_close(cpio->archive);
629232153Smm	if (cpio->dot)
630232153Smm		fprintf(stderr, "\n");
631228753Smm	if (r != ARCHIVE_OK)
632228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
633228753Smm
634228753Smm	if (!cpio->quiet) {
635228753Smm		int64_t blocks =
636248616Smm			(archive_filter_bytes(cpio->archive, 0) + 511)
637228753Smm			/ 512;
638228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
639228753Smm		    blocks == 1 ? "block" : "blocks");
640228753Smm	}
641232153Smm	archive_write_free(cpio->archive);
642318483Smm	archive_entry_linkresolver_free(cpio->linkresolver);
643228753Smm}
644228753Smm
645232153Smmstatic const char *
646232153Smmremove_leading_slash(const char *p)
647232153Smm{
648232153Smm	const char *rp;
649232153Smm
650232153Smm	/* Remove leading "//./" or "//?/" or "//?/UNC/"
651232153Smm	 * (absolute path prefixes used by Windows API) */
652232153Smm	if ((p[0] == '/' || p[0] == '\\') &&
653232153Smm	    (p[1] == '/' || p[1] == '\\') &&
654232153Smm	    (p[2] == '.' || p[2] == '?') &&
655232153Smm	    (p[3] == '/' || p[3] == '\\'))
656232153Smm	{
657232153Smm		if (p[2] == '?' &&
658232153Smm		    (p[4] == 'U' || p[4] == 'u') &&
659232153Smm		    (p[5] == 'N' || p[5] == 'n') &&
660232153Smm		    (p[6] == 'C' || p[6] == 'c') &&
661232153Smm		    (p[7] == '/' || p[7] == '\\'))
662232153Smm			p += 8;
663232153Smm		else
664232153Smm			p += 4;
665232153Smm	}
666232153Smm	do {
667232153Smm		rp = p;
668232153Smm		/* Remove leading drive letter from archives created
669232153Smm		 * on Windows. */
670232153Smm		if (((p[0] >= 'a' && p[0] <= 'z') ||
671232153Smm		     (p[0] >= 'A' && p[0] <= 'Z')) &&
672232153Smm			 p[1] == ':') {
673232153Smm			p += 2;
674232153Smm		}
675232153Smm		/* Remove leading "/../", "//", etc. */
676232153Smm		while (p[0] == '/' || p[0] == '\\') {
677232153Smm			if (p[1] == '.' && p[2] == '.' &&
678232153Smm				(p[3] == '/' || p[3] == '\\')) {
679232153Smm				p += 3; /* Remove "/..", leave "/"
680232153Smm					 * for next pass. */
681232153Smm			} else
682232153Smm				p += 1; /* Remove "/". */
683232153Smm		}
684232153Smm	} while (rp != p);
685232153Smm	return (p);
686232153Smm}
687232153Smm
688228753Smm/*
689228753Smm * This is used by both out mode (to copy objects from disk into
690228753Smm * an archive) and pass mode (to copy objects from disk to
691228753Smm * an archive_write_disk "archive").
692228753Smm */
693228753Smmstatic int
694228753Smmfile_to_archive(struct cpio *cpio, const char *srcpath)
695228753Smm{
696228753Smm	const char *destpath;
697228753Smm	struct archive_entry *entry, *spare;
698228753Smm	size_t len;
699228753Smm	int r;
700228753Smm
701228753Smm	/*
702228753Smm	 * Create an archive_entry describing the source file.
703228753Smm	 *
704228753Smm	 */
705228753Smm	entry = archive_entry_new();
706228753Smm	if (entry == NULL)
707228753Smm		lafe_errc(1, 0, "Couldn't allocate entry");
708228753Smm	archive_entry_copy_sourcepath(entry, srcpath);
709228753Smm	r = archive_read_disk_entry_from_file(cpio->archive_read_disk,
710228753Smm	    entry, -1, NULL);
711228753Smm	if (r < ARCHIVE_FAILED)
712228753Smm		lafe_errc(1, 0, "%s",
713228753Smm		    archive_error_string(cpio->archive_read_disk));
714228753Smm	if (r < ARCHIVE_OK)
715228753Smm		lafe_warnc(0, "%s",
716228753Smm		    archive_error_string(cpio->archive_read_disk));
717228753Smm	if (r <= ARCHIVE_FAILED) {
718313571Smm		archive_entry_free(entry);
719228753Smm		cpio->return_value = 1;
720228753Smm		return (r);
721228753Smm	}
722228753Smm
723228777Smm	if (cpio->uid_override >= 0) {
724228753Smm		archive_entry_set_uid(entry, cpio->uid_override);
725228777Smm		archive_entry_set_uname(entry, cpio->uname_override);
726228777Smm	}
727228777Smm	if (cpio->gid_override >= 0) {
728228753Smm		archive_entry_set_gid(entry, cpio->gid_override);
729228777Smm		archive_entry_set_gname(entry, cpio->gname_override);
730228777Smm	}
731228753Smm
732228753Smm	/*
733228753Smm	 * Generate a destination path for this entry.
734228753Smm	 * "destination path" is the name to which it will be copied in
735228753Smm	 * pass mode or the name that will go into the archive in
736228753Smm	 * output mode.
737228753Smm	 */
738228753Smm	destpath = srcpath;
739228753Smm	if (cpio->destdir) {
740358927Smm		len = cpio->destdir_len + strlen(srcpath) + 8;
741228753Smm		if (len >= cpio->pass_destpath_alloc) {
742228753Smm			while (len >= cpio->pass_destpath_alloc) {
743228753Smm				cpio->pass_destpath_alloc += 512;
744228753Smm				cpio->pass_destpath_alloc *= 2;
745228753Smm			}
746228753Smm			free(cpio->pass_destpath);
747228753Smm			cpio->pass_destpath = malloc(cpio->pass_destpath_alloc);
748228753Smm			if (cpio->pass_destpath == NULL)
749228753Smm				lafe_errc(1, ENOMEM,
750228753Smm				    "Can't allocate path buffer");
751228753Smm		}
752228753Smm		strcpy(cpio->pass_destpath, cpio->destdir);
753232153Smm		strcat(cpio->pass_destpath, remove_leading_slash(srcpath));
754228753Smm		destpath = cpio->pass_destpath;
755228753Smm	}
756228753Smm	if (cpio->option_rename)
757228753Smm		destpath = cpio_rename(destpath);
758228753Smm	if (destpath == NULL)
759228753Smm		return (0);
760228753Smm	archive_entry_copy_pathname(entry, destpath);
761228753Smm
762228753Smm	/*
763228753Smm	 * If we're trying to preserve hardlinks, match them here.
764228753Smm	 */
765228753Smm	spare = NULL;
766228753Smm	if (cpio->linkresolver != NULL
767228753Smm	    && archive_entry_filetype(entry) != AE_IFDIR) {
768228753Smm		archive_entry_linkify(cpio->linkresolver, &entry, &spare);
769228753Smm	}
770228753Smm
771228753Smm	if (entry != NULL) {
772228753Smm		r = entry_to_archive(cpio, entry);
773228753Smm		archive_entry_free(entry);
774228753Smm		if (spare != NULL) {
775228753Smm			if (r == 0)
776228753Smm				r = entry_to_archive(cpio, spare);
777228753Smm			archive_entry_free(spare);
778228753Smm		}
779228753Smm	}
780228753Smm	return (r);
781228753Smm}
782228753Smm
783228753Smmstatic int
784228753Smmentry_to_archive(struct cpio *cpio, struct archive_entry *entry)
785228753Smm{
786228753Smm	const char *destpath = archive_entry_pathname(entry);
787228753Smm	const char *srcpath = archive_entry_sourcepath(entry);
788228753Smm	int fd = -1;
789228753Smm	ssize_t bytes_read;
790228753Smm	int r;
791228753Smm
792228753Smm	/* Print out the destination name to the user. */
793228753Smm	if (cpio->verbose)
794228753Smm		fprintf(stderr,"%s", destpath);
795232153Smm	if (cpio->dot)
796232153Smm		fprintf(stderr, ".");
797228753Smm
798228753Smm	/*
799228753Smm	 * Option_link only makes sense in pass mode and for
800228753Smm	 * regular files.  Also note: if a link operation fails
801228753Smm	 * because of cross-device restrictions, we'll fall back
802228753Smm	 * to copy mode for that entry.
803228753Smm	 *
804228753Smm	 * TODO: Test other cpio implementations to see if they
805228753Smm	 * hard-link anything other than regular files here.
806228753Smm	 */
807228753Smm	if (cpio->option_link
808228753Smm	    && archive_entry_filetype(entry) == AE_IFREG)
809228753Smm	{
810228753Smm		struct archive_entry *t;
811228753Smm		/* Save the original entry in case we need it later. */
812228753Smm		t = archive_entry_clone(entry);
813228753Smm		if (t == NULL)
814228753Smm			lafe_errc(1, ENOMEM, "Can't create link");
815228753Smm		/* Note: link(2) doesn't create parent directories,
816228753Smm		 * so we use archive_write_header() instead as a
817228753Smm		 * convenience. */
818228753Smm		archive_entry_set_hardlink(t, srcpath);
819228753Smm		/* This is a straight link that carries no data. */
820228753Smm		archive_entry_set_size(t, 0);
821228753Smm		r = archive_write_header(cpio->archive, t);
822228753Smm		archive_entry_free(t);
823228753Smm		if (r != ARCHIVE_OK)
824228753Smm			lafe_warnc(archive_errno(cpio->archive),
825228753Smm			    "%s", archive_error_string(cpio->archive));
826228753Smm		if (r == ARCHIVE_FATAL)
827228753Smm			exit(1);
828228753Smm#ifdef EXDEV
829228753Smm		if (r != ARCHIVE_OK && archive_errno(cpio->archive) == EXDEV) {
830228753Smm			/* Cross-device link:  Just fall through and use
831228753Smm			 * the original entry to copy the file over. */
832228753Smm			lafe_warnc(0, "Copying file instead");
833228753Smm		} else
834228753Smm#endif
835228753Smm		return (0);
836228753Smm	}
837228753Smm
838228753Smm	/*
839228753Smm	 * Make sure we can open the file (if necessary) before
840228753Smm	 * trying to write the header.
841228753Smm	 */
842228753Smm	if (archive_entry_filetype(entry) == AE_IFREG) {
843228753Smm		if (archive_entry_size(entry) > 0) {
844228753Smm			fd = open(srcpath, O_RDONLY | O_BINARY);
845228753Smm			if (fd < 0) {
846228753Smm				lafe_warnc(errno,
847228753Smm				    "%s: could not open file", srcpath);
848228753Smm				goto cleanup;
849228753Smm			}
850228753Smm		}
851228753Smm	} else {
852228753Smm		archive_entry_set_size(entry, 0);
853228753Smm	}
854228753Smm
855228753Smm	r = archive_write_header(cpio->archive, entry);
856228753Smm
857228753Smm	if (r != ARCHIVE_OK)
858228753Smm		lafe_warnc(archive_errno(cpio->archive),
859228753Smm		    "%s: %s",
860228753Smm		    srcpath,
861228753Smm		    archive_error_string(cpio->archive));
862228753Smm
863228753Smm	if (r == ARCHIVE_FATAL)
864228753Smm		exit(1);
865228753Smm
866232153Smm	if (r >= ARCHIVE_WARN && archive_entry_size(entry) > 0 && fd >= 0) {
867248616Smm		bytes_read = read(fd, cpio->buff, (unsigned)cpio->buff_size);
868228753Smm		while (bytes_read > 0) {
869248616Smm			ssize_t bytes_write;
870248616Smm			bytes_write = archive_write_data(cpio->archive,
871228753Smm			    cpio->buff, bytes_read);
872248616Smm			if (bytes_write < 0)
873228753Smm				lafe_errc(1, archive_errno(cpio->archive),
874228753Smm				    "%s", archive_error_string(cpio->archive));
875248616Smm			if (bytes_write < bytes_read) {
876228753Smm				lafe_warnc(0,
877248616Smm				    "Truncated write; file may have "
878248616Smm				    "grown while being archived.");
879228753Smm			}
880248616Smm			bytes_read = read(fd, cpio->buff,
881248616Smm			    (unsigned)cpio->buff_size);
882228753Smm		}
883228753Smm	}
884228753Smm
885228753Smm	fd = restore_time(cpio, entry, srcpath, fd);
886228753Smm
887228753Smmcleanup:
888228753Smm	if (cpio->verbose)
889228753Smm		fprintf(stderr,"\n");
890228753Smm	if (fd >= 0)
891228753Smm		close(fd);
892228753Smm	return (0);
893228753Smm}
894228753Smm
895228753Smmstatic int
896228753Smmrestore_time(struct cpio *cpio, struct archive_entry *entry,
897228753Smm    const char *name, int fd)
898228753Smm{
899228753Smm#ifndef HAVE_UTIMES
900228753Smm	static int warned = 0;
901228753Smm
902228753Smm	(void)cpio; /* UNUSED */
903228753Smm	(void)entry; /* UNUSED */
904228753Smm	(void)name; /* UNUSED */
905228753Smm
906228753Smm	if (!warned)
907228753Smm		lafe_warnc(0, "Can't restore access times on this platform");
908228753Smm	warned = 1;
909228753Smm	return (fd);
910228753Smm#else
911228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
912228753Smm	struct __timeval times[2];
913228753Smm#else
914228753Smm	struct timeval times[2];
915228753Smm#endif
916228753Smm
917228753Smm	if (!cpio->option_atime_restore)
918228753Smm		return (fd);
919228753Smm
920228753Smm        times[1].tv_sec = archive_entry_mtime(entry);
921228753Smm        times[1].tv_usec = archive_entry_mtime_nsec(entry) / 1000;
922228753Smm
923228753Smm        times[0].tv_sec = archive_entry_atime(entry);
924228753Smm        times[0].tv_usec = archive_entry_atime_nsec(entry) / 1000;
925228753Smm
926228753Smm#if defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
927228753Smm        if (fd >= 0 && futimes(fd, times) == 0)
928228753Smm		return (fd);
929228753Smm#endif
930228753Smm	/*
931228753Smm	 * Some platform cannot restore access times if the file descriptor
932228753Smm	 * is still opened.
933228753Smm	 */
934228753Smm	if (fd >= 0) {
935228753Smm		close(fd);
936228753Smm		fd = -1;
937228753Smm	}
938228753Smm
939228753Smm#ifdef HAVE_LUTIMES
940228753Smm        if (lutimes(name, times) != 0)
941228753Smm#else
942228753Smm        if ((AE_IFLNK != archive_entry_filetype(entry))
943228753Smm			&& utimes(name, times) != 0)
944228753Smm#endif
945228753Smm                lafe_warnc(errno, "Can't update time for %s", name);
946228753Smm#endif
947228753Smm	return (fd);
948228753Smm}
949228753Smm
950228753Smm
951228753Smmstatic void
952228753Smmmode_in(struct cpio *cpio)
953228753Smm{
954228753Smm	struct archive *a;
955228753Smm	struct archive_entry *entry;
956228753Smm	struct archive *ext;
957228753Smm	const char *destpath;
958228753Smm	int r;
959228753Smm
960228753Smm	ext = archive_write_disk_new();
961228753Smm	if (ext == NULL)
962228753Smm		lafe_errc(1, 0, "Couldn't allocate restore object");
963228753Smm	r = archive_write_disk_set_options(ext, cpio->extract_flags);
964228753Smm	if (r != ARCHIVE_OK)
965228753Smm		lafe_errc(1, 0, "%s", archive_error_string(ext));
966228753Smm	a = archive_read_new();
967228753Smm	if (a == NULL)
968228753Smm		lafe_errc(1, 0, "Couldn't allocate archive object");
969232153Smm	archive_read_support_filter_all(a);
970228753Smm	archive_read_support_format_all(a);
971302001Smm	if (cpio->passphrase != NULL)
972302001Smm		r = archive_read_add_passphrase(a, cpio->passphrase);
973302001Smm	else
974302001Smm		r = archive_read_set_passphrase_callback(a, cpio,
975302001Smm			&passphrase_callback);
976302001Smm	if (r != ARCHIVE_OK)
977302001Smm		lafe_errc(1, 0, "%s", archive_error_string(a));
978228753Smm
979248616Smm	if (archive_read_open_filename(a, cpio->filename,
980248616Smm					cpio->bytes_per_block))
981228753Smm		lafe_errc(1, archive_errno(a),
982228753Smm		    "%s", archive_error_string(a));
983228753Smm	for (;;) {
984228753Smm		r = archive_read_next_header(a, &entry);
985228753Smm		if (r == ARCHIVE_EOF)
986228753Smm			break;
987228753Smm		if (r != ARCHIVE_OK) {
988228753Smm			lafe_errc(1, archive_errno(a),
989228753Smm			    "%s", archive_error_string(a));
990228753Smm		}
991238856Smm		if (archive_match_path_excluded(cpio->matching, entry))
992228753Smm			continue;
993228753Smm		if (cpio->option_rename) {
994228753Smm			destpath = cpio_rename(archive_entry_pathname(entry));
995228753Smm			archive_entry_set_pathname(entry, destpath);
996228753Smm		} else
997228753Smm			destpath = archive_entry_pathname(entry);
998228753Smm		if (destpath == NULL)
999228753Smm			continue;
1000228753Smm		if (cpio->verbose)
1001232153Smm			fprintf(stderr, "%s\n", destpath);
1002232153Smm		if (cpio->dot)
1003232153Smm			fprintf(stderr, ".");
1004228753Smm		if (cpio->uid_override >= 0)
1005228753Smm			archive_entry_set_uid(entry, cpio->uid_override);
1006228753Smm		if (cpio->gid_override >= 0)
1007228753Smm			archive_entry_set_gid(entry, cpio->gid_override);
1008228753Smm		r = archive_write_header(ext, entry);
1009228753Smm		if (r != ARCHIVE_OK) {
1010228753Smm			fprintf(stderr, "%s: %s\n",
1011228753Smm			    archive_entry_pathname(entry),
1012228753Smm			    archive_error_string(ext));
1013232153Smm		} else if (!archive_entry_size_is_set(entry)
1014232153Smm		    || archive_entry_size(entry) > 0) {
1015228753Smm			r = extract_data(a, ext);
1016228753Smm			if (r != ARCHIVE_OK)
1017228753Smm				cpio->return_value = 1;
1018228753Smm		}
1019228753Smm	}
1020228753Smm	r = archive_read_close(a);
1021232153Smm	if (cpio->dot)
1022232153Smm		fprintf(stderr, "\n");
1023228753Smm	if (r != ARCHIVE_OK)
1024228753Smm		lafe_errc(1, 0, "%s", archive_error_string(a));
1025228753Smm	r = archive_write_close(ext);
1026228753Smm	if (r != ARCHIVE_OK)
1027228753Smm		lafe_errc(1, 0, "%s", archive_error_string(ext));
1028228753Smm	if (!cpio->quiet) {
1029248616Smm		int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1030228753Smm			      / 512;
1031228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1032228753Smm		    blocks == 1 ? "block" : "blocks");
1033228753Smm	}
1034232153Smm	archive_read_free(a);
1035232153Smm	archive_write_free(ext);
1036228753Smm	exit(cpio->return_value);
1037228753Smm}
1038228753Smm
1039228753Smm/*
1040228753Smm * Exits if there's a fatal error.  Returns ARCHIVE_OK
1041228753Smm * if everything is kosher.
1042228753Smm */
1043228753Smmstatic int
1044228753Smmextract_data(struct archive *ar, struct archive *aw)
1045228753Smm{
1046228753Smm	int r;
1047228753Smm	size_t size;
1048228753Smm	const void *block;
1049232153Smm	int64_t offset;
1050228753Smm
1051228753Smm	for (;;) {
1052228753Smm		r = archive_read_data_block(ar, &block, &size, &offset);
1053228753Smm		if (r == ARCHIVE_EOF)
1054228753Smm			return (ARCHIVE_OK);
1055228753Smm		if (r != ARCHIVE_OK) {
1056228753Smm			lafe_warnc(archive_errno(ar),
1057228753Smm			    "%s", archive_error_string(ar));
1058228753Smm			exit(1);
1059228753Smm		}
1060248616Smm		r = (int)archive_write_data_block(aw, block, size, offset);
1061228753Smm		if (r != ARCHIVE_OK) {
1062228753Smm			lafe_warnc(archive_errno(aw),
1063228753Smm			    "%s", archive_error_string(aw));
1064228753Smm			return (r);
1065228753Smm		}
1066228753Smm	}
1067228753Smm}
1068228753Smm
1069228753Smmstatic void
1070228753Smmmode_list(struct cpio *cpio)
1071228753Smm{
1072228753Smm	struct archive *a;
1073228753Smm	struct archive_entry *entry;
1074228753Smm	int r;
1075228753Smm
1076228753Smm	a = archive_read_new();
1077228753Smm	if (a == NULL)
1078228753Smm		lafe_errc(1, 0, "Couldn't allocate archive object");
1079232153Smm	archive_read_support_filter_all(a);
1080228753Smm	archive_read_support_format_all(a);
1081302001Smm	if (cpio->passphrase != NULL)
1082302001Smm		r = archive_read_add_passphrase(a, cpio->passphrase);
1083302001Smm	else
1084302001Smm		r = archive_read_set_passphrase_callback(a, cpio,
1085302001Smm			&passphrase_callback);
1086302001Smm	if (r != ARCHIVE_OK)
1087302001Smm		lafe_errc(1, 0, "%s", archive_error_string(a));
1088228753Smm
1089248616Smm	if (archive_read_open_filename(a, cpio->filename,
1090248616Smm					cpio->bytes_per_block))
1091228753Smm		lafe_errc(1, archive_errno(a),
1092228753Smm		    "%s", archive_error_string(a));
1093228753Smm	for (;;) {
1094228753Smm		r = archive_read_next_header(a, &entry);
1095228753Smm		if (r == ARCHIVE_EOF)
1096228753Smm			break;
1097228753Smm		if (r != ARCHIVE_OK) {
1098228753Smm			lafe_errc(1, archive_errno(a),
1099228753Smm			    "%s", archive_error_string(a));
1100228753Smm		}
1101238856Smm		if (archive_match_path_excluded(cpio->matching, entry))
1102228753Smm			continue;
1103228753Smm		if (cpio->verbose)
1104228753Smm			list_item_verbose(cpio, entry);
1105228753Smm		else
1106228753Smm			fprintf(stdout, "%s\n", archive_entry_pathname(entry));
1107228753Smm	}
1108228753Smm	r = archive_read_close(a);
1109228753Smm	if (r != ARCHIVE_OK)
1110228753Smm		lafe_errc(1, 0, "%s", archive_error_string(a));
1111228753Smm	if (!cpio->quiet) {
1112248616Smm		int64_t blocks = (archive_filter_bytes(a, 0) + 511)
1113228753Smm			      / 512;
1114228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1115228753Smm		    blocks == 1 ? "block" : "blocks");
1116228753Smm	}
1117232153Smm	archive_read_free(a);
1118228753Smm	exit(0);
1119228753Smm}
1120228753Smm
1121228753Smm/*
1122228753Smm * Display information about the current file.
1123228753Smm *
1124228753Smm * The format here roughly duplicates the output of 'ls -l'.
1125228753Smm * This is based on SUSv2, where 'tar tv' is documented as
1126228753Smm * listing additional information in an "unspecified format,"
1127228753Smm * and 'pax -l' is documented as using the same format as 'ls -l'.
1128228753Smm */
1129228753Smmstatic void
1130228753Smmlist_item_verbose(struct cpio *cpio, struct archive_entry *entry)
1131228753Smm{
1132228753Smm	char			 size[32];
1133228753Smm	char			 date[32];
1134228753Smm	char			 uids[16], gids[16];
1135228753Smm	const char 		*uname, *gname;
1136228753Smm	FILE			*out = stdout;
1137228753Smm	const char		*fmt;
1138228753Smm	time_t			 mtime;
1139228753Smm	static time_t		 now;
1140358090Smm	struct tm		*ltime;
1141358090Smm#if defined(HAVE_LOCALTIME_R) || defined(HAVE__LOCALTIME64_S)
1142358090Smm	struct tm		tmbuf;
1143358090Smm#endif
1144358090Smm#if defined(HAVE__LOCALTIME64_S)
1145358090Smm	errno_t			terr;
1146358090Smm	__time64_t		tmptime;
1147358090Smm#endif
1148228753Smm
1149228753Smm	if (!now)
1150228753Smm		time(&now);
1151228753Smm
1152228753Smm	if (cpio->option_numeric_uid_gid) {
1153228753Smm		/* Format numeric uid/gid for display. */
1154228753Smm		strcpy(uids, cpio_i64toa(archive_entry_uid(entry)));
1155228753Smm		uname = uids;
1156228753Smm		strcpy(gids, cpio_i64toa(archive_entry_gid(entry)));
1157228753Smm		gname = gids;
1158228753Smm	} else {
1159228753Smm		/* Use uname if it's present, else lookup name from uid. */
1160228753Smm		uname = archive_entry_uname(entry);
1161228753Smm		if (uname == NULL)
1162232153Smm			uname = lookup_uname(cpio, (uid_t)archive_entry_uid(entry));
1163228753Smm		/* Use gname if it's present, else lookup name from gid. */
1164228753Smm		gname = archive_entry_gname(entry);
1165228753Smm		if (gname == NULL)
1166232153Smm			gname = lookup_gname(cpio, (uid_t)archive_entry_gid(entry));
1167228753Smm	}
1168228753Smm
1169228753Smm	/* Print device number or file size. */
1170228753Smm	if (archive_entry_filetype(entry) == AE_IFCHR
1171228753Smm	    || archive_entry_filetype(entry) == AE_IFBLK) {
1172228753Smm		snprintf(size, sizeof(size), "%lu,%lu",
1173228753Smm		    (unsigned long)archive_entry_rdevmajor(entry),
1174228753Smm		    (unsigned long)archive_entry_rdevminor(entry));
1175228753Smm	} else {
1176228753Smm		strcpy(size, cpio_i64toa(archive_entry_size(entry)));
1177228753Smm	}
1178228753Smm
1179228753Smm	/* Format the time using 'ls -l' conventions. */
1180228753Smm	mtime = archive_entry_mtime(entry);
1181228753Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1182228753Smm	/* Windows' strftime function does not support %e format. */
1183228753Smm	if (mtime - now > 365*86400/2
1184228753Smm		|| mtime - now < -365*86400/2)
1185228753Smm		fmt = cpio->day_first ? "%d %b  %Y" : "%b %d  %Y";
1186228753Smm	else
1187228753Smm		fmt = cpio->day_first ? "%d %b %H:%M" : "%b %d %H:%M";
1188228753Smm#else
1189275031Sdim	if (mtime - now > 365*86400/2
1190275031Sdim		|| mtime - now < -365*86400/2)
1191228753Smm		fmt = cpio->day_first ? "%e %b  %Y" : "%b %e  %Y";
1192228753Smm	else
1193228753Smm		fmt = cpio->day_first ? "%e %b %H:%M" : "%b %e %H:%M";
1194228753Smm#endif
1195358090Smm#if defined(HAVE_LOCALTIME_R)
1196358090Smm	ltime = localtime_r(&mtime, &tmbuf);
1197358090Smm#elif defined(HAVE__LOCALTIME64_S)
1198358090Smm	tmptime = mtime;
1199358090Smm	terr = _localtime64_s(&tmbuf, &tmptime);
1200358090Smm	if (terr)
1201358090Smm		ltime = NULL;
1202358090Smm	else
1203358090Smm		ltime = &tmbuf;
1204358090Smm#else
1205358090Smm	ltime = localtime(&mtime);
1206358090Smm#endif
1207358090Smm	strftime(date, sizeof(date), fmt, ltime);
1208228753Smm
1209228753Smm	fprintf(out, "%s%3d %-8s %-8s %8s %12s %s",
1210228753Smm	    archive_entry_strmode(entry),
1211228753Smm	    archive_entry_nlink(entry),
1212228753Smm	    uname, gname, size, date,
1213228753Smm	    archive_entry_pathname(entry));
1214228753Smm
1215228753Smm	/* Extra information for links. */
1216228753Smm	if (archive_entry_hardlink(entry)) /* Hard link */
1217228753Smm		fprintf(out, " link to %s", archive_entry_hardlink(entry));
1218228753Smm	else if (archive_entry_symlink(entry)) /* Symbolic link */
1219228753Smm		fprintf(out, " -> %s", archive_entry_symlink(entry));
1220228753Smm	fprintf(out, "\n");
1221228753Smm}
1222228753Smm
1223228753Smmstatic void
1224228753Smmmode_pass(struct cpio *cpio, const char *destdir)
1225228753Smm{
1226228753Smm	struct lafe_line_reader *lr;
1227228753Smm	const char *p;
1228228753Smm	int r;
1229228753Smm
1230228753Smm	/* Ensure target dir has a trailing '/' to simplify path surgery. */
1231358927Smm	cpio->destdir_len = strlen(destdir);
1232358927Smm	cpio->destdir = malloc(cpio->destdir_len + 8);
1233358927Smm	memcpy(cpio->destdir, destdir, cpio->destdir_len);
1234358927Smm	if (cpio->destdir_len == 0 || destdir[cpio->destdir_len - 1] != '/')
1235358927Smm		cpio->destdir[cpio->destdir_len++] = '/';
1236358927Smm	cpio->destdir[cpio->destdir_len] = '\0';
1237228753Smm
1238228753Smm	cpio->archive = archive_write_disk_new();
1239228753Smm	if (cpio->archive == NULL)
1240228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
1241228753Smm	r = archive_write_disk_set_options(cpio->archive, cpio->extract_flags);
1242228753Smm	if (r != ARCHIVE_OK)
1243228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1244228753Smm	cpio->linkresolver = archive_entry_linkresolver_new();
1245228753Smm	archive_write_disk_set_standard_lookup(cpio->archive);
1246228753Smm
1247228753Smm	cpio->archive_read_disk = archive_read_disk_new();
1248228753Smm	if (cpio->archive_read_disk == NULL)
1249228753Smm		lafe_errc(1, 0, "Failed to allocate archive object");
1250228753Smm	if (cpio->option_follow_links)
1251228753Smm		archive_read_disk_set_symlink_logical(cpio->archive_read_disk);
1252228753Smm	else
1253228753Smm		archive_read_disk_set_symlink_physical(cpio->archive_read_disk);
1254228753Smm	archive_read_disk_set_standard_lookup(cpio->archive_read_disk);
1255228753Smm
1256228753Smm	lr = lafe_line_reader("-", cpio->option_null);
1257228753Smm	while ((p = lafe_line_reader_next(lr)) != NULL)
1258228753Smm		file_to_archive(cpio, p);
1259228753Smm	lafe_line_reader_free(lr);
1260228753Smm
1261228753Smm	archive_entry_linkresolver_free(cpio->linkresolver);
1262228753Smm	r = archive_write_close(cpio->archive);
1263232153Smm	if (cpio->dot)
1264232153Smm		fprintf(stderr, "\n");
1265228753Smm	if (r != ARCHIVE_OK)
1266228753Smm		lafe_errc(1, 0, "%s", archive_error_string(cpio->archive));
1267228753Smm
1268228753Smm	if (!cpio->quiet) {
1269228753Smm		int64_t blocks =
1270248616Smm			(archive_filter_bytes(cpio->archive, 0) + 511)
1271228753Smm			/ 512;
1272228753Smm		fprintf(stderr, "%lu %s\n", (unsigned long)blocks,
1273228753Smm		    blocks == 1 ? "block" : "blocks");
1274228753Smm	}
1275228753Smm
1276232153Smm	archive_write_free(cpio->archive);
1277318483Smm	free(cpio->pass_destpath);
1278228753Smm}
1279228753Smm
1280228753Smm/*
1281228753Smm * Prompt for a new name for this entry.  Returns a pointer to the
1282228753Smm * new name or NULL if the entry should not be copied.  This
1283228753Smm * implements the semantics defined in POSIX.1-1996, which specifies
1284228753Smm * that an input of '.' means the name should be unchanged.  GNU cpio
1285228753Smm * treats '.' as a literal new name.
1286228753Smm */
1287228753Smmstatic const char *
1288228753Smmcpio_rename(const char *name)
1289228753Smm{
1290228753Smm	static char buff[1024];
1291228753Smm	FILE *t;
1292228753Smm	char *p, *ret;
1293232153Smm#if defined(_WIN32) && !defined(__CYGWIN__)
1294232153Smm	FILE *to;
1295228753Smm
1296232153Smm	t = fopen("CONIN$", "r");
1297232153Smm	if (t == NULL)
1298232153Smm		return (name);
1299232153Smm	to = fopen("CONOUT$", "w");
1300302001Smm	if (to == NULL) {
1301302001Smm		fclose(t);
1302232153Smm		return (name);
1303302001Smm	}
1304232153Smm	fprintf(to, "%s (Enter/./(new name))? ", name);
1305232153Smm	fclose(to);
1306232153Smm#else
1307228753Smm	t = fopen("/dev/tty", "r+");
1308228753Smm	if (t == NULL)
1309228753Smm		return (name);
1310228753Smm	fprintf(t, "%s (Enter/./(new name))? ", name);
1311228753Smm	fflush(t);
1312232153Smm#endif
1313228753Smm
1314228753Smm	p = fgets(buff, sizeof(buff), t);
1315228753Smm	fclose(t);
1316228753Smm	if (p == NULL)
1317228753Smm		/* End-of-file is a blank line. */
1318228753Smm		return (NULL);
1319228753Smm
1320228753Smm	while (*p == ' ' || *p == '\t')
1321228753Smm		++p;
1322228753Smm	if (*p == '\n' || *p == '\0')
1323228753Smm		/* Empty line. */
1324228753Smm		return (NULL);
1325228753Smm	if (*p == '.' && p[1] == '\n')
1326228753Smm		/* Single period preserves original name. */
1327228753Smm		return (name);
1328228753Smm	ret = p;
1329228753Smm	/* Trim the final newline. */
1330228753Smm	while (*p != '\0' && *p != '\n')
1331228753Smm		++p;
1332228753Smm	/* Overwrite the final \n with a null character. */
1333228753Smm	*p = '\0';
1334228753Smm	return (ret);
1335228753Smm}
1336228753Smm
1337228753Smmstatic void
1338228753Smmfree_cache(struct name_cache *cache)
1339228753Smm{
1340228753Smm	size_t i;
1341228753Smm
1342228753Smm	if (cache != NULL) {
1343228753Smm		for (i = 0; i < cache->size; i++)
1344228753Smm			free(cache->cache[i].name);
1345228753Smm		free(cache);
1346228753Smm	}
1347228753Smm}
1348228753Smm
1349228753Smm/*
1350228753Smm * Lookup uname/gname from uid/gid, return NULL if no match.
1351228753Smm */
1352228753Smmstatic const char *
1353228753Smmlookup_name(struct cpio *cpio, struct name_cache **name_cache_variable,
1354228753Smm    int (*lookup_fn)(struct cpio *, const char **, id_t), id_t id)
1355228753Smm{
1356228753Smm	char asnum[16];
1357228753Smm	struct name_cache	*cache;
1358228753Smm	const char *name;
1359228753Smm	int slot;
1360228753Smm
1361228753Smm
1362228753Smm	if (*name_cache_variable == NULL) {
1363311042Smm		*name_cache_variable = calloc(1, sizeof(struct name_cache));
1364228753Smm		if (*name_cache_variable == NULL)
1365228753Smm			lafe_errc(1, ENOMEM, "No more memory");
1366228753Smm		(*name_cache_variable)->size = name_cache_size;
1367228753Smm	}
1368228753Smm
1369228753Smm	cache = *name_cache_variable;
1370228753Smm	cache->probes++;
1371228753Smm
1372228753Smm	slot = id % cache->size;
1373228753Smm	if (cache->cache[slot].name != NULL) {
1374228753Smm		if (cache->cache[slot].id == id) {
1375228753Smm			cache->hits++;
1376228753Smm			return (cache->cache[slot].name);
1377228753Smm		}
1378228753Smm		free(cache->cache[slot].name);
1379228753Smm		cache->cache[slot].name = NULL;
1380228753Smm	}
1381228753Smm
1382316338Smm	if (lookup_fn(cpio, &name, id)) {
1383316338Smm		/* If lookup failed, format it as a number. */
1384316338Smm		snprintf(asnum, sizeof(asnum), "%u", (unsigned)id);
1385316338Smm		name = asnum;
1386228753Smm	}
1387316338Smm
1388316338Smm	cache->cache[slot].name = strdup(name);
1389316338Smm	if (cache->cache[slot].name != NULL) {
1390316338Smm		cache->cache[slot].id = id;
1391316338Smm		return (cache->cache[slot].name);
1392316338Smm	}
1393316338Smm
1394316338Smm	/*
1395316338Smm	 * Conveniently, NULL marks an empty slot, so
1396316338Smm	 * if the strdup() fails, we've just failed to
1397316338Smm	 * cache it.  No recovery necessary.
1398316338Smm	 */
1399228753Smm	return (NULL);
1400228753Smm}
1401228753Smm
1402228753Smmstatic const char *
1403228753Smmlookup_uname(struct cpio *cpio, uid_t uid)
1404228753Smm{
1405228753Smm	return (lookup_name(cpio, &cpio->uname_cache,
1406228753Smm		    &lookup_uname_helper, (id_t)uid));
1407228753Smm}
1408228753Smm
1409228753Smmstatic int
1410228753Smmlookup_uname_helper(struct cpio *cpio, const char **name, id_t id)
1411228753Smm{
1412228753Smm	struct passwd	*pwent;
1413228753Smm
1414228753Smm	(void)cpio; /* UNUSED */
1415228753Smm
1416228753Smm	errno = 0;
1417228753Smm	pwent = getpwuid((uid_t)id);
1418228753Smm	if (pwent == NULL) {
1419316338Smm		if (errno && errno != ENOENT)
1420238856Smm			lafe_warnc(errno, "getpwuid(%s) failed",
1421238856Smm			    cpio_i64toa((int64_t)id));
1422316338Smm		return 1;
1423228753Smm	}
1424228753Smm
1425228753Smm	*name = pwent->pw_name;
1426316338Smm	return 0;
1427228753Smm}
1428228753Smm
1429228753Smmstatic const char *
1430228753Smmlookup_gname(struct cpio *cpio, gid_t gid)
1431228753Smm{
1432228753Smm	return (lookup_name(cpio, &cpio->gname_cache,
1433228753Smm		    &lookup_gname_helper, (id_t)gid));
1434228753Smm}
1435228753Smm
1436228753Smmstatic int
1437228753Smmlookup_gname_helper(struct cpio *cpio, const char **name, id_t id)
1438228753Smm{
1439228753Smm	struct group	*grent;
1440228753Smm
1441228753Smm	(void)cpio; /* UNUSED */
1442228753Smm
1443228753Smm	errno = 0;
1444228753Smm	grent = getgrgid((gid_t)id);
1445228753Smm	if (grent == NULL) {
1446316338Smm		if (errno && errno != ENOENT)
1447238856Smm			lafe_warnc(errno, "getgrgid(%s) failed",
1448238856Smm			    cpio_i64toa((int64_t)id));
1449316338Smm		return 1;
1450228753Smm	}
1451228753Smm
1452228753Smm	*name = grent->gr_name;
1453316338Smm	return 0;
1454228753Smm}
1455228753Smm
1456228753Smm/*
1457228753Smm * It would be nice to just use printf() for formatting large numbers,
1458228753Smm * but the compatibility problems are a big headache.  Hence the
1459228753Smm * following simple utility function.
1460228753Smm */
1461228753Smmconst char *
1462228753Smmcpio_i64toa(int64_t n0)
1463228753Smm{
1464232153Smm	/* 2^64 =~ 1.8 * 10^19, so 20 decimal digits suffice.
1465232153Smm	 * We also need 1 byte for '-' and 1 for '\0'.
1466232153Smm	 */
1467228753Smm	static char buff[22];
1468228753Smm	int64_t n = n0 < 0 ? -n0 : n0;
1469228753Smm	char *p = buff + sizeof(buff);
1470228753Smm
1471228753Smm	*--p = '\0';
1472228753Smm	do {
1473228753Smm		*--p = '0' + (int)(n % 10);
1474228753Smm		n /= 10;
1475228753Smm	} while (n > 0);
1476228753Smm	if (n0 < 0)
1477228753Smm		*--p = '-';
1478228753Smm	return p;
1479228753Smm}
1480302001Smm
1481302001Smm#define PPBUFF_SIZE 1024
1482302001Smmstatic const char *
1483302001Smmpassphrase_callback(struct archive *a, void *_client_data)
1484302001Smm{
1485302001Smm	struct cpio *cpio = (struct cpio *)_client_data;
1486302001Smm	(void)a; /* UNUSED */
1487302001Smm
1488302001Smm	if (cpio->ppbuff == NULL) {
1489302001Smm		cpio->ppbuff = malloc(PPBUFF_SIZE);
1490302001Smm		if (cpio->ppbuff == NULL)
1491302001Smm			lafe_errc(1, errno, "Out of memory");
1492302001Smm	}
1493302001Smm	return lafe_readpassphrase("Enter passphrase:",
1494302001Smm		cpio->ppbuff, PPBUFF_SIZE);
1495302001Smm}
1496302001Smm
1497302001Smmstatic void
1498302001Smmpassphrase_free(char *ppbuff)
1499302001Smm{
1500302001Smm	if (ppbuff != NULL) {
1501302001Smm		memset(ppbuff, 0, PPBUFF_SIZE);
1502302001Smm		free(ppbuff);
1503302001Smm	}
1504302001Smm}
1505