xref: /netbsd-src/external/bsd/libarchive/dist/tar/write.c (revision 4e6df137e8e14049b5a701d249962c480449c141)
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25 
26 #include "bsdtar_platform.h"
27 __FBSDID("$FreeBSD: src/usr.bin/tar/write.c,v 1.79 2008/11/27 05:49:52 kientzle Exp $");
28 
29 #ifdef HAVE_SYS_TYPES_H
30 #include <sys/types.h>
31 #endif
32 #ifdef HAVE_SYS_IOCTL_H
33 #include <sys/ioctl.h>
34 #endif
35 #ifdef HAVE_SYS_STAT_H
36 #include <sys/stat.h>
37 #endif
38 #ifdef HAVE_ATTR_XATTR_H
39 #include <attr/xattr.h>
40 #endif
41 #ifdef HAVE_ERRNO_H
42 #include <errno.h>
43 #endif
44 #ifdef HAVE_FCNTL_H
45 #include <fcntl.h>
46 #endif
47 #ifdef HAVE_GRP_H
48 #include <grp.h>
49 #endif
50 #ifdef HAVE_IO_H
51 #include <io.h>
52 #endif
53 #ifdef HAVE_LIMITS_H
54 #include <limits.h>
55 #endif
56 #ifdef HAVE_LINUX_FS_H
57 #include <linux/fs.h>	/* for Linux file flags */
58 #endif
59 /*
60  * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
61  * As the include guards don't agree, the order of include is important.
62  */
63 #ifdef HAVE_LINUX_EXT2_FS_H
64 #include <linux/ext2_fs.h>	/* for Linux file flags */
65 #endif
66 #if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
67 /* This header exists but is broken on Cygwin. */
68 #include <ext2fs/ext2_fs.h>
69 #endif
70 #ifdef HAVE_PWD_H
71 #include <pwd.h>
72 #endif
73 #ifdef HAVE_STDINT_H
74 #include <stdint.h>
75 #endif
76 #include <stdio.h>
77 #ifdef HAVE_STDLIB_H
78 #include <stdlib.h>
79 #endif
80 #ifdef HAVE_STRING_H
81 #include <string.h>
82 #endif
83 #ifdef HAVE_UNISTD_H
84 #include <unistd.h>
85 #endif
86 
87 #include "bsdtar.h"
88 #include "err.h"
89 #include "line_reader.h"
90 #include "tree.h"
91 
92 /* Size of buffer for holding file data prior to writing. */
93 #define FILEDATABUFLEN	65536
94 
95 /* Fixed size of uname/gname caches. */
96 #define	name_cache_size 101
97 
98 static const char * const NO_NAME = "(noname)";
99 
100 struct archive_dir_entry {
101 	struct archive_dir_entry	*next;
102 	time_t			 mtime_sec;
103 	int			 mtime_nsec;
104 	char			*name;
105 };
106 
107 struct archive_dir {
108 	struct archive_dir_entry *head, *tail;
109 };
110 
111 struct name_cache {
112 	int	probes;
113 	int	hits;
114 	size_t	size;
115 	struct {
116 		id_t id;
117 		const char *name;
118 	} cache[name_cache_size];
119 };
120 
121 static void		 add_dir_list(struct bsdtar *bsdtar, const char *path,
122 			     time_t mtime_sec, int mtime_nsec);
123 static int		 append_archive(struct bsdtar *, struct archive *,
124 			     struct archive *ina);
125 static int		 append_archive_filename(struct bsdtar *,
126 			     struct archive *, const char *fname);
127 static void		 archive_names_from_file(struct bsdtar *bsdtar,
128 			     struct archive *a);
129 static int		 copy_file_data(struct bsdtar *, struct archive *a,
130 			     struct archive *ina, struct archive_entry *);
131 static int		 new_enough(struct bsdtar *, const char *path,
132 			     const struct stat *);
133 static void		 report_write(struct bsdtar *, struct archive *,
134 			     struct archive_entry *, int64_t progress);
135 static void		 test_for_append(struct bsdtar *);
136 static void		 write_archive(struct archive *, struct bsdtar *);
137 static void		 write_entry_backend(struct bsdtar *, struct archive *,
138 			     struct archive_entry *);
139 static int		 write_file_data(struct bsdtar *, struct archive *,
140 			     struct archive_entry *, int fd);
141 static void		 write_hierarchy(struct bsdtar *, struct archive *,
142 			     const char *);
143 
144 #if defined(_WIN32) && !defined(__CYGWIN__)
145 /* Not a full lseek() emulation, but enough for our needs here. */
146 static int
147 seek_file(int fd, int64_t offset, int whence)
148 {
149 	LARGE_INTEGER distance;
150 	(void)whence; /* UNUSED */
151 	distance.QuadPart = offset;
152 	return (SetFilePointerEx((HANDLE)_get_osfhandle(fd),
153 		distance, NULL, FILE_BEGIN) ? 1 : -1);
154 }
155 #define open _open
156 #define close _close
157 #define read _read
158 #define lseek seek_file
159 #endif
160 
161 void
162 tar_mode_c(struct bsdtar *bsdtar)
163 {
164 	struct archive *a;
165 	int r;
166 
167 	if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
168 		lafe_errc(1, 0, "no files or directories specified");
169 
170 	a = archive_write_new();
171 
172 	/* Support any format that the library supports. */
173 	if (bsdtar->create_format == NULL) {
174 		r = archive_write_set_format_pax_restricted(a);
175 		bsdtar->create_format = "pax restricted";
176 	} else {
177 		r = archive_write_set_format_by_name(a, bsdtar->create_format);
178 	}
179 	if (r != ARCHIVE_OK) {
180 		fprintf(stderr, "Can't use format %s: %s\n",
181 		    bsdtar->create_format,
182 		    archive_error_string(a));
183 		usage();
184 	}
185 
186 	/*
187 	 * If user explicitly set the block size, then assume they
188 	 * want the last block padded as well.  Otherwise, use the
189 	 * default block size and accept archive_write_open_file()'s
190 	 * default padding decisions.
191 	 */
192 	if (bsdtar->bytes_per_block != 0) {
193 		archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
194 		archive_write_set_bytes_in_last_block(a,
195 		    bsdtar->bytes_per_block);
196 	} else
197 		archive_write_set_bytes_per_block(a, DEFAULT_BYTES_PER_BLOCK);
198 
199 	if (bsdtar->compress_program) {
200 		archive_write_set_compression_program(a, bsdtar->compress_program);
201 	} else {
202 		switch (bsdtar->create_compression) {
203 		case 0:
204 			r = archive_write_set_compression_none(a);
205 			break;
206 		case 'j': case 'y':
207 			r = archive_write_set_compression_bzip2(a);
208 			break;
209 		case 'J':
210 			r = archive_write_set_compression_xz(a);
211 			break;
212 		case OPTION_LZMA:
213 			archive_write_set_compression_lzma(a);
214 			break;
215 		case 'z':
216 			r = archive_write_set_compression_gzip(a);
217 			break;
218 		case 'Z':
219 			r = archive_write_set_compression_compress(a);
220 			break;
221 		default:
222 			lafe_errc(1, 0,
223 			    "Unrecognized compression option -%c",
224 			    bsdtar->create_compression);
225 		}
226 		if (r != ARCHIVE_OK) {
227 			lafe_errc(1, 0,
228 			    "Unsupported compression option -%c",
229 			    bsdtar->create_compression);
230 		}
231 	}
232 
233 	if (ARCHIVE_OK != archive_write_set_options(a, bsdtar->option_options))
234 		lafe_errc(1, 0, "%s", archive_error_string(a));
235 	if (ARCHIVE_OK != archive_write_open_file(a, bsdtar->filename))
236 		lafe_errc(1, 0, "%s", archive_error_string(a));
237 	write_archive(a, bsdtar);
238 }
239 
240 /*
241  * Same as 'c', except we only support tar or empty formats in
242  * uncompressed files on disk.
243  */
244 void
245 tar_mode_r(struct bsdtar *bsdtar)
246 {
247 	int64_t	end_offset;
248 	int	format;
249 	struct archive *a;
250 	struct archive_entry *entry;
251 	int	r;
252 
253 	/* Sanity-test some arguments and the file. */
254 	test_for_append(bsdtar);
255 
256 	format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
257 
258 #if defined(__BORLANDC__)
259 	bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT);
260 #else
261 	bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT, 0666);
262 #endif
263 	if (bsdtar->fd < 0)
264 		lafe_errc(1, errno,
265 		    "Cannot open %s", bsdtar->filename);
266 
267 	a = archive_read_new();
268 	archive_read_support_compression_all(a);
269 	archive_read_support_format_tar(a);
270 	archive_read_support_format_gnutar(a);
271 	r = archive_read_open_fd(a, bsdtar->fd, 10240);
272 	if (r != ARCHIVE_OK)
273 		lafe_errc(1, archive_errno(a),
274 		    "Can't read archive %s: %s", bsdtar->filename,
275 		    archive_error_string(a));
276 	while (0 == archive_read_next_header(a, &entry)) {
277 		if (archive_compression(a) != ARCHIVE_COMPRESSION_NONE) {
278 			archive_read_finish(a);
279 			close(bsdtar->fd);
280 			lafe_errc(1, 0,
281 			    "Cannot append to compressed archive.");
282 		}
283 		/* Keep going until we hit end-of-archive */
284 		format = archive_format(a);
285 	}
286 
287 	end_offset = archive_read_header_position(a);
288 	archive_read_finish(a);
289 
290 	/* Re-open archive for writing */
291 	a = archive_write_new();
292 	archive_write_set_compression_none(a);
293 	/*
294 	 * Set the format to be used for writing.  To allow people to
295 	 * extend empty files, we need to allow them to specify the format,
296 	 * which opens the possibility that they will specify a format that
297 	 * doesn't match the existing format.  Hence, the following bit
298 	 * of arcane ugliness.
299 	 */
300 
301 	if (bsdtar->create_format != NULL) {
302 		/* If the user requested a format, use that, but ... */
303 		archive_write_set_format_by_name(a,
304 		    bsdtar->create_format);
305 		/* ... complain if it's not compatible. */
306 		format &= ARCHIVE_FORMAT_BASE_MASK;
307 		if (format != (int)(archive_format(a) & ARCHIVE_FORMAT_BASE_MASK)
308 		    && format != ARCHIVE_FORMAT_EMPTY) {
309 			lafe_errc(1, 0,
310 			    "Format %s is incompatible with the archive %s.",
311 			    bsdtar->create_format, bsdtar->filename);
312 		}
313 	} else {
314 		/*
315 		 * Just preserve the current format, with a little care
316 		 * for formats that libarchive can't write.
317 		 */
318 		if (format == ARCHIVE_FORMAT_TAR_GNUTAR)
319 			/* TODO: When gtar supports pax, use pax restricted. */
320 			format = ARCHIVE_FORMAT_TAR_USTAR;
321 		if (format == ARCHIVE_FORMAT_EMPTY)
322 			format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
323 		archive_write_set_format(a, format);
324 	}
325 	if (lseek(bsdtar->fd, end_offset, SEEK_SET) < 0)
326 		lafe_errc(1, errno, "Could not seek to archive end");
327 	if (ARCHIVE_OK != archive_write_set_options(a, bsdtar->option_options))
328 		lafe_errc(1, 0, "%s", archive_error_string(a));
329 	if (ARCHIVE_OK != archive_write_open_fd(a, bsdtar->fd))
330 		lafe_errc(1, 0, "%s", archive_error_string(a));
331 
332 	write_archive(a, bsdtar); /* XXX check return val XXX */
333 
334 	close(bsdtar->fd);
335 	bsdtar->fd = -1;
336 }
337 
338 void
339 tar_mode_u(struct bsdtar *bsdtar)
340 {
341 	int64_t			 end_offset;
342 	struct archive		*a;
343 	struct archive_entry	*entry;
344 	int			 format;
345 	struct archive_dir_entry	*p;
346 	struct archive_dir	 archive_dir;
347 
348 	bsdtar->archive_dir = &archive_dir;
349 	memset(&archive_dir, 0, sizeof(archive_dir));
350 
351 	format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
352 
353 	/* Sanity-test some arguments and the file. */
354 	test_for_append(bsdtar);
355 
356 	bsdtar->fd = open(bsdtar->filename, O_RDWR);
357 	if (bsdtar->fd < 0)
358 		lafe_errc(1, errno,
359 		    "Cannot open %s", bsdtar->filename);
360 
361 	a = archive_read_new();
362 	archive_read_support_compression_all(a);
363 	archive_read_support_format_tar(a);
364 	archive_read_support_format_gnutar(a);
365 	if (archive_read_open_fd(a, bsdtar->fd,
366 	    bsdtar->bytes_per_block != 0 ? bsdtar->bytes_per_block :
367 		DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK) {
368 		lafe_errc(1, 0,
369 		    "Can't open %s: %s", bsdtar->filename,
370 		    archive_error_string(a));
371 	}
372 
373 	/* Build a list of all entries and their recorded mod times. */
374 	while (0 == archive_read_next_header(a, &entry)) {
375 		if (archive_compression(a) != ARCHIVE_COMPRESSION_NONE) {
376 			archive_read_finish(a);
377 			close(bsdtar->fd);
378 			lafe_errc(1, 0,
379 			    "Cannot append to compressed archive.");
380 		}
381 		add_dir_list(bsdtar, archive_entry_pathname(entry),
382 		    archive_entry_mtime(entry),
383 		    archive_entry_mtime_nsec(entry));
384 		/* Record the last format determination we see */
385 		format = archive_format(a);
386 		/* Keep going until we hit end-of-archive */
387 	}
388 
389 	end_offset = archive_read_header_position(a);
390 	archive_read_finish(a);
391 
392 	/* Re-open archive for writing. */
393 	a = archive_write_new();
394 	archive_write_set_compression_none(a);
395 	/*
396 	 * Set format to same one auto-detected above, except that
397 	 * we don't write GNU tar format, so use ustar instead.
398 	 */
399 	if (format == ARCHIVE_FORMAT_TAR_GNUTAR)
400 		format = ARCHIVE_FORMAT_TAR_USTAR;
401 	archive_write_set_format(a, format);
402 	if (bsdtar->bytes_per_block != 0) {
403 		archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
404 		archive_write_set_bytes_in_last_block(a,
405 		    bsdtar->bytes_per_block);
406 	} else
407 		archive_write_set_bytes_per_block(a, DEFAULT_BYTES_PER_BLOCK);
408 	if (lseek(bsdtar->fd, end_offset, SEEK_SET) < 0)
409 		lafe_errc(1, errno, "Could not seek to archive end");
410 	if (ARCHIVE_OK != archive_write_set_options(a, bsdtar->option_options))
411 		lafe_errc(1, 0, "%s", archive_error_string(a));
412 	if (ARCHIVE_OK != archive_write_open_fd(a, bsdtar->fd))
413 		lafe_errc(1, 0, "%s", archive_error_string(a));
414 
415 	write_archive(a, bsdtar);
416 
417 	close(bsdtar->fd);
418 	bsdtar->fd = -1;
419 
420 	while (bsdtar->archive_dir->head != NULL) {
421 		p = bsdtar->archive_dir->head->next;
422 		free(bsdtar->archive_dir->head->name);
423 		free(bsdtar->archive_dir->head);
424 		bsdtar->archive_dir->head = p;
425 	}
426 	bsdtar->archive_dir->tail = NULL;
427 }
428 
429 
430 /*
431  * Write user-specified files/dirs to opened archive.
432  */
433 static void
434 write_archive(struct archive *a, struct bsdtar *bsdtar)
435 {
436 	const char *arg;
437 	struct archive_entry *entry, *sparse_entry;
438 
439 	/* Allocate a buffer for file data. */
440 	if ((bsdtar->buff = malloc(FILEDATABUFLEN)) == NULL)
441 		lafe_errc(1, 0, "cannot allocate memory");
442 
443 	if ((bsdtar->resolver = archive_entry_linkresolver_new()) == NULL)
444 		lafe_errc(1, 0, "cannot create link resolver");
445 	archive_entry_linkresolver_set_strategy(bsdtar->resolver,
446 	    archive_format(a));
447 	if ((bsdtar->diskreader = archive_read_disk_new()) == NULL)
448 		lafe_errc(1, 0, "Cannot create read_disk object");
449 	archive_read_disk_set_standard_lookup(bsdtar->diskreader);
450 
451 	if (bsdtar->names_from_file != NULL)
452 		archive_names_from_file(bsdtar, a);
453 
454 	while (*bsdtar->argv) {
455 		arg = *bsdtar->argv;
456 		if (arg[0] == '-' && arg[1] == 'C') {
457 			arg += 2;
458 			if (*arg == '\0') {
459 				bsdtar->argv++;
460 				arg = *bsdtar->argv;
461 				if (arg == NULL) {
462 					lafe_warnc(0, "%s",
463 					    "Missing argument for -C");
464 					bsdtar->return_value = 1;
465 					goto cleanup;
466 				}
467 			}
468 			set_chdir(bsdtar, arg);
469 		} else {
470 			if (*arg != '/' && (arg[0] != '@' || arg[1] != '/'))
471 				do_chdir(bsdtar); /* Handle a deferred -C */
472 			if (*arg == '@') {
473 				if (append_archive_filename(bsdtar, a,
474 				    arg + 1) != 0)
475 					break;
476 			} else
477 				write_hierarchy(bsdtar, a, arg);
478 		}
479 		bsdtar->argv++;
480 	}
481 
482 	entry = NULL;
483 	archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
484 	while (entry != NULL) {
485 		write_entry_backend(bsdtar, a, entry);
486 		archive_entry_free(entry);
487 		entry = NULL;
488 		archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
489 	}
490 
491 	if (archive_write_close(a)) {
492 		lafe_warnc(0, "%s", archive_error_string(a));
493 		bsdtar->return_value = 1;
494 	}
495 
496 cleanup:
497 	/* Free file data buffer. */
498 	free(bsdtar->buff);
499 	archive_entry_linkresolver_free(bsdtar->resolver);
500 	bsdtar->resolver = NULL;
501 	archive_read_finish(bsdtar->diskreader);
502 	bsdtar->diskreader = NULL;
503 
504 	if (bsdtar->option_totals) {
505 		fprintf(stderr, "Total bytes written: %s\n",
506 		    tar_i64toa(archive_position_compressed(a)));
507 	}
508 
509 	archive_write_finish(a);
510 }
511 
512 /*
513  * Archive names specified in file.
514  *
515  * Unless --null was specified, a line containing exactly "-C" will
516  * cause the next line to be a directory to pass to chdir().  If
517  * --null is specified, then a line "-C" is just another filename.
518  */
519 static void
520 archive_names_from_file(struct bsdtar *bsdtar, struct archive *a)
521 {
522 	struct lafe_line_reader *lr;
523 	const char *line;
524 
525 	bsdtar->next_line_is_dir = 0;
526 
527 	lr = lafe_line_reader(bsdtar->names_from_file, bsdtar->option_null);
528 	while ((line = lafe_line_reader_next(lr)) != NULL) {
529 		if (bsdtar->next_line_is_dir) {
530 			set_chdir(bsdtar, line);
531 			bsdtar->next_line_is_dir = 0;
532 		} else if (!bsdtar->option_null && strcmp(line, "-C") == 0)
533 			bsdtar->next_line_is_dir = 1;
534 		else {
535 			if (*line != '/')
536 				do_chdir(bsdtar); /* Handle a deferred -C */
537 			write_hierarchy(bsdtar, a, line);
538 		}
539 	}
540 	lafe_line_reader_free(lr);
541 	if (bsdtar->next_line_is_dir)
542 		lafe_errc(1, errno,
543 		    "Unexpected end of filename list; "
544 		    "directory expected after -C");
545 }
546 
547 /*
548  * Copy from specified archive to current archive.  Returns non-zero
549  * for write errors (which force us to terminate the entire archiving
550  * operation).  If there are errors reading the input archive, we set
551  * bsdtar->return_value but return zero, so the overall archiving
552  * operation will complete and return non-zero.
553  */
554 static int
555 append_archive_filename(struct bsdtar *bsdtar, struct archive *a,
556     const char *filename)
557 {
558 	struct archive *ina;
559 	int rc;
560 
561 	if (strcmp(filename, "-") == 0)
562 		filename = NULL; /* Library uses NULL for stdio. */
563 
564 	ina = archive_read_new();
565 	archive_read_support_format_all(ina);
566 	archive_read_support_compression_all(ina);
567 	if (archive_read_open_file(ina, filename, 10240)) {
568 		lafe_warnc(0, "%s", archive_error_string(ina));
569 		bsdtar->return_value = 1;
570 		return (0);
571 	}
572 
573 	rc = append_archive(bsdtar, a, ina);
574 
575 	if (rc != ARCHIVE_OK) {
576 		lafe_warnc(0, "Error reading archive %s: %s",
577 		    filename, archive_error_string(ina));
578 		bsdtar->return_value = 1;
579 	}
580 	archive_read_finish(ina);
581 
582 	return (rc);
583 }
584 
585 static int
586 append_archive(struct bsdtar *bsdtar, struct archive *a, struct archive *ina)
587 {
588 	struct archive_entry *in_entry;
589 	int e;
590 
591 	while (0 == archive_read_next_header(ina, &in_entry)) {
592 		if (!new_enough(bsdtar, archive_entry_pathname(in_entry),
593 			archive_entry_stat(in_entry)))
594 			continue;
595 		if (lafe_excluded(bsdtar->matching, archive_entry_pathname(in_entry)))
596 			continue;
597 		if (bsdtar->option_interactive &&
598 		    !yes("copy '%s'", archive_entry_pathname(in_entry)))
599 			continue;
600 		if (bsdtar->verbose)
601 			safe_fprintf(stderr, "a %s",
602 			    archive_entry_pathname(in_entry));
603 		if (need_report())
604 			report_write(bsdtar, a, in_entry, 0);
605 
606 		e = archive_write_header(a, in_entry);
607 		if (e != ARCHIVE_OK) {
608 			if (!bsdtar->verbose)
609 				lafe_warnc(0, "%s: %s",
610 				    archive_entry_pathname(in_entry),
611 				    archive_error_string(a));
612 			else
613 				fprintf(stderr, ": %s", archive_error_string(a));
614 		}
615 		if (e == ARCHIVE_FATAL)
616 			exit(1);
617 
618 		if (e >= ARCHIVE_WARN) {
619 			if (archive_entry_size(in_entry) == 0)
620 				archive_read_data_skip(ina);
621 			else if (copy_file_data(bsdtar, a, ina, in_entry))
622 				exit(1);
623 		}
624 
625 		if (bsdtar->verbose)
626 			fprintf(stderr, "\n");
627 	}
628 
629 	/* Note: If we got here, we saw no write errors, so return success. */
630 	return (0);
631 }
632 
633 /* Helper function to copy data between archives. */
634 static int
635 copy_file_data(struct bsdtar *bsdtar, struct archive *a,
636     struct archive *ina, struct archive_entry *entry)
637 {
638 	ssize_t	bytes_read;
639 	ssize_t	bytes_written;
640 	int64_t	progress = 0;
641 
642 	bytes_read = archive_read_data(ina, bsdtar->buff, FILEDATABUFLEN);
643 	while (bytes_read > 0) {
644 		if (need_report())
645 			report_write(bsdtar, a, entry, progress);
646 
647 		bytes_written = archive_write_data(a, bsdtar->buff,
648 		    bytes_read);
649 		if (bytes_written < bytes_read) {
650 			lafe_warnc(0, "%s", archive_error_string(a));
651 			return (-1);
652 		}
653 		progress += bytes_written;
654 		bytes_read = archive_read_data(ina, bsdtar->buff,
655 		    FILEDATABUFLEN);
656 	}
657 
658 	return (0);
659 }
660 
661 /*
662  * Add the file or dir hierarchy named by 'path' to the archive
663  */
664 static void
665 write_hierarchy(struct bsdtar *bsdtar, struct archive *a, const char *path)
666 {
667 	struct archive_entry *entry = NULL, *spare_entry = NULL;
668 	struct tree *tree;
669 	char symlink_mode = bsdtar->symlink_mode;
670 	dev_t first_dev = 0;
671 	int dev_recorded = 0;
672 	int tree_ret;
673 
674 	tree = tree_open(path);
675 
676 	if (!tree) {
677 		lafe_warnc(errno, "%s: Cannot open", path);
678 		bsdtar->return_value = 1;
679 		return;
680 	}
681 
682 	while ((tree_ret = tree_next(tree)) != 0) {
683 		int r;
684 		const char *name = tree_current_path(tree);
685 		const struct stat *st = NULL; /* info to use for this entry */
686 		const struct stat *lst = NULL; /* lstat() information */
687 		int descend;
688 
689 		if (tree_ret == TREE_ERROR_FATAL)
690 			lafe_errc(1, tree_errno(tree),
691 			    "%s: Unable to continue traversing directory tree",
692 			    name);
693 		if (tree_ret == TREE_ERROR_DIR) {
694 			lafe_warnc(errno,
695 			    "%s: Couldn't visit directory", name);
696 			bsdtar->return_value = 1;
697 		}
698 		if (tree_ret != TREE_REGULAR)
699 			continue;
700 
701 		/*
702 		 * If this file/dir is excluded by a filename
703 		 * pattern, skip it.
704 		 */
705 		if (lafe_excluded(bsdtar->matching, name))
706 			continue;
707 
708 		/*
709 		 * Get lstat() info from the tree library.
710 		 */
711 		lst = tree_current_lstat(tree);
712 		if (lst == NULL) {
713 			/* Couldn't lstat(); must not exist. */
714 			lafe_warnc(errno, "%s: Cannot stat", name);
715 			/* Return error if files disappear during traverse. */
716 			bsdtar->return_value = 1;
717 			continue;
718 		}
719 
720 		/*
721 		 * Distinguish 'L'/'P'/'H' symlink following.
722 		 */
723 		switch(symlink_mode) {
724 		case 'H':
725 			/* 'H': After the first item, rest like 'P'. */
726 			symlink_mode = 'P';
727 			/* 'H': First item (from command line) like 'L'. */
728 			/* FALLTHROUGH */
729 		case 'L':
730 			/* 'L': Do descend through a symlink to dir. */
731 			descend = tree_current_is_dir(tree);
732 			/* 'L': Follow symlinks to files. */
733 			archive_read_disk_set_symlink_logical(bsdtar->diskreader);
734 			/* 'L': Archive symlinks as targets, if we can. */
735 			st = tree_current_stat(tree);
736 			if (st != NULL)
737 				break;
738 			/* If stat fails, we have a broken symlink;
739 			 * in that case, don't follow the link. */
740 			/* FALLTHROUGH */
741 		default:
742 			/* 'P': Don't descend through a symlink to dir. */
743 			descend = tree_current_is_physical_dir(tree);
744 			/* 'P': Don't follow symlinks to files. */
745 			archive_read_disk_set_symlink_physical(bsdtar->diskreader);
746 			/* 'P': Archive symlinks as symlinks. */
747 			st = lst;
748 			break;
749 		}
750 
751 		/*
752 		 * Are we about to cross to a new filesystem?
753 		 */
754 		if (!dev_recorded) {
755 			/* This is the initial file system. */
756 			first_dev = lst->st_dev;
757 			dev_recorded = 1;
758 		} else if (lst->st_dev == first_dev) {
759 			/* The starting file system is always acceptable. */
760 		} else if (descend == 0) {
761 			/* We're not descending, so no need to check. */
762 		} else if (bsdtar->option_dont_traverse_mounts) {
763 			/* User has asked us not to cross mount points. */
764 			descend = 0;
765 		} else {
766 			/* We're prepared to cross a mount point. */
767 
768 			/* XXX TODO: check whether this filesystem is
769 			 * synthetic and/or local.  Add a new
770 			 * --local-only option to skip non-local
771 			 * filesystems.  Skip synthetic filesystems
772 			 * regardless.
773 			 *
774 			 * The results should be cached, since
775 			 * tree.c doesn't usually visit a directory
776 			 * and the directory contents together.  A simple
777 			 * move-to-front list should perform quite well.
778 			 *
779 			 * This is going to be heavily OS dependent:
780 			 * FreeBSD's statfs() in conjunction with getvfsbyname()
781 			 * provides all of this; NetBSD's statvfs() does
782 			 * most of it; other systems will vary.
783 			 */
784 		}
785 
786 		/*
787 		 * In -u mode, check that the file is newer than what's
788 		 * already in the archive; in all modes, obey --newerXXX flags.
789 		 */
790 		if (!new_enough(bsdtar, name, st))
791 			continue;
792 
793 		archive_entry_free(entry);
794 		entry = archive_entry_new();
795 
796 		archive_entry_set_pathname(entry, name);
797 		archive_entry_copy_sourcepath(entry,
798 		    tree_current_access_path(tree));
799 
800 		/* Populate the archive_entry with metadata from the disk. */
801 		/* XXX TODO: Arrange to open a regular file before
802 		 * calling this so we can pass in an fd and shorten
803 		 * the race to query metadata.  The linkify dance
804 		 * makes this more complex than it might sound. */
805 #if defined(_WIN32) && !defined(__CYGWIN__)
806 		/* TODO: tree.c uses stat(), which is badly broken
807 		 * on Windows.  To fix this, we should
808 		 * deprecate tree_current_stat() and provide a new
809 		 * call tree_populate_entry(t, entry).  This call
810 		 * would use stat() internally on POSIX and
811 		 * GetInfoByFileHandle() internally on Windows.
812 		 * This would be another step towards a tree-walker
813 		 * that can be integrated deep into libarchive.
814 		 * For now, just set st to NULL on Windows;
815 		 * archive_read_disk_entry_from_file() should
816 		 * be smart enough to use platform-appropriate
817 		 * ways to probe file information.
818 		 */
819 		st = NULL;
820 #endif
821 		r = archive_read_disk_entry_from_file(bsdtar->diskreader,
822 		    entry, -1, st);
823 		if (r != ARCHIVE_OK)
824 			lafe_warnc(archive_errno(bsdtar->diskreader),
825 			    "%s", archive_error_string(bsdtar->diskreader));
826 		if (r < ARCHIVE_WARN)
827 			continue;
828 
829 		/* XXX TODO: Just use flag data from entry; avoid the
830 		 * duplicate check here. */
831 
832 		/*
833 		 * If this file/dir is flagged "nodump" and we're
834 		 * honoring such flags, skip this file/dir.
835 		 */
836 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
837 		/* BSD systems store flags in struct stat */
838 		if (bsdtar->option_honor_nodump &&
839 		    (lst->st_flags & UF_NODUMP))
840 			continue;
841 #endif
842 
843 #if defined(EXT2_IOC_GETFLAGS) && defined(EXT2_NODUMP_FL)
844 		/* Linux uses ioctl to read flags. */
845 		if (bsdtar->option_honor_nodump) {
846 			int fd = open(name, O_RDONLY | O_NONBLOCK);
847 			if (fd >= 0) {
848 				unsigned long fflags;
849 				int r = ioctl(fd, EXT2_IOC_GETFLAGS, &fflags);
850 				close(fd);
851 				if (r >= 0 && (fflags & EXT2_NODUMP_FL))
852 					continue;
853 			}
854 		}
855 #endif
856 
857 		/*
858 		 * If the user vetoes this file/directory, skip it.
859 		 * We want this to be fairly late; if some other
860 		 * check would veto this file, we shouldn't bother
861 		 * the user with it.
862 		 */
863 		if (bsdtar->option_interactive &&
864 		    !yes("add '%s'", name))
865 			continue;
866 
867 		/* Note: if user vetoes, we won't descend. */
868 		if (descend && !bsdtar->option_no_subdirs)
869 			tree_descend(tree);
870 
871 		/*
872 		 * Rewrite the pathname to be archived.  If rewrite
873 		 * fails, skip the entry.
874 		 */
875 		if (edit_pathname(bsdtar, entry))
876 			continue;
877 
878 		/* Display entry as we process it.
879 		 * This format is required by SUSv2. */
880 		if (bsdtar->verbose)
881 			safe_fprintf(stderr, "a %s",
882 			    archive_entry_pathname(entry));
883 
884 		/* Non-regular files get archived with zero size. */
885 		if (archive_entry_filetype(entry) != AE_IFREG)
886 			archive_entry_set_size(entry, 0);
887 
888 		archive_entry_linkify(bsdtar->resolver, &entry, &spare_entry);
889 
890 		while (entry != NULL) {
891 			write_entry_backend(bsdtar, a, entry);
892 			archive_entry_free(entry);
893 			entry = spare_entry;
894 			spare_entry = NULL;
895 		}
896 
897 		if (bsdtar->verbose)
898 			fprintf(stderr, "\n");
899 	}
900 	archive_entry_free(entry);
901 	tree_close(tree);
902 }
903 
904 /*
905  * Backend for write_entry.
906  */
907 static void
908 write_entry_backend(struct bsdtar *bsdtar, struct archive *a,
909     struct archive_entry *entry)
910 {
911 	int fd = -1;
912 	int e;
913 
914 	if (archive_entry_size(entry) > 0) {
915 		const char *pathname = archive_entry_sourcepath(entry);
916 		fd = open(pathname, O_RDONLY);
917 		if (fd == -1) {
918 			if (!bsdtar->verbose)
919 				lafe_warnc(errno,
920 				    "%s: could not open file", pathname);
921 			else
922 				fprintf(stderr, ": %s", strerror(errno));
923 			return;
924 		}
925 	}
926 
927 	e = archive_write_header(a, entry);
928 	if (e != ARCHIVE_OK) {
929 		if (!bsdtar->verbose)
930 			lafe_warnc(0, "%s: %s",
931 			    archive_entry_pathname(entry),
932 			    archive_error_string(a));
933 		else
934 			fprintf(stderr, ": %s", archive_error_string(a));
935 	}
936 
937 	if (e == ARCHIVE_FATAL)
938 		exit(1);
939 
940 	/*
941 	 * If we opened a file earlier, write it out now.  Note that
942 	 * the format handler might have reset the size field to zero
943 	 * to inform us that the archive body won't get stored.  In
944 	 * that case, just skip the write.
945 	 */
946 	if (e >= ARCHIVE_WARN && fd >= 0 && archive_entry_size(entry) > 0) {
947 		if (write_file_data(bsdtar, a, entry, fd))
948 			exit(1);
949 	}
950 
951 	/*
952 	 * If we opened a file, close it now even if there was an error
953 	 * which made us decide not to write the archive body.
954 	 */
955 	if (fd >= 0)
956 		close(fd);
957 }
958 
959 static void
960 report_write(struct bsdtar *bsdtar, struct archive *a,
961     struct archive_entry *entry, int64_t progress)
962 {
963 	uint64_t comp, uncomp;
964 	if (bsdtar->verbose)
965 		fprintf(stderr, "\n");
966 	comp = archive_position_compressed(a);
967 	uncomp = archive_position_uncompressed(a);
968 	fprintf(stderr, "In: %d files, %s bytes;",
969 	    archive_file_count(a), tar_i64toa(uncomp));
970 	fprintf(stderr,
971 	    " Out: %s bytes, compression %d%%\n",
972 	    tar_i64toa(comp), (int)((uncomp - comp) * 100 / uncomp));
973 	/* Can't have two calls to tar_i64toa() pending, so split the output. */
974 	safe_fprintf(stderr, "Current: %s (%s",
975 	    archive_entry_pathname(entry),
976 	    tar_i64toa(progress));
977 	fprintf(stderr, "/%s bytes)\n",
978 	    tar_i64toa(archive_entry_size(entry)));
979 }
980 
981 
982 /* Helper function to copy file to archive. */
983 static int
984 write_file_data(struct bsdtar *bsdtar, struct archive *a,
985     struct archive_entry *entry, int fd)
986 {
987 	ssize_t	bytes_read;
988 	ssize_t	bytes_written;
989 	int64_t	progress = 0;
990 
991 	bytes_read = read(fd, bsdtar->buff, FILEDATABUFLEN);
992 	while (bytes_read > 0) {
993 		if (need_report())
994 			report_write(bsdtar, a, entry, progress);
995 
996 		bytes_written = archive_write_data(a, bsdtar->buff,
997 		    bytes_read);
998 		if (bytes_written < 0) {
999 			/* Write failed; this is bad */
1000 			lafe_warnc(0, "%s", archive_error_string(a));
1001 			return (-1);
1002 		}
1003 		if (bytes_written < bytes_read) {
1004 			/* Write was truncated; warn but continue. */
1005 			lafe_warnc(0,
1006 			    "%s: Truncated write; file may have grown while being archived.",
1007 			    archive_entry_pathname(entry));
1008 			return (0);
1009 		}
1010 		progress += bytes_written;
1011 		bytes_read = read(fd, bsdtar->buff, FILEDATABUFLEN);
1012 	}
1013 	return 0;
1014 }
1015 
1016 /*
1017  * Test if the specified file is new enough to include in the archive.
1018  */
1019 static int
1020 new_enough(struct bsdtar *bsdtar, const char *path, const struct stat *st)
1021 {
1022 	struct archive_dir_entry *p;
1023 
1024 	/*
1025 	 * If this file/dir is excluded by a time comparison, skip it.
1026 	 */
1027 	if (bsdtar->newer_ctime_sec > 0) {
1028 		if (st->st_ctime < bsdtar->newer_ctime_sec)
1029 			return (0); /* Too old, skip it. */
1030 		if (st->st_ctime == bsdtar->newer_ctime_sec
1031 		    && ARCHIVE_STAT_CTIME_NANOS(st)
1032 		    <= bsdtar->newer_ctime_nsec)
1033 			return (0); /* Too old, skip it. */
1034 	}
1035 	if (bsdtar->newer_mtime_sec > 0) {
1036 		if (st->st_mtime < bsdtar->newer_mtime_sec)
1037 			return (0); /* Too old, skip it. */
1038 		if (st->st_mtime == bsdtar->newer_mtime_sec
1039 		    && ARCHIVE_STAT_MTIME_NANOS(st)
1040 		    <= bsdtar->newer_mtime_nsec)
1041 			return (0); /* Too old, skip it. */
1042 	}
1043 
1044 	/*
1045 	 * In -u mode, we only write an entry if it's newer than
1046 	 * what was already in the archive.
1047 	 */
1048 	if (bsdtar->archive_dir != NULL &&
1049 	    bsdtar->archive_dir->head != NULL) {
1050 		for (p = bsdtar->archive_dir->head; p != NULL; p = p->next) {
1051 			if (pathcmp(path, p->name)==0)
1052 				return (p->mtime_sec < st->st_mtime ||
1053 				    (p->mtime_sec == st->st_mtime &&
1054 					p->mtime_nsec
1055 					< ARCHIVE_STAT_MTIME_NANOS(st)));
1056 		}
1057 	}
1058 
1059 	/* If the file wasn't rejected, include it. */
1060 	return (1);
1061 }
1062 
1063 /*
1064  * Add an entry to the dir list for 'u' mode.
1065  *
1066  * XXX TODO: Make this fast.
1067  */
1068 static void
1069 add_dir_list(struct bsdtar *bsdtar, const char *path,
1070     time_t mtime_sec, int mtime_nsec)
1071 {
1072 	struct archive_dir_entry	*p;
1073 
1074 	/*
1075 	 * Search entire list to see if this file has appeared before.
1076 	 * If it has, override the timestamp data.
1077 	 */
1078 	p = bsdtar->archive_dir->head;
1079 	while (p != NULL) {
1080 		if (strcmp(path, p->name)==0) {
1081 			p->mtime_sec = mtime_sec;
1082 			p->mtime_nsec = mtime_nsec;
1083 			return;
1084 		}
1085 		p = p->next;
1086 	}
1087 
1088 	p = malloc(sizeof(*p));
1089 	if (p == NULL)
1090 		lafe_errc(1, ENOMEM, "Can't read archive directory");
1091 
1092 	p->name = strdup(path);
1093 	if (p->name == NULL)
1094 		lafe_errc(1, ENOMEM, "Can't read archive directory");
1095 	p->mtime_sec = mtime_sec;
1096 	p->mtime_nsec = mtime_nsec;
1097 	p->next = NULL;
1098 	if (bsdtar->archive_dir->tail == NULL) {
1099 		bsdtar->archive_dir->head = bsdtar->archive_dir->tail = p;
1100 	} else {
1101 		bsdtar->archive_dir->tail->next = p;
1102 		bsdtar->archive_dir->tail = p;
1103 	}
1104 }
1105 
1106 static void
1107 test_for_append(struct bsdtar *bsdtar)
1108 {
1109 	struct stat s;
1110 
1111 	if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
1112 		lafe_errc(1, 0, "no files or directories specified");
1113 	if (bsdtar->filename == NULL)
1114 		lafe_errc(1, 0, "Cannot append to stdout.");
1115 
1116 	if (bsdtar->create_compression != 0)
1117 		lafe_errc(1, 0,
1118 		    "Cannot append to %s with compression", bsdtar->filename);
1119 
1120 	if (stat(bsdtar->filename, &s) != 0)
1121 		return;
1122 
1123 	if (!S_ISREG(s.st_mode) && !S_ISBLK(s.st_mode))
1124 		lafe_errc(1, 0,
1125 		    "Cannot append to %s: not a regular file.",
1126 		    bsdtar->filename);
1127 
1128 /* Is this an appropriate check here on Windows? */
1129 /*
1130 	if (GetFileType(handle) != FILE_TYPE_DISK)
1131 		lafe_errc(1, 0, "Cannot append");
1132 */
1133 
1134 }
1135