xref: /dragonfly/contrib/libarchive/tar/write.c (revision 3679fd1e)
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: src/usr.bin/tar/write.c,v 1.79 2008/11/27 05:49:52 kientzle Exp $");
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 		char *p;
149 		/* Set default write options. */
150 		p = malloc(sizeof(IGNORE_WRONG_MODULE_NAME)
151 		    + strlen(writer_options) + 1);
152 		if (p == 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,
158 		    sizeof(IGNORE_WRONG_MODULE_NAME) -1);
159 		strcpy(p + sizeof(IGNORE_WRONG_MODULE_NAME) -1, writer_options);
160 		r = archive_write_set_options(a, p);
161 		free(p);
162 		if (r < ARCHIVE_WARN)
163 			lafe_errc(1, 0, "%s", archive_error_string(a));
164 		else
165 			archive_clear_error(a);
166 	}
167 	if (ARCHIVE_OK != archive_write_set_options(a, bsdtar->option_options))
168 		lafe_errc(1, 0, "%s", archive_error_string(a));
169 }
170 
171 static void
172 set_reader_options(struct bsdtar *bsdtar, struct archive *a)
173 {
174 	const char *reader_options;
175 	int r;
176 
177 	(void)bsdtar; /* UNUSED */
178 
179 	reader_options = getenv(ENV_READER_OPTIONS);
180 	if (reader_options != NULL) {
181 		char *p;
182 		/* Set default write options. */
183 		p = malloc(sizeof(IGNORE_WRONG_MODULE_NAME)
184 		    + strlen(reader_options) + 1);
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,
191 		    sizeof(IGNORE_WRONG_MODULE_NAME) -1);
192 		strcpy(p + sizeof(IGNORE_WRONG_MODULE_NAME) -1, reader_options);
193 		r = archive_read_set_options(a, p);
194 		free(p);
195 		if (r < ARCHIVE_WARN)
196 			lafe_errc(1, 0, "%s", archive_error_string(a));
197 		else
198 			archive_clear_error(a);
199 	}
200 }
201 
202 void
203 tar_mode_c(struct bsdtar *bsdtar)
204 {
205 	struct archive *a;
206 	const void *filter_name;
207 	int r;
208 
209 	if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
210 		lafe_errc(1, 0, "no files or directories specified");
211 
212 	a = archive_write_new();
213 
214 	/* Support any format that the library supports. */
215 	if (cset_get_format(bsdtar->cset) == NULL) {
216 		r = archive_write_set_format_pax_restricted(a);
217 		cset_set_format(bsdtar->cset, "pax restricted");
218 	} else {
219 		r = archive_write_set_format_by_name(a,
220 			cset_get_format(bsdtar->cset));
221 	}
222 	if (r != ARCHIVE_OK) {
223 		fprintf(stderr, "Can't use format %s: %s\n",
224 		    cset_get_format(bsdtar->cset),
225 		    archive_error_string(a));
226 		usage();
227 	}
228 
229 	archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
230 	archive_write_set_bytes_in_last_block(a, bsdtar->bytes_in_last_block);
231 
232 	r = cset_write_add_filters(bsdtar->cset, a, &filter_name);
233 	if (r < ARCHIVE_WARN) {
234 		lafe_errc(1, 0, "Unsupported compression option --%s",
235 		    (const char *)filter_name);
236 	}
237 
238 	set_writer_options(bsdtar, a);
239 	if (bsdtar->passphrase != NULL)
240 		r = archive_write_set_passphrase(a, bsdtar->passphrase);
241 	else
242 		r = archive_write_set_passphrase_callback(a, bsdtar,
243 			&passphrase_callback);
244 	if (r != ARCHIVE_OK)
245 		lafe_errc(1, 0, "%s", archive_error_string(a));
246 	if (ARCHIVE_OK != archive_write_open_filename(a, bsdtar->filename))
247 		lafe_errc(1, 0, "%s", archive_error_string(a));
248 	write_archive(a, bsdtar);
249 }
250 
251 /*
252  * Same as 'c', except we only support tar or empty formats in
253  * uncompressed files on disk.
254  */
255 void
256 tar_mode_r(struct bsdtar *bsdtar)
257 {
258 	int64_t	end_offset;
259 	int	format;
260 	struct archive *a;
261 	struct archive_entry *entry;
262 	int	r;
263 
264 	/* Sanity-test some arguments and the file. */
265 	test_for_append(bsdtar);
266 
267 	format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
268 
269 #if defined(__BORLANDC__)
270 	bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT | O_BINARY);
271 #else
272 	bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT | O_BINARY, 0666);
273 #endif
274 	if (bsdtar->fd < 0)
275 		lafe_errc(1, errno,
276 		    "Cannot open %s", bsdtar->filename);
277 
278 	a = archive_read_new();
279 	archive_read_support_filter_all(a);
280 	archive_read_support_format_empty(a);
281 	archive_read_support_format_tar(a);
282 	archive_read_support_format_gnutar(a);
283 	set_reader_options(bsdtar, a);
284 	r = archive_read_open_fd(a, bsdtar->fd, 10240);
285 	if (r != ARCHIVE_OK)
286 		lafe_errc(1, archive_errno(a),
287 		    "Can't read archive %s: %s", bsdtar->filename,
288 		    archive_error_string(a));
289 	while (0 == archive_read_next_header(a, &entry)) {
290 		if (archive_filter_code(a, 0) != ARCHIVE_FILTER_NONE) {
291 			archive_read_free(a);
292 			close(bsdtar->fd);
293 			lafe_errc(1, 0,
294 			    "Cannot append to compressed archive.");
295 		}
296 		/* Keep going until we hit end-of-archive */
297 		format = archive_format(a);
298 	}
299 
300 	end_offset = archive_read_header_position(a);
301 	archive_read_free(a);
302 
303 	/* Re-open archive for writing */
304 	a = archive_write_new();
305 	/*
306 	 * Set the format to be used for writing.  To allow people to
307 	 * extend empty files, we need to allow them to specify the format,
308 	 * which opens the possibility that they will specify a format that
309 	 * doesn't match the existing format.  Hence, the following bit
310 	 * of arcane ugliness.
311 	 */
312 
313 	if (cset_get_format(bsdtar->cset) != NULL) {
314 		/* If the user requested a format, use that, but ... */
315 		archive_write_set_format_by_name(a,
316 		    cset_get_format(bsdtar->cset));
317 		/* ... complain if it's not compatible. */
318 		format &= ARCHIVE_FORMAT_BASE_MASK;
319 		if (format != (int)(archive_format(a) & ARCHIVE_FORMAT_BASE_MASK)
320 		    && format != ARCHIVE_FORMAT_EMPTY) {
321 			lafe_errc(1, 0,
322 			    "Format %s is incompatible with the archive %s.",
323 			    cset_get_format(bsdtar->cset), bsdtar->filename);
324 		}
325 	} else {
326 		/*
327 		 * Just preserve the current format, with a little care
328 		 * for formats that libarchive can't write.
329 		 */
330 		if (format == ARCHIVE_FORMAT_EMPTY)
331 			format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
332 		archive_write_set_format(a, format);
333 	}
334 	if (lseek(bsdtar->fd, end_offset, SEEK_SET) < 0)
335 		lafe_errc(1, errno, "Could not seek to archive end");
336 	set_writer_options(bsdtar, a);
337 	if (ARCHIVE_OK != archive_write_open_fd(a, bsdtar->fd))
338 		lafe_errc(1, 0, "%s", archive_error_string(a));
339 
340 	write_archive(a, bsdtar); /* XXX check return val XXX */
341 
342 	close(bsdtar->fd);
343 	bsdtar->fd = -1;
344 }
345 
346 void
347 tar_mode_u(struct bsdtar *bsdtar)
348 {
349 	int64_t			 end_offset;
350 	struct archive		*a;
351 	struct archive_entry	*entry;
352 	int			 format;
353 	struct archive_dir_entry	*p;
354 	struct archive_dir	 archive_dir;
355 
356 	bsdtar->archive_dir = &archive_dir;
357 	memset(&archive_dir, 0, sizeof(archive_dir));
358 
359 	format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
360 
361 	/* Sanity-test some arguments and the file. */
362 	test_for_append(bsdtar);
363 
364 	bsdtar->fd = open(bsdtar->filename, O_RDWR | O_BINARY);
365 	if (bsdtar->fd < 0)
366 		lafe_errc(1, errno,
367 		    "Cannot open %s", bsdtar->filename);
368 
369 	a = archive_read_new();
370 	archive_read_support_filter_all(a);
371 	archive_read_support_format_tar(a);
372 	archive_read_support_format_gnutar(a);
373 	set_reader_options(bsdtar, a);
374 	if (archive_read_open_fd(a, bsdtar->fd, bsdtar->bytes_per_block)
375 	    != ARCHIVE_OK) {
376 		lafe_errc(1, 0,
377 		    "Can't open %s: %s", bsdtar->filename,
378 		    archive_error_string(a));
379 	}
380 
381 	/* Build a list of all entries and their recorded mod times. */
382 	while (0 == archive_read_next_header(a, &entry)) {
383 		if (archive_filter_code(a, 0) != ARCHIVE_FILTER_NONE) {
384 			archive_read_free(a);
385 			close(bsdtar->fd);
386 			lafe_errc(1, 0,
387 			    "Cannot append to compressed archive.");
388 		}
389 		if (archive_match_exclude_entry(bsdtar->matching,
390 		    ARCHIVE_MATCH_MTIME | ARCHIVE_MATCH_OLDER |
391 		    ARCHIVE_MATCH_EQUAL, entry) != ARCHIVE_OK)
392 			lafe_errc(1, 0, "Error : %s",
393 			    archive_error_string(bsdtar->matching));
394 		/* Record the last format determination we see */
395 		format = archive_format(a);
396 		/* Keep going until we hit end-of-archive */
397 	}
398 
399 	end_offset = archive_read_header_position(a);
400 	archive_read_free(a);
401 
402 	/* Re-open archive for writing. */
403 	a = archive_write_new();
404 	/*
405 	 * Set format to same one auto-detected above.
406 	 */
407 	archive_write_set_format(a, format);
408 	archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
409 	archive_write_set_bytes_in_last_block(a, bsdtar->bytes_in_last_block);
410 
411 	if (lseek(bsdtar->fd, end_offset, SEEK_SET) < 0)
412 		lafe_errc(1, errno, "Could not seek to archive end");
413 	set_writer_options(bsdtar, a);
414 	if (ARCHIVE_OK != archive_write_open_fd(a, bsdtar->fd))
415 		lafe_errc(1, 0, "%s", archive_error_string(a));
416 
417 	write_archive(a, bsdtar);
418 
419 	close(bsdtar->fd);
420 	bsdtar->fd = -1;
421 
422 	while (bsdtar->archive_dir->head != NULL) {
423 		p = bsdtar->archive_dir->head->next;
424 		free(bsdtar->archive_dir->head->name);
425 		free(bsdtar->archive_dir->head);
426 		bsdtar->archive_dir->head = p;
427 	}
428 	bsdtar->archive_dir->tail = NULL;
429 }
430 
431 
432 /*
433  * Write user-specified files/dirs to opened archive.
434  */
435 static void
436 write_archive(struct archive *a, struct bsdtar *bsdtar)
437 {
438 	const char *arg;
439 	struct archive_entry *entry, *sparse_entry;
440 
441 	/* Choose a suitable copy buffer size */
442 	bsdtar->buff_size = 64 * 1024;
443 	while (bsdtar->buff_size < (size_t)bsdtar->bytes_per_block)
444 	  bsdtar->buff_size *= 2;
445 	/* Try to compensate for space we'll lose to alignment. */
446 	bsdtar->buff_size += 16 * 1024;
447 
448 	/* Allocate a buffer for file data. */
449 	if ((bsdtar->buff = malloc(bsdtar->buff_size)) == NULL)
450 		lafe_errc(1, 0, "cannot allocate memory");
451 
452 	if ((bsdtar->resolver = archive_entry_linkresolver_new()) == NULL)
453 		lafe_errc(1, 0, "cannot create link resolver");
454 	archive_entry_linkresolver_set_strategy(bsdtar->resolver,
455 	    archive_format(a));
456 
457 	/* Create a read_disk object. */
458 	if ((bsdtar->diskreader = archive_read_disk_new()) == NULL)
459 		lafe_errc(1, 0, "Cannot create read_disk object");
460 	/* Tell the read_disk how handle symlink. */
461 	switch (bsdtar->symlink_mode) {
462 	case 'H':
463 		archive_read_disk_set_symlink_hybrid(bsdtar->diskreader);
464 		break;
465 	case 'L':
466 		archive_read_disk_set_symlink_logical(bsdtar->diskreader);
467 		break;
468 	default:
469 		archive_read_disk_set_symlink_physical(bsdtar->diskreader);
470 		break;
471 	}
472 	/* Register entry filters. */
473 	archive_read_disk_set_matching(bsdtar->diskreader,
474 	    bsdtar->matching, excluded_callback, bsdtar);
475 	archive_read_disk_set_metadata_filter_callback(
476 	    bsdtar->diskreader, metadata_filter, bsdtar);
477 	/* Set the behavior of archive_read_disk. */
478 	archive_read_disk_set_behavior(bsdtar->diskreader,
479 	    bsdtar->readdisk_flags);
480 	archive_read_disk_set_standard_lookup(bsdtar->diskreader);
481 
482 	if (bsdtar->names_from_file != NULL)
483 		archive_names_from_file(bsdtar, a);
484 
485 	while (*bsdtar->argv) {
486 		arg = *bsdtar->argv;
487 		if (arg[0] == '-' && arg[1] == 'C') {
488 			arg += 2;
489 			if (*arg == '\0') {
490 				bsdtar->argv++;
491 				arg = *bsdtar->argv;
492 				if (arg == NULL) {
493 					lafe_warnc(0, "%s",
494 					    "Missing argument for -C");
495 					bsdtar->return_value = 1;
496 					goto cleanup;
497 				}
498 				if (*arg == '\0') {
499 					lafe_warnc(0,
500 					    "Meaningless argument for -C: ''");
501 					bsdtar->return_value = 1;
502 					goto cleanup;
503 				}
504 			}
505 			set_chdir(bsdtar, arg);
506 		} else {
507 			if (*arg != '/' && (arg[0] != '@' || arg[1] != '/'))
508 				do_chdir(bsdtar); /* Handle a deferred -C */
509 			if (*arg == '@') {
510 				if (append_archive_filename(bsdtar, a,
511 				    arg + 1) != 0)
512 					break;
513 			} else
514 				write_hierarchy(bsdtar, a, arg);
515 		}
516 		bsdtar->argv++;
517 	}
518 
519 	archive_read_disk_set_matching(bsdtar->diskreader, NULL, NULL, NULL);
520 	archive_read_disk_set_metadata_filter_callback(
521 	    bsdtar->diskreader, NULL, NULL);
522 	entry = NULL;
523 	archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
524 	while (entry != NULL) {
525 		int r;
526 		struct archive_entry *entry2;
527 		struct archive *disk = bsdtar->diskreader;
528 
529 		/*
530 		 * This tricky code here is to correctly read the cotents
531 		 * of the entry because the disk reader bsdtar->diskreader
532 		 * is pointing at does not have any information about the
533 		 * entry by this time and using archive_read_data_block()
534 		 * with the disk reader consequently must fail. And we
535 		 * have to re-open the entry to read the contents.
536 		 */
537 		/* TODO: Work with -C option as well. */
538 		r = archive_read_disk_open(disk,
539 			archive_entry_sourcepath(entry));
540 		if (r != ARCHIVE_OK) {
541 			lafe_warnc(archive_errno(disk),
542 			    "%s", archive_error_string(disk));
543 			bsdtar->return_value = 1;
544 			archive_entry_free(entry);
545 			continue;
546 		}
547 
548 		/*
549 		 * Invoke archive_read_next_header2() to work
550 		 * archive_read_data_block(), which is called via write_file(),
551 		 * without failure.
552 		 */
553 		entry2 = archive_entry_new();
554 		r = archive_read_next_header2(disk, entry2);
555 		archive_entry_free(entry2);
556 		if (r != ARCHIVE_OK) {
557 			lafe_warnc(archive_errno(disk),
558 			    "%s", archive_error_string(disk));
559 			if (r == ARCHIVE_FATAL)
560 				bsdtar->return_value = 1;
561 			else
562 				archive_read_close(disk);
563 			archive_entry_free(entry);
564 			continue;
565 		}
566 
567 		write_file(bsdtar, a, entry);
568 		archive_entry_free(entry);
569 		archive_read_close(disk);
570 		entry = NULL;
571 		archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
572 	}
573 
574 	if (archive_write_close(a)) {
575 		lafe_warnc(0, "%s", archive_error_string(a));
576 		bsdtar->return_value = 1;
577 	}
578 
579 cleanup:
580 	/* Free file data buffer. */
581 	free(bsdtar->buff);
582 	archive_entry_linkresolver_free(bsdtar->resolver);
583 	bsdtar->resolver = NULL;
584 	archive_read_free(bsdtar->diskreader);
585 	bsdtar->diskreader = NULL;
586 
587 	if (bsdtar->option_totals) {
588 		fprintf(stderr, "Total bytes written: %s\n",
589 		    tar_i64toa(archive_filter_bytes(a, -1)));
590 	}
591 
592 	archive_write_free(a);
593 }
594 
595 /*
596  * Archive names specified in file.
597  *
598  * Unless --null was specified, a line containing exactly "-C" will
599  * cause the next line to be a directory to pass to chdir().  If
600  * --null is specified, then a line "-C" is just another filename.
601  */
602 static void
603 archive_names_from_file(struct bsdtar *bsdtar, struct archive *a)
604 {
605 	struct lafe_line_reader *lr;
606 	const char *line;
607 
608 	bsdtar->next_line_is_dir = 0;
609 
610 	lr = lafe_line_reader(bsdtar->names_from_file, bsdtar->option_null);
611 	while ((line = lafe_line_reader_next(lr)) != NULL) {
612 		if (bsdtar->next_line_is_dir) {
613 			if (*line != '\0')
614 				set_chdir(bsdtar, line);
615 			else {
616 				lafe_warnc(0,
617 				    "Meaningless argument for -C: ''");
618 				bsdtar->return_value = 1;
619 			}
620 			bsdtar->next_line_is_dir = 0;
621 		} else if (!bsdtar->option_null && strcmp(line, "-C") == 0)
622 			bsdtar->next_line_is_dir = 1;
623 		else {
624 			if (*line != '/')
625 				do_chdir(bsdtar); /* Handle a deferred -C */
626 			write_hierarchy(bsdtar, a, line);
627 		}
628 	}
629 	lafe_line_reader_free(lr);
630 	if (bsdtar->next_line_is_dir)
631 		lafe_errc(1, errno,
632 		    "Unexpected end of filename list; "
633 		    "directory expected after -C");
634 }
635 
636 /*
637  * Copy from specified archive to current archive.  Returns non-zero
638  * for write errors (which force us to terminate the entire archiving
639  * operation).  If there are errors reading the input archive, we set
640  * bsdtar->return_value but return zero, so the overall archiving
641  * operation will complete and return non-zero.
642  */
643 static int
644 append_archive_filename(struct bsdtar *bsdtar, struct archive *a,
645     const char *raw_filename)
646 {
647 	struct archive *ina;
648 	const char *filename = raw_filename;
649 	int rc;
650 
651 	if (strcmp(filename, "-") == 0)
652 		filename = NULL; /* Library uses NULL for stdio. */
653 
654 	ina = archive_read_new();
655 	archive_read_support_format_all(ina);
656 	archive_read_support_filter_all(ina);
657 	set_reader_options(bsdtar, ina);
658 	archive_read_set_options(ina, "mtree:checkfs");
659 	if (bsdtar->passphrase != NULL)
660 		rc = archive_read_add_passphrase(a, bsdtar->passphrase);
661 	else
662 		rc = archive_read_set_passphrase_callback(ina, bsdtar,
663 			&passphrase_callback);
664 	if (rc != ARCHIVE_OK)
665 		lafe_errc(1, 0, "%s", archive_error_string(a));
666 	if (archive_read_open_filename(ina, filename,
667 					bsdtar->bytes_per_block)) {
668 		lafe_warnc(0, "%s", archive_error_string(ina));
669 		bsdtar->return_value = 1;
670 		return (0);
671 	}
672 
673 	rc = append_archive(bsdtar, a, ina);
674 
675 	if (rc != ARCHIVE_OK) {
676 		lafe_warnc(0, "Error reading archive %s: %s",
677 		    raw_filename, archive_error_string(ina));
678 		bsdtar->return_value = 1;
679 	}
680 	archive_read_free(ina);
681 
682 	return (rc);
683 }
684 
685 static int
686 append_archive(struct bsdtar *bsdtar, struct archive *a, struct archive *ina)
687 {
688 	struct archive_entry *in_entry;
689 	int e;
690 
691 	while (ARCHIVE_OK == (e = archive_read_next_header(ina, &in_entry))) {
692 		if (archive_match_excluded(bsdtar->matching, in_entry))
693 			continue;
694 		if (bsdtar->option_interactive &&
695 		    !yes("copy '%s'", archive_entry_pathname(in_entry)))
696 			continue;
697 		if (bsdtar->verbose > 1) {
698 			safe_fprintf(stderr, "a ");
699 			list_item_verbose(bsdtar, stderr, in_entry);
700 		} else if (bsdtar->verbose > 0)
701 			safe_fprintf(stderr, "a %s",
702 			    archive_entry_pathname(in_entry));
703 		if (need_report())
704 			report_write(bsdtar, a, in_entry, 0);
705 
706 		e = archive_write_header(a, in_entry);
707 		if (e != ARCHIVE_OK) {
708 			if (!bsdtar->verbose)
709 				lafe_warnc(0, "%s: %s",
710 				    archive_entry_pathname(in_entry),
711 				    archive_error_string(a));
712 			else
713 				fprintf(stderr, ": %s", archive_error_string(a));
714 		}
715 		if (e == ARCHIVE_FATAL)
716 			exit(1);
717 
718 		if (e >= ARCHIVE_WARN) {
719 			if (archive_entry_size(in_entry) == 0)
720 				archive_read_data_skip(ina);
721 			else if (copy_file_data_block(bsdtar, a, ina, in_entry))
722 				exit(1);
723 		}
724 
725 		if (bsdtar->verbose)
726 			fprintf(stderr, "\n");
727 	}
728 
729 	return (e == ARCHIVE_EOF ? ARCHIVE_OK : e);
730 }
731 
732 /* Helper function to copy file to archive. */
733 static int
734 copy_file_data_block(struct bsdtar *bsdtar, struct archive *a,
735     struct archive *in_a, struct archive_entry *entry)
736 {
737 	size_t	bytes_read;
738 	ssize_t	bytes_written;
739 	int64_t	offset, progress = 0;
740 	char *null_buff = NULL;
741 	const void *buff;
742 	int r;
743 
744 	while ((r = archive_read_data_block(in_a, &buff,
745 	    &bytes_read, &offset)) == ARCHIVE_OK) {
746 		if (need_report())
747 			report_write(bsdtar, a, entry, progress);
748 
749 		if (offset > progress) {
750 			int64_t sparse = offset - progress;
751 			size_t ns;
752 
753 			if (null_buff == NULL) {
754 				null_buff = bsdtar->buff;
755 				memset(null_buff, 0, bsdtar->buff_size);
756 			}
757 
758 			while (sparse > 0) {
759 				if (sparse > (int64_t)bsdtar->buff_size)
760 					ns = bsdtar->buff_size;
761 				else
762 					ns = (size_t)sparse;
763 				bytes_written =
764 				    archive_write_data(a, null_buff, ns);
765 				if (bytes_written < 0) {
766 					/* Write failed; this is bad */
767 					lafe_warnc(0, "%s",
768 					     archive_error_string(a));
769 					return (-1);
770 				}
771 				if ((size_t)bytes_written < ns) {
772 					/* Write was truncated; warn but
773 					 * continue. */
774 					lafe_warnc(0,
775 					    "%s: Truncated write; file may "
776 					    "have grown while being archived.",
777 					    archive_entry_pathname(entry));
778 					return (0);
779 				}
780 				progress += bytes_written;
781 				sparse -= bytes_written;
782 			}
783 		}
784 
785 		bytes_written = archive_write_data(a, buff, bytes_read);
786 		if (bytes_written < 0) {
787 			/* Write failed; this is bad */
788 			lafe_warnc(0, "%s", archive_error_string(a));
789 			return (-1);
790 		}
791 		if ((size_t)bytes_written < bytes_read) {
792 			/* Write was truncated; warn but continue. */
793 			lafe_warnc(0,
794 			    "%s: Truncated write; file may have grown "
795 			    "while being archived.",
796 			    archive_entry_pathname(entry));
797 			return (0);
798 		}
799 		progress += bytes_written;
800 	}
801 	if (r < ARCHIVE_WARN) {
802 		lafe_warnc(archive_errno(a), "%s", archive_error_string(a));
803 		return (-1);
804 	}
805 	return (0);
806 }
807 
808 static void
809 excluded_callback(struct archive *a, void *_data, struct archive_entry *entry)
810 {
811 	struct bsdtar *bsdtar = (struct bsdtar *)_data;
812 
813 	if (bsdtar->option_no_subdirs)
814 		return;
815 	if (!archive_read_disk_can_descend(a))
816 		return;
817 	if (bsdtar->option_interactive &&
818 	    !yes("add '%s'", archive_entry_pathname(entry)))
819 		return;
820 	archive_read_disk_descend(a);
821 }
822 
823 static int
824 metadata_filter(struct archive *a, void *_data, struct archive_entry *entry)
825 {
826 	struct bsdtar *bsdtar = (struct bsdtar *)_data;
827 
828 	/* XXX TODO: check whether this filesystem is
829 	 * synthetic and/or local.  Add a new
830 	 * --local-only option to skip non-local
831 	 * filesystems.  Skip synthetic filesystems
832 	 * regardless.
833 	 *
834 	 * The results should be cached, since
835 	 * tree.c doesn't usually visit a directory
836 	 * and the directory contents together.  A simple
837 	 * move-to-front list should perform quite well.
838 	 *
839 	 * Use archive_read_disk_current_filesystem_is_remote().
840 	 */
841 
842 	/*
843 	 * If the user vetoes this file/directory, skip it.
844 	 * We want this to be fairly late; if some other
845 	 * check would veto this file, we shouldn't bother
846 	 * the user with it.
847 	 */
848 	if (bsdtar->option_interactive &&
849 	    !yes("add '%s'", archive_entry_pathname(entry)))
850 		return (0);
851 
852 	/* Note: if user vetoes, we won't descend. */
853 	if (!bsdtar->option_no_subdirs && 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) {
888 				bsdtar->return_value = 1;
889 				return;
890 			} else if (r < ARCHIVE_WARN)
891 				continue;
892 		}
893 
894 		if (bsdtar->uid >= 0) {
895 			archive_entry_set_uid(entry, bsdtar->uid);
896 			if (!bsdtar->uname)
897 				archive_entry_set_uname(entry,
898 				    archive_read_disk_uname(bsdtar->diskreader,
899 					bsdtar->uid));
900 		}
901 		if (bsdtar->gid >= 0) {
902 			archive_entry_set_gid(entry, bsdtar->gid);
903 			if (!bsdtar->gname)
904 				archive_entry_set_gname(entry,
905 				    archive_read_disk_gname(bsdtar->diskreader,
906 					bsdtar->gid));
907 		}
908 		if (bsdtar->uname)
909 			archive_entry_set_uname(entry, bsdtar->uname);
910 		if (bsdtar->gname)
911 			archive_entry_set_gname(entry, bsdtar->gname);
912 
913 		/*
914 		 * Rewrite the pathname to be archived.  If rewrite
915 		 * fails, skip the entry.
916 		 */
917 		if (edit_pathname(bsdtar, entry))
918 			continue;
919 
920 		/* Display entry as we process it. */
921 		if (bsdtar->verbose > 1) {
922 			safe_fprintf(stderr, "a ");
923 			list_item_verbose(bsdtar, stderr, entry);
924 		} else if (bsdtar->verbose > 0) {
925 		/* This format is required by SUSv2. */
926 			safe_fprintf(stderr, "a %s",
927 			    archive_entry_pathname(entry));
928 		}
929 
930 		/* Non-regular files get archived with zero size. */
931 		if (archive_entry_filetype(entry) != AE_IFREG)
932 			archive_entry_set_size(entry, 0);
933 
934 		archive_entry_linkify(bsdtar->resolver, &entry, &spare_entry);
935 
936 		while (entry != NULL) {
937 			write_file(bsdtar, a, entry);
938 			archive_entry_free(entry);
939 			entry = spare_entry;
940 			spare_entry = NULL;
941 		}
942 
943 		if (bsdtar->verbose)
944 			fprintf(stderr, "\n");
945 	}
946 	archive_entry_free(entry);
947 	archive_read_close(disk);
948 }
949 
950 /*
951  * Write a single file (or directory or other filesystem object) to
952  * the archive.
953  */
954 static void
955 write_file(struct bsdtar *bsdtar, struct archive *a,
956     struct archive_entry *entry)
957 {
958 	write_entry(bsdtar, a, entry);
959 }
960 
961 /*
962  * Write a single entry to the archive.
963  */
964 static void
965 write_entry(struct bsdtar *bsdtar, struct archive *a,
966     struct archive_entry *entry)
967 {
968 	int e;
969 
970 	e = archive_write_header(a, entry);
971 	if (e != ARCHIVE_OK) {
972 		if (bsdtar->verbose > 1) {
973 			safe_fprintf(stderr, "a ");
974 			list_item_verbose(bsdtar, stderr, entry);
975 			lafe_warnc(0, ": %s", archive_error_string(a));
976 		} else if (bsdtar->verbose > 0) {
977 			lafe_warnc(0, "%s: %s",
978 			    archive_entry_pathname(entry),
979 			    archive_error_string(a));
980 		} else
981 			fprintf(stderr, ": %s", archive_error_string(a));
982 	}
983 
984 	if (e == ARCHIVE_FATAL)
985 		exit(1);
986 
987 	/*
988 	 * If we opened a file earlier, write it out now.  Note that
989 	 * the format handler might have reset the size field to zero
990 	 * to inform us that the archive body won't get stored.  In
991 	 * that case, just skip the write.
992 	 */
993 	if (e >= ARCHIVE_WARN && archive_entry_size(entry) > 0) {
994 		if (copy_file_data_block(bsdtar, a, bsdtar->diskreader, entry))
995 			exit(1);
996 	}
997 }
998 
999 static void
1000 report_write(struct bsdtar *bsdtar, struct archive *a,
1001     struct archive_entry *entry, int64_t progress)
1002 {
1003 	uint64_t comp, uncomp;
1004 	int compression;
1005 
1006 	if (bsdtar->verbose)
1007 		fprintf(stderr, "\n");
1008 	comp = archive_filter_bytes(a, -1);
1009 	uncomp = archive_filter_bytes(a, 0);
1010 	fprintf(stderr, "In: %d files, %s bytes;",
1011 	    archive_file_count(a), tar_i64toa(uncomp));
1012 	if (comp > uncomp)
1013 		compression = 0;
1014 	else
1015 		compression = (int)((uncomp - comp) * 100 / uncomp);
1016 	fprintf(stderr,
1017 	    " Out: %s bytes, compression %d%%\n",
1018 	    tar_i64toa(comp), compression);
1019 	/* Can't have two calls to tar_i64toa() pending, so split the output. */
1020 	safe_fprintf(stderr, "Current: %s (%s",
1021 	    archive_entry_pathname(entry),
1022 	    tar_i64toa(progress));
1023 	fprintf(stderr, "/%s bytes)\n",
1024 	    tar_i64toa(archive_entry_size(entry)));
1025 }
1026 
1027 static void
1028 test_for_append(struct bsdtar *bsdtar)
1029 {
1030 	struct stat s;
1031 
1032 	if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
1033 		lafe_errc(1, 0, "no files or directories specified");
1034 	if (bsdtar->filename == NULL)
1035 		lafe_errc(1, 0, "Cannot append to stdout.");
1036 
1037 	if (stat(bsdtar->filename, &s) != 0)
1038 		return;
1039 
1040 	if (!S_ISREG(s.st_mode) && !S_ISBLK(s.st_mode))
1041 		lafe_errc(1, 0,
1042 		    "Cannot append to %s: not a regular file.",
1043 		    bsdtar->filename);
1044 
1045 /* Is this an appropriate check here on Windows? */
1046 /*
1047 	if (GetFileType(handle) != FILE_TYPE_DISK)
1048 		lafe_errc(1, 0, "Cannot append");
1049 */
1050 
1051 }
1052