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