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