xref: /freebsd/contrib/libarchive/tar/write.c (revision e8d8bef961a50d4dc22501cde4fb9fb0be1b2532)
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * Copyright (c) 2012 Michihiro NAKAJIMA
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
16  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
17  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
18  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
19  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
20  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
21  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26 
27 #include "bsdtar_platform.h"
28 __FBSDID("$FreeBSD$");
29 
30 #ifdef HAVE_SYS_TYPES_H
31 #include <sys/types.h>
32 #endif
33 #ifdef HAVE_SYS_STAT_H
34 #include <sys/stat.h>
35 #endif
36 #ifdef HAVE_ATTR_XATTR_H
37 #include <attr/xattr.h>
38 #endif
39 #ifdef HAVE_ERRNO_H
40 #include <errno.h>
41 #endif
42 #ifdef HAVE_FCNTL_H
43 #include <fcntl.h>
44 #endif
45 #ifdef HAVE_GRP_H
46 #include <grp.h>
47 #endif
48 #ifdef HAVE_IO_H
49 #include <io.h>
50 #endif
51 #ifdef HAVE_LIBGEN_H
52 #include <libgen.h>
53 #endif
54 #ifdef HAVE_LIMITS_H
55 #include <limits.h>
56 #endif
57 #ifdef HAVE_PATHS_H
58 #include <paths.h>
59 #endif
60 #ifdef HAVE_PWD_H
61 #include <pwd.h>
62 #endif
63 #ifdef HAVE_STDINT_H
64 #include <stdint.h>
65 #endif
66 #include <stdio.h>
67 #ifdef HAVE_STDLIB_H
68 #include <stdlib.h>
69 #endif
70 #ifdef HAVE_STRING_H
71 #include <string.h>
72 #endif
73 #ifdef HAVE_UNISTD_H
74 #include <unistd.h>
75 #endif
76 
77 #include "bsdtar.h"
78 #include "err.h"
79 #include "line_reader.h"
80 
81 #ifndef O_BINARY
82 #define	O_BINARY 0
83 #endif
84 
85 struct archive_dir_entry {
86 	struct archive_dir_entry	*next;
87 	time_t			 mtime_sec;
88 	int			 mtime_nsec;
89 	char			*name;
90 };
91 
92 struct archive_dir {
93 	struct archive_dir_entry *head, *tail;
94 };
95 
96 static int		 append_archive(struct bsdtar *, struct archive *,
97 			     struct archive *ina);
98 static int		 append_archive_filename(struct bsdtar *,
99 			     struct archive *, const char *fname);
100 static void		 archive_names_from_file(struct bsdtar *bsdtar,
101 			     struct archive *a);
102 static int		 copy_file_data_block(struct bsdtar *,
103 			     struct archive *a, struct archive *,
104 			     struct archive_entry *);
105 static void		 excluded_callback(struct archive *, void *,
106 			     struct archive_entry *);
107 static void		 report_write(struct bsdtar *, struct archive *,
108 			     struct archive_entry *, int64_t progress);
109 static void		 test_for_append(struct bsdtar *);
110 static int		 metadata_filter(struct archive *, void *,
111 			     struct archive_entry *);
112 static void		 write_archive(struct archive *, struct bsdtar *);
113 static void		 write_entry(struct bsdtar *, struct archive *,
114 			     struct archive_entry *);
115 static void		 write_file(struct bsdtar *, struct archive *,
116 			     struct archive_entry *);
117 static void		 write_hierarchy(struct bsdtar *, struct archive *,
118 			     const char *);
119 
120 #if defined(_WIN32) && !defined(__CYGWIN__)
121 /* Not a full lseek() emulation, but enough for our needs here. */
122 static int
123 seek_file(int fd, int64_t offset, int whence)
124 {
125 	LARGE_INTEGER distance;
126 	(void)whence; /* UNUSED */
127 	distance.QuadPart = offset;
128 	return (SetFilePointerEx((HANDLE)_get_osfhandle(fd),
129 		distance, NULL, FILE_BEGIN) ? 1 : -1);
130 }
131 #define	open _open
132 #define	close _close
133 #define	read _read
134 #ifdef lseek
135 #undef lseek
136 #endif
137 #define	lseek seek_file
138 #endif
139 
140 static void
141 set_writer_options(struct bsdtar *bsdtar, struct archive *a)
142 {
143 	const char *writer_options;
144 	int r;
145 
146 	writer_options = getenv(ENV_WRITER_OPTIONS);
147 	if (writer_options != NULL) {
148 		size_t module_len = sizeof(IGNORE_WRONG_MODULE_NAME) - 1;
149 		size_t opt_len = strlen(writer_options) + 1;
150 		char *p;
151 		/* Set default write options. */
152 		if ((p = malloc(module_len + opt_len)) == NULL)
153 			lafe_errc(1, errno, "Out of memory");
154 		/* Prepend magic code to ignore options for
155 		 * a format or filters which are not added to
156 		 * the archive write object. */
157 		memcpy(p, IGNORE_WRONG_MODULE_NAME, module_len);
158 		memcpy(p, writer_options, opt_len);
159 		r = archive_write_set_options(a, p);
160 		free(p);
161 		if (r < ARCHIVE_WARN)
162 			lafe_errc(1, 0, "%s", archive_error_string(a));
163 		else
164 			archive_clear_error(a);
165 	}
166 	if (ARCHIVE_OK != archive_write_set_options(a, bsdtar->option_options))
167 		lafe_errc(1, 0, "%s", archive_error_string(a));
168 }
169 
170 static void
171 set_reader_options(struct bsdtar *bsdtar, struct archive *a)
172 {
173 	const char *reader_options;
174 	int r;
175 
176 	(void)bsdtar; /* UNUSED */
177 
178 	reader_options = getenv(ENV_READER_OPTIONS);
179 	if (reader_options != NULL) {
180 		size_t module_len = sizeof(IGNORE_WRONG_MODULE_NAME) - 1;
181 		size_t opt_len = strlen(reader_options) + 1;
182 		char *p;
183 		/* Set default write options. */
184 		if ((p = malloc(module_len + opt_len)) == NULL)
185 		if (p == NULL)
186 			lafe_errc(1, errno, "Out of memory");
187 		/* Prepend magic code to ignore options for
188 		 * a format or filters which are not added to
189 		 * the archive write object. */
190 		memcpy(p, IGNORE_WRONG_MODULE_NAME, module_len);
191 		memcpy(p, reader_options, opt_len);
192 		r = archive_read_set_options(a, p);
193 		free(p);
194 		if (r < ARCHIVE_WARN)
195 			lafe_errc(1, 0, "%s", archive_error_string(a));
196 		else
197 			archive_clear_error(a);
198 	}
199 }
200 
201 void
202 tar_mode_c(struct bsdtar *bsdtar)
203 {
204 	struct archive *a;
205 	const void *filter_name;
206 	int r;
207 
208 	if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
209 		lafe_errc(1, 0, "no files or directories specified");
210 
211 	a = archive_write_new();
212 
213 	/* Support any format that the library supports. */
214 	if (cset_get_format(bsdtar->cset) == NULL) {
215 		r = archive_write_set_format_pax_restricted(a);
216 		cset_set_format(bsdtar->cset, "pax restricted");
217 	} else {
218 		r = archive_write_set_format_by_name(a,
219 			cset_get_format(bsdtar->cset));
220 	}
221 	if (r != ARCHIVE_OK) {
222 		fprintf(stderr, "Can't use format %s: %s\n",
223 		    cset_get_format(bsdtar->cset),
224 		    archive_error_string(a));
225 		usage();
226 	}
227 
228 	archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
229 	archive_write_set_bytes_in_last_block(a, bsdtar->bytes_in_last_block);
230 
231 	r = cset_write_add_filters(bsdtar->cset, a, &filter_name);
232 	if (r < ARCHIVE_WARN) {
233 		lafe_errc(1, 0, "Unsupported compression option --%s",
234 		    (const char *)filter_name);
235 	}
236 
237 	set_writer_options(bsdtar, a);
238 	if (bsdtar->passphrase != NULL)
239 		r = archive_write_set_passphrase(a, bsdtar->passphrase);
240 	else
241 		r = archive_write_set_passphrase_callback(a, bsdtar,
242 			&passphrase_callback);
243 	if (r != ARCHIVE_OK)
244 		lafe_errc(1, 0, "%s", archive_error_string(a));
245 	if (ARCHIVE_OK != archive_write_open_filename(a, bsdtar->filename))
246 		lafe_errc(1, 0, "%s", archive_error_string(a));
247 	write_archive(a, bsdtar);
248 }
249 
250 /*
251  * Same as 'c', except we only support tar or empty formats in
252  * uncompressed files on disk.
253  */
254 void
255 tar_mode_r(struct bsdtar *bsdtar)
256 {
257 	int64_t	end_offset;
258 	int	format;
259 	struct archive *a;
260 	struct archive_entry *entry;
261 	int	r;
262 
263 	/* Sanity-test some arguments and the file. */
264 	test_for_append(bsdtar);
265 
266 	format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
267 
268 #if defined(__BORLANDC__)
269 	bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT | O_BINARY);
270 #else
271 	bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT | O_BINARY, 0666);
272 #endif
273 	if (bsdtar->fd < 0)
274 		lafe_errc(1, errno,
275 		    "Cannot open %s", bsdtar->filename);
276 
277 	a = archive_read_new();
278 	archive_read_support_filter_all(a);
279 	archive_read_support_format_empty(a);
280 	archive_read_support_format_tar(a);
281 	archive_read_support_format_gnutar(a);
282 	set_reader_options(bsdtar, a);
283 	r = archive_read_open_fd(a, bsdtar->fd, 10240);
284 	if (r != ARCHIVE_OK)
285 		lafe_errc(1, archive_errno(a),
286 		    "Can't read archive %s: %s", bsdtar->filename,
287 		    archive_error_string(a));
288 	while (0 == archive_read_next_header(a, &entry)) {
289 		if (archive_filter_code(a, 0) != ARCHIVE_FILTER_NONE) {
290 			archive_read_free(a);
291 			close(bsdtar->fd);
292 			lafe_errc(1, 0,
293 			    "Cannot append to compressed archive.");
294 		}
295 		/* Keep going until we hit end-of-archive */
296 		format = archive_format(a);
297 	}
298 
299 	end_offset = archive_read_header_position(a);
300 	archive_read_free(a);
301 
302 	/* Re-open archive for writing */
303 	a = archive_write_new();
304 	/*
305 	 * Set the format to be used for writing.  To allow people to
306 	 * extend empty files, we need to allow them to specify the format,
307 	 * which opens the possibility that they will specify a format that
308 	 * doesn't match the existing format.  Hence, the following bit
309 	 * of arcane ugliness.
310 	 */
311 
312 	if (cset_get_format(bsdtar->cset) != NULL) {
313 		/* If the user requested a format, use that, but ... */
314 		archive_write_set_format_by_name(a,
315 		    cset_get_format(bsdtar->cset));
316 		/* ... complain if it's not compatible. */
317 		format &= ARCHIVE_FORMAT_BASE_MASK;
318 		if (format != (int)(archive_format(a) & ARCHIVE_FORMAT_BASE_MASK)
319 		    && format != ARCHIVE_FORMAT_EMPTY) {
320 			lafe_errc(1, 0,
321 			    "Format %s is incompatible with the archive %s.",
322 			    cset_get_format(bsdtar->cset), bsdtar->filename);
323 		}
324 	} else {
325 		/*
326 		 * Just preserve the current format, with a little care
327 		 * for formats that libarchive can't write.
328 		 */
329 		if (format == ARCHIVE_FORMAT_EMPTY)
330 			format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
331 		archive_write_set_format(a, format);
332 	}
333 	if (lseek(bsdtar->fd, end_offset, SEEK_SET) < 0)
334 		lafe_errc(1, errno, "Could not seek to archive end");
335 	set_writer_options(bsdtar, a);
336 	if (ARCHIVE_OK != archive_write_open_fd(a, bsdtar->fd))
337 		lafe_errc(1, 0, "%s", archive_error_string(a));
338 
339 	write_archive(a, bsdtar); /* XXX check return val XXX */
340 
341 	close(bsdtar->fd);
342 	bsdtar->fd = -1;
343 }
344 
345 void
346 tar_mode_u(struct bsdtar *bsdtar)
347 {
348 	int64_t			 end_offset;
349 	struct archive		*a;
350 	struct archive_entry	*entry;
351 	int			 format;
352 	struct archive_dir_entry	*p;
353 	struct archive_dir	 archive_dir;
354 
355 	bsdtar->archive_dir = &archive_dir;
356 	memset(&archive_dir, 0, sizeof(archive_dir));
357 
358 	format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
359 
360 	/* Sanity-test some arguments and the file. */
361 	test_for_append(bsdtar);
362 
363 	bsdtar->fd = open(bsdtar->filename, O_RDWR | O_BINARY);
364 	if (bsdtar->fd < 0)
365 		lafe_errc(1, errno,
366 		    "Cannot open %s", bsdtar->filename);
367 
368 	a = archive_read_new();
369 	archive_read_support_filter_all(a);
370 	archive_read_support_format_tar(a);
371 	archive_read_support_format_gnutar(a);
372 	set_reader_options(bsdtar, a);
373 	if (archive_read_open_fd(a, bsdtar->fd, bsdtar->bytes_per_block)
374 	    != ARCHIVE_OK) {
375 		lafe_errc(1, 0,
376 		    "Can't open %s: %s", bsdtar->filename,
377 		    archive_error_string(a));
378 	}
379 
380 	/* Build a list of all entries and their recorded mod times. */
381 	while (0 == archive_read_next_header(a, &entry)) {
382 		if (archive_filter_code(a, 0) != ARCHIVE_FILTER_NONE) {
383 			archive_read_free(a);
384 			close(bsdtar->fd);
385 			lafe_errc(1, 0,
386 			    "Cannot append to compressed archive.");
387 		}
388 		if (archive_match_exclude_entry(bsdtar->matching,
389 		    ARCHIVE_MATCH_MTIME | ARCHIVE_MATCH_OLDER |
390 		    ARCHIVE_MATCH_EQUAL, entry) != ARCHIVE_OK)
391 			lafe_errc(1, 0, "Error : %s",
392 			    archive_error_string(bsdtar->matching));
393 		/* Record the last format determination we see */
394 		format = archive_format(a);
395 		/* Keep going until we hit end-of-archive */
396 	}
397 
398 	end_offset = archive_read_header_position(a);
399 	archive_read_free(a);
400 
401 	/* Re-open archive for writing. */
402 	a = archive_write_new();
403 	/*
404 	 * Set format to same one auto-detected above.
405 	 */
406 	archive_write_set_format(a, format);
407 	archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
408 	archive_write_set_bytes_in_last_block(a, bsdtar->bytes_in_last_block);
409 
410 	if (lseek(bsdtar->fd, end_offset, SEEK_SET) < 0)
411 		lafe_errc(1, errno, "Could not seek to archive end");
412 	set_writer_options(bsdtar, a);
413 	if (ARCHIVE_OK != archive_write_open_fd(a, bsdtar->fd))
414 		lafe_errc(1, 0, "%s", archive_error_string(a));
415 
416 	write_archive(a, bsdtar);
417 
418 	close(bsdtar->fd);
419 	bsdtar->fd = -1;
420 
421 	while (bsdtar->archive_dir->head != NULL) {
422 		p = bsdtar->archive_dir->head->next;
423 		free(bsdtar->archive_dir->head->name);
424 		free(bsdtar->archive_dir->head);
425 		bsdtar->archive_dir->head = p;
426 	}
427 	bsdtar->archive_dir->tail = NULL;
428 }
429 
430 
431 /*
432  * Write user-specified files/dirs to opened archive.
433  */
434 static void
435 write_archive(struct archive *a, struct bsdtar *bsdtar)
436 {
437 	const char *arg;
438 	struct archive_entry *entry, *sparse_entry;
439 
440 	/* Choose a suitable copy buffer size */
441 	bsdtar->buff_size = 64 * 1024;
442 	while (bsdtar->buff_size < (size_t)bsdtar->bytes_per_block)
443 	  bsdtar->buff_size *= 2;
444 	/* Try to compensate for space we'll lose to alignment. */
445 	bsdtar->buff_size += 16 * 1024;
446 
447 	/* Allocate a buffer for file data. */
448 	if ((bsdtar->buff = malloc(bsdtar->buff_size)) == NULL)
449 		lafe_errc(1, 0, "cannot allocate memory");
450 
451 	if ((bsdtar->resolver = archive_entry_linkresolver_new()) == NULL)
452 		lafe_errc(1, 0, "cannot create link resolver");
453 	archive_entry_linkresolver_set_strategy(bsdtar->resolver,
454 	    archive_format(a));
455 
456 	/* Create a read_disk object. */
457 	if ((bsdtar->diskreader = archive_read_disk_new()) == NULL)
458 		lafe_errc(1, 0, "Cannot create read_disk object");
459 	/* Tell the read_disk how handle symlink. */
460 	switch (bsdtar->symlink_mode) {
461 	case 'H':
462 		archive_read_disk_set_symlink_hybrid(bsdtar->diskreader);
463 		break;
464 	case 'L':
465 		archive_read_disk_set_symlink_logical(bsdtar->diskreader);
466 		break;
467 	default:
468 		archive_read_disk_set_symlink_physical(bsdtar->diskreader);
469 		break;
470 	}
471 	/* Register entry filters. */
472 	archive_read_disk_set_matching(bsdtar->diskreader,
473 	    bsdtar->matching, excluded_callback, bsdtar);
474 	archive_read_disk_set_metadata_filter_callback(
475 	    bsdtar->diskreader, metadata_filter, bsdtar);
476 	/* Set the behavior of archive_read_disk. */
477 	archive_read_disk_set_behavior(bsdtar->diskreader,
478 	    bsdtar->readdisk_flags);
479 	archive_read_disk_set_standard_lookup(bsdtar->diskreader);
480 
481 	if (bsdtar->names_from_file != NULL)
482 		archive_names_from_file(bsdtar, a);
483 
484 	while (*bsdtar->argv) {
485 		arg = *bsdtar->argv;
486 		if (arg[0] == '-' && arg[1] == 'C') {
487 			arg += 2;
488 			if (*arg == '\0') {
489 				bsdtar->argv++;
490 				arg = *bsdtar->argv;
491 				if (arg == NULL) {
492 					lafe_warnc(0, "%s",
493 					    "Missing argument for -C");
494 					bsdtar->return_value = 1;
495 					goto cleanup;
496 				}
497 				if (*arg == '\0') {
498 					lafe_warnc(0,
499 					    "Meaningless argument for -C: ''");
500 					bsdtar->return_value = 1;
501 					goto cleanup;
502 				}
503 			}
504 			set_chdir(bsdtar, arg);
505 		} else {
506 			if (*arg != '/')
507 				do_chdir(bsdtar); /* Handle a deferred -C */
508 			if (*arg == '@') {
509 				if (append_archive_filename(bsdtar, a,
510 				    arg + 1) != 0)
511 					break;
512 			} else
513 				write_hierarchy(bsdtar, a, arg);
514 		}
515 		bsdtar->argv++;
516 	}
517 
518 	archive_read_disk_set_matching(bsdtar->diskreader, NULL, NULL, NULL);
519 	archive_read_disk_set_metadata_filter_callback(
520 	    bsdtar->diskreader, NULL, NULL);
521 	entry = NULL;
522 	archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
523 	while (entry != NULL) {
524 		int r;
525 		struct archive_entry *entry2;
526 		struct archive *disk = bsdtar->diskreader;
527 
528 		/*
529 		 * This tricky code here is to correctly read the contents
530 		 * of the entry because the disk reader bsdtar->diskreader
531 		 * is pointing at does not have any information about the
532 		 * entry by this time and using archive_read_data_block()
533 		 * with the disk reader consequently must fail. And we
534 		 * have to re-open the entry to read the contents.
535 		 */
536 		/* TODO: Work with -C option as well. */
537 		r = archive_read_disk_open(disk,
538 			archive_entry_sourcepath(entry));
539 		if (r != ARCHIVE_OK) {
540 			lafe_warnc(archive_errno(disk),
541 			    "%s", archive_error_string(disk));
542 			bsdtar->return_value = 1;
543 			goto next_entry;
544 		}
545 
546 		/*
547 		 * Invoke archive_read_next_header2() to work
548 		 * archive_read_data_block(), which is called via write_file(),
549 		 * without failure.
550 		 */
551 		entry2 = archive_entry_new();
552 		r = archive_read_next_header2(disk, entry2);
553 		archive_entry_free(entry2);
554 		if (r != ARCHIVE_OK) {
555 			lafe_warnc(archive_errno(disk),
556 			    "%s", archive_error_string(disk));
557 			if (r == ARCHIVE_FATAL)
558 				bsdtar->return_value = 1;
559 			archive_read_close(disk);
560 			goto next_entry;
561 		}
562 
563 		write_file(bsdtar, a, entry);
564 		archive_read_close(disk);
565 next_entry:
566 		archive_entry_free(entry);
567 		entry = NULL;
568 		archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
569 	}
570 
571 	if (archive_write_close(a)) {
572 		lafe_warnc(0, "%s", archive_error_string(a));
573 		bsdtar->return_value = 1;
574 	}
575 
576 cleanup:
577 	/* Free file data buffer. */
578 	free(bsdtar->buff);
579 	archive_entry_linkresolver_free(bsdtar->resolver);
580 	bsdtar->resolver = NULL;
581 	archive_read_free(bsdtar->diskreader);
582 	bsdtar->diskreader = NULL;
583 
584 	if (bsdtar->flags & OPTFLAG_TOTALS) {
585 		fprintf(stderr, "Total bytes written: %s\n",
586 		    tar_i64toa(archive_filter_bytes(a, -1)));
587 	}
588 
589 	archive_write_free(a);
590 }
591 
592 /*
593  * Archive names specified in file.
594  *
595  * Unless --null was specified, a line containing exactly "-C" will
596  * cause the next line to be a directory to pass to chdir().  If
597  * --null is specified, then a line "-C" is just another filename.
598  */
599 static void
600 archive_names_from_file(struct bsdtar *bsdtar, struct archive *a)
601 {
602 	struct lafe_line_reader *lr;
603 	const char *line;
604 
605 	bsdtar->next_line_is_dir = 0;
606 
607 	lr = lafe_line_reader(bsdtar->names_from_file,
608 	    (bsdtar->flags & OPTFLAG_NULL));
609 	while ((line = lafe_line_reader_next(lr)) != NULL) {
610 		if (bsdtar->next_line_is_dir) {
611 			if (*line != '\0')
612 				set_chdir(bsdtar, line);
613 			else {
614 				lafe_warnc(0,
615 				    "Meaningless argument for -C: ''");
616 				bsdtar->return_value = 1;
617 			}
618 			bsdtar->next_line_is_dir = 0;
619 		} else if (((bsdtar->flags & OPTFLAG_NULL) == 0) &&
620 		    strcmp(line, "-C") == 0)
621 			bsdtar->next_line_is_dir = 1;
622 		else {
623 			if (*line != '/')
624 				do_chdir(bsdtar); /* Handle a deferred -C */
625 			write_hierarchy(bsdtar, a, line);
626 		}
627 	}
628 	lafe_line_reader_free(lr);
629 	if (bsdtar->next_line_is_dir)
630 		lafe_errc(1, errno,
631 		    "Unexpected end of filename list; "
632 		    "directory expected after -C");
633 }
634 
635 /*
636  * Copy from specified archive to current archive.  Returns non-zero
637  * for write errors (which force us to terminate the entire archiving
638  * operation).  If there are errors reading the input archive, we set
639  * bsdtar->return_value but return zero, so the overall archiving
640  * operation will complete and return non-zero.
641  */
642 static int
643 append_archive_filename(struct bsdtar *bsdtar, struct archive *a,
644     const char *raw_filename)
645 {
646 	struct archive *ina;
647 	const char *filename = raw_filename;
648 	int rc;
649 
650 	if (strcmp(filename, "-") == 0)
651 		filename = NULL; /* Library uses NULL for stdio. */
652 
653 	ina = archive_read_new();
654 	archive_read_support_format_all(ina);
655 	archive_read_support_filter_all(ina);
656 	set_reader_options(bsdtar, ina);
657 	archive_read_set_options(ina, "mtree:checkfs");
658 	if (bsdtar->passphrase != NULL)
659 		rc = archive_read_add_passphrase(a, bsdtar->passphrase);
660 	else
661 		rc = archive_read_set_passphrase_callback(ina, bsdtar,
662 			&passphrase_callback);
663 	if (rc != ARCHIVE_OK)
664 		lafe_errc(1, 0, "%s", archive_error_string(a));
665 	if (archive_read_open_filename(ina, filename,
666 					bsdtar->bytes_per_block)) {
667 		lafe_warnc(0, "%s", archive_error_string(ina));
668 		bsdtar->return_value = 1;
669 		return (0);
670 	}
671 
672 	rc = append_archive(bsdtar, a, ina);
673 
674 	if (rc != ARCHIVE_OK) {
675 		lafe_warnc(0, "Error reading archive %s: %s",
676 		    raw_filename, archive_error_string(ina));
677 		bsdtar->return_value = 1;
678 	}
679 	archive_read_free(ina);
680 
681 	return (rc);
682 }
683 
684 static int
685 append_archive(struct bsdtar *bsdtar, struct archive *a, struct archive *ina)
686 {
687 	struct archive_entry *in_entry;
688 	int e;
689 
690 	while (ARCHIVE_OK == (e = archive_read_next_header(ina, &in_entry))) {
691 		if (archive_match_excluded(bsdtar->matching, in_entry))
692 			continue;
693 		if ((bsdtar->flags & OPTFLAG_INTERACTIVE) &&
694 		    !yes("copy '%s'", archive_entry_pathname(in_entry)))
695 			continue;
696 		if (bsdtar->verbose > 1) {
697 			safe_fprintf(stderr, "a ");
698 			list_item_verbose(bsdtar, stderr, in_entry);
699 		} else if (bsdtar->verbose > 0)
700 			safe_fprintf(stderr, "a %s",
701 			    archive_entry_pathname(in_entry));
702 		if (need_report())
703 			report_write(bsdtar, a, in_entry, 0);
704 
705 		e = archive_write_header(a, in_entry);
706 		if (e != ARCHIVE_OK) {
707 			if (!bsdtar->verbose)
708 				lafe_warnc(0, "%s: %s",
709 				    archive_entry_pathname(in_entry),
710 				    archive_error_string(a));
711 			else
712 				fprintf(stderr, ": %s", archive_error_string(a));
713 		}
714 		if (e == ARCHIVE_FATAL)
715 			exit(1);
716 
717 		if (e >= ARCHIVE_WARN) {
718 			if (archive_entry_size(in_entry) == 0)
719 				archive_read_data_skip(ina);
720 			else if (copy_file_data_block(bsdtar, a, ina, in_entry))
721 				exit(1);
722 		}
723 
724 		if (bsdtar->verbose)
725 			fprintf(stderr, "\n");
726 	}
727 
728 	return (e == ARCHIVE_EOF ? ARCHIVE_OK : e);
729 }
730 
731 /* Helper function to copy file to archive. */
732 static int
733 copy_file_data_block(struct bsdtar *bsdtar, struct archive *a,
734     struct archive *in_a, struct archive_entry *entry)
735 {
736 	size_t	bytes_read;
737 	ssize_t	bytes_written;
738 	int64_t	offset, progress = 0;
739 	char *null_buff = NULL;
740 	const void *buff;
741 	int r;
742 
743 	while ((r = archive_read_data_block(in_a, &buff,
744 	    &bytes_read, &offset)) == ARCHIVE_OK) {
745 		if (need_report())
746 			report_write(bsdtar, a, entry, progress);
747 
748 		if (offset > progress) {
749 			int64_t sparse = offset - progress;
750 			size_t ns;
751 
752 			if (null_buff == NULL) {
753 				null_buff = bsdtar->buff;
754 				memset(null_buff, 0, bsdtar->buff_size);
755 			}
756 
757 			while (sparse > 0) {
758 				if (sparse > (int64_t)bsdtar->buff_size)
759 					ns = bsdtar->buff_size;
760 				else
761 					ns = (size_t)sparse;
762 				bytes_written =
763 				    archive_write_data(a, null_buff, ns);
764 				if (bytes_written < 0) {
765 					/* Write failed; this is bad */
766 					lafe_warnc(0, "%s",
767 					     archive_error_string(a));
768 					return (-1);
769 				}
770 				if ((size_t)bytes_written < ns) {
771 					/* Write was truncated; warn but
772 					 * continue. */
773 					lafe_warnc(0,
774 					    "%s: Truncated write; file may "
775 					    "have grown while being archived.",
776 					    archive_entry_pathname(entry));
777 					return (0);
778 				}
779 				progress += bytes_written;
780 				sparse -= bytes_written;
781 			}
782 		}
783 
784 		bytes_written = archive_write_data(a, buff, bytes_read);
785 		if (bytes_written < 0) {
786 			/* Write failed; this is bad */
787 			lafe_warnc(0, "%s", archive_error_string(a));
788 			return (-1);
789 		}
790 		if ((size_t)bytes_written < bytes_read) {
791 			/* Write was truncated; warn but continue. */
792 			lafe_warnc(0,
793 			    "%s: Truncated write; file may have grown "
794 			    "while being archived.",
795 			    archive_entry_pathname(entry));
796 			return (0);
797 		}
798 		progress += bytes_written;
799 	}
800 	if (r < ARCHIVE_WARN) {
801 		lafe_warnc(archive_errno(a), "%s", archive_error_string(a));
802 		return (-1);
803 	}
804 	return (0);
805 }
806 
807 static void
808 excluded_callback(struct archive *a, void *_data, struct archive_entry *entry)
809 {
810 	struct bsdtar *bsdtar = (struct bsdtar *)_data;
811 
812 	if (bsdtar->flags & OPTFLAG_NO_SUBDIRS)
813 		return;
814 	if (!archive_read_disk_can_descend(a))
815 		return;
816 	if ((bsdtar->flags & OPTFLAG_INTERACTIVE) &&
817 	    !yes("add '%s'", archive_entry_pathname(entry)))
818 		return;
819 	archive_read_disk_descend(a);
820 }
821 
822 static int
823 metadata_filter(struct archive *a, void *_data, struct archive_entry *entry)
824 {
825 	struct bsdtar *bsdtar = (struct bsdtar *)_data;
826 
827 	/* XXX TODO: check whether this filesystem is
828 	 * synthetic and/or local.  Add a new
829 	 * --local-only option to skip non-local
830 	 * filesystems.  Skip synthetic filesystems
831 	 * regardless.
832 	 *
833 	 * The results should be cached, since
834 	 * tree.c doesn't usually visit a directory
835 	 * and the directory contents together.  A simple
836 	 * move-to-front list should perform quite well.
837 	 *
838 	 * Use archive_read_disk_current_filesystem_is_remote().
839 	 */
840 
841 	/*
842 	 * If the user vetoes this file/directory, skip it.
843 	 * We want this to be fairly late; if some other
844 	 * check would veto this file, we shouldn't bother
845 	 * the user with it.
846 	 */
847 	if ((bsdtar->flags & OPTFLAG_INTERACTIVE) &&
848 	    !yes("add '%s'", archive_entry_pathname(entry)))
849 		return (0);
850 
851 	/* Note: if user vetoes, we won't descend. */
852 	if (((bsdtar->flags & OPTFLAG_NO_SUBDIRS) == 0) &&
853 	    archive_read_disk_can_descend(a))
854 		archive_read_disk_descend(a);
855 
856 	return (1);
857 }
858 
859 /*
860  * Add the file or dir hierarchy named by 'path' to the archive
861  */
862 static void
863 write_hierarchy(struct bsdtar *bsdtar, struct archive *a, const char *path)
864 {
865 	struct archive *disk = bsdtar->diskreader;
866 	struct archive_entry *entry = NULL, *spare_entry = NULL;
867 	int r;
868 
869 	r = archive_read_disk_open(disk, path);
870 	if (r != ARCHIVE_OK) {
871 		lafe_warnc(archive_errno(disk),
872 		    "%s", archive_error_string(disk));
873 		bsdtar->return_value = 1;
874 		return;
875 	}
876 	bsdtar->first_fs = -1;
877 
878 	for (;;) {
879 		archive_entry_free(entry);
880 		entry = archive_entry_new();
881 		r = archive_read_next_header2(disk, entry);
882 		if (r == ARCHIVE_EOF)
883 			break;
884 		else if (r != ARCHIVE_OK) {
885 			lafe_warnc(archive_errno(disk),
886 			    "%s", archive_error_string(disk));
887 			if (r == ARCHIVE_FATAL || r == ARCHIVE_FAILED) {
888 				bsdtar->return_value = 1;
889 				archive_entry_free(entry);
890 				archive_read_close(disk);
891 				return;
892 			} else if (r < ARCHIVE_WARN)
893 				continue;
894 		}
895 
896 		if (bsdtar->uid >= 0) {
897 			archive_entry_set_uid(entry, bsdtar->uid);
898 			if (!bsdtar->uname)
899 				archive_entry_set_uname(entry,
900 				    archive_read_disk_uname(bsdtar->diskreader,
901 					bsdtar->uid));
902 		}
903 		if (bsdtar->gid >= 0) {
904 			archive_entry_set_gid(entry, bsdtar->gid);
905 			if (!bsdtar->gname)
906 				archive_entry_set_gname(entry,
907 				    archive_read_disk_gname(bsdtar->diskreader,
908 					bsdtar->gid));
909 		}
910 		if (bsdtar->uname)
911 			archive_entry_set_uname(entry, bsdtar->uname);
912 		if (bsdtar->gname)
913 			archive_entry_set_gname(entry, bsdtar->gname);
914 
915 		/*
916 		 * Rewrite the pathname to be archived.  If rewrite
917 		 * fails, skip the entry.
918 		 */
919 		if (edit_pathname(bsdtar, entry))
920 			continue;
921 
922 		/* Display entry as we process it. */
923 		if (bsdtar->verbose > 1) {
924 			safe_fprintf(stderr, "a ");
925 			list_item_verbose(bsdtar, stderr, entry);
926 		} else if (bsdtar->verbose > 0) {
927 		/* This format is required by SUSv2. */
928 			safe_fprintf(stderr, "a %s",
929 			    archive_entry_pathname(entry));
930 		}
931 
932 		/* Non-regular files get archived with zero size. */
933 		if (archive_entry_filetype(entry) != AE_IFREG)
934 			archive_entry_set_size(entry, 0);
935 
936 		archive_entry_linkify(bsdtar->resolver, &entry, &spare_entry);
937 
938 		while (entry != NULL) {
939 			write_file(bsdtar, a, entry);
940 			archive_entry_free(entry);
941 			entry = spare_entry;
942 			spare_entry = NULL;
943 		}
944 
945 		if (bsdtar->verbose)
946 			fprintf(stderr, "\n");
947 	}
948 	archive_entry_free(entry);
949 	archive_read_close(disk);
950 }
951 
952 /*
953  * Write a single file (or directory or other filesystem object) to
954  * the archive.
955  */
956 static void
957 write_file(struct bsdtar *bsdtar, struct archive *a,
958     struct archive_entry *entry)
959 {
960 	write_entry(bsdtar, a, entry);
961 }
962 
963 /*
964  * Write a single entry to the archive.
965  */
966 static void
967 write_entry(struct bsdtar *bsdtar, struct archive *a,
968     struct archive_entry *entry)
969 {
970 	int e;
971 
972 	e = archive_write_header(a, entry);
973 	if (e != ARCHIVE_OK) {
974 		if (bsdtar->verbose > 1) {
975 			safe_fprintf(stderr, "a ");
976 			list_item_verbose(bsdtar, stderr, entry);
977 			lafe_warnc(0, ": %s", archive_error_string(a));
978 		} else if (bsdtar->verbose > 0) {
979 			lafe_warnc(0, "%s: %s",
980 			    archive_entry_pathname(entry),
981 			    archive_error_string(a));
982 		} else
983 			fprintf(stderr, ": %s", archive_error_string(a));
984 	}
985 
986 	if (e == ARCHIVE_FATAL)
987 		exit(1);
988 
989 	/*
990 	 * If we opened a file earlier, write it out now.  Note that
991 	 * the format handler might have reset the size field to zero
992 	 * to inform us that the archive body won't get stored.  In
993 	 * that case, just skip the write.
994 	 */
995 	if (e >= ARCHIVE_WARN && archive_entry_size(entry) > 0) {
996 		if (copy_file_data_block(bsdtar, a, bsdtar->diskreader, entry))
997 			exit(1);
998 	}
999 }
1000 
1001 static void
1002 report_write(struct bsdtar *bsdtar, struct archive *a,
1003     struct archive_entry *entry, int64_t progress)
1004 {
1005 	uint64_t comp, uncomp;
1006 	int compression;
1007 
1008 	if (bsdtar->verbose)
1009 		fprintf(stderr, "\n");
1010 	comp = archive_filter_bytes(a, -1);
1011 	uncomp = archive_filter_bytes(a, 0);
1012 	fprintf(stderr, "In: %d files, %s bytes;",
1013 	    archive_file_count(a), tar_i64toa(uncomp));
1014 	if (comp >= uncomp)
1015 		compression = 0;
1016 	else
1017 		compression = (int)((uncomp - comp) * 100 / uncomp);
1018 	fprintf(stderr,
1019 	    " Out: %s bytes, compression %d%%\n",
1020 	    tar_i64toa(comp), compression);
1021 	/* Can't have two calls to tar_i64toa() pending, so split the output. */
1022 	safe_fprintf(stderr, "Current: %s (%s",
1023 	    archive_entry_pathname(entry),
1024 	    tar_i64toa(progress));
1025 	fprintf(stderr, "/%s bytes)\n",
1026 	    tar_i64toa(archive_entry_size(entry)));
1027 }
1028 
1029 static void
1030 test_for_append(struct bsdtar *bsdtar)
1031 {
1032 	struct stat s;
1033 
1034 	if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
1035 		lafe_errc(1, 0, "no files or directories specified");
1036 	if (bsdtar->filename == NULL)
1037 		lafe_errc(1, 0, "Cannot append to stdout.");
1038 
1039 	if (stat(bsdtar->filename, &s) != 0)
1040 		return;
1041 
1042 	if (!S_ISREG(s.st_mode) && !S_ISBLK(s.st_mode))
1043 		lafe_errc(1, 0,
1044 		    "Cannot append to %s: not a regular file.",
1045 		    bsdtar->filename);
1046 
1047 /* Is this an appropriate check here on Windows? */
1048 /*
1049 	if (GetFileType(handle) != FILE_TYPE_DISK)
1050 		lafe_errc(1, 0, "Cannot append");
1051 */
1052 
1053 }
1054