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