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