SYSENTER/SYSCALL support
[minix.git] / commands / tar / write.c
blob67595e73fd3feec677e4ea04ec03992965354a14
1 /*-
2 * Copyright (c) 2003-2007 Tim Kientzle
3 * All rights reserved.
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.
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.
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 $");
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
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.
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
87 #include "bsdtar.h"
88 #include "err.h"
89 #include "line_reader.h"
90 #include "tree.h"
92 /* Size of buffer for holding file data prior to writing. */
93 #define FILEDATABUFLEN 65536
95 /* Fixed size of uname/gname caches. */
96 #define name_cache_size 101
98 #ifndef O_BINARY
99 #define O_BINARY 0
100 #endif
102 static const char * const NO_NAME = "(noname)";
104 struct archive_dir_entry {
105 struct archive_dir_entry *next;
106 time_t mtime_sec;
107 int mtime_nsec;
108 char *name;
111 struct archive_dir {
112 struct archive_dir_entry *head, *tail;
115 struct name_cache {
116 int probes;
117 int hits;
118 size_t size;
119 struct {
120 id_t id;
121 const char *name;
122 } cache[name_cache_size];
125 static void add_dir_list(struct bsdtar *bsdtar, const char *path,
126 time_t mtime_sec, int mtime_nsec);
127 static int append_archive(struct bsdtar *, struct archive *,
128 struct archive *ina);
129 static int append_archive_filename(struct bsdtar *,
130 struct archive *, const char *fname);
131 static void archive_names_from_file(struct bsdtar *bsdtar,
132 struct archive *a);
133 static int copy_file_data(struct bsdtar *, struct archive *a,
134 struct archive *ina, struct archive_entry *);
135 static int new_enough(struct bsdtar *, const char *path,
136 const struct stat *);
137 #ifndef __minix
138 static void report_write(struct bsdtar *, struct archive *,
139 struct archive_entry *, int64_t progress);
140 #else
141 static void report_write(struct bsdtar *, struct archive *,
142 struct archive_entry *, int32_t progress);
143 #endif
144 static void test_for_append(struct bsdtar *);
145 static void write_archive(struct archive *, struct bsdtar *);
146 static void write_entry_backend(struct bsdtar *, struct archive *,
147 struct archive_entry *);
148 static int write_file_data(struct bsdtar *, struct archive *,
149 struct archive_entry *, int fd);
150 static void write_hierarchy(struct bsdtar *, struct archive *,
151 const char *);
153 #if defined(_WIN32) && !defined(__CYGWIN__)
154 /* Not a full lseek() emulation, but enough for our needs here. */
155 static int
156 seek_file(int fd, int64_t offset, int whence)
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);
164 #define open _open
165 #define close _close
166 #define read _read
167 #define lseek seek_file
168 #endif
170 void
171 tar_mode_c(struct bsdtar *bsdtar)
173 struct archive *a;
174 int r;
176 if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
177 lafe_errc(1, 0, "no files or directories specified");
179 a = archive_write_new();
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);
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();
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.
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);
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);
235 if (r != ARCHIVE_OK) {
236 lafe_errc(1, 0,
237 "Unsupported compression option -%c",
238 bsdtar->create_compression);
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);
250 * Same as 'c', except we only support tar or empty formats in
251 * uncompressed files on disk.
253 void
254 tar_mode_r(struct bsdtar *bsdtar)
256 #ifndef __minix
257 int64_t end_offset;
258 #else
259 off_t end_offset;
260 #endif
261 int format;
262 struct archive *a;
263 struct archive_entry *entry;
264 int r;
266 /* Sanity-test some arguments and the file. */
267 test_for_append(bsdtar);
269 format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
271 #if defined(__BORLANDC__)
272 bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT | O_BINARY);
273 #else
274 bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT | O_BINARY, 0666);
275 #endif
276 if (bsdtar->fd < 0)
277 lafe_errc(1, errno,
278 "Cannot open %s", bsdtar->filename);
280 a = archive_read_new();
281 archive_read_support_compression_all(a);
282 archive_read_support_format_tar(a);
283 archive_read_support_format_gnutar(a);
284 r = archive_read_open_fd(a, bsdtar->fd, 10240);
285 if (r != ARCHIVE_OK)
286 lafe_errc(1, archive_errno(a),
287 "Can't read archive %s: %s", bsdtar->filename,
288 archive_error_string(a));
289 while (0 == archive_read_next_header(a, &entry)) {
290 if (archive_compression(a) != ARCHIVE_COMPRESSION_NONE) {
291 archive_read_finish(a);
292 close(bsdtar->fd);
293 lafe_errc(1, 0,
294 "Cannot append to compressed archive.");
296 /* Keep going until we hit end-of-archive */
297 format = archive_format(a);
300 end_offset = archive_read_header_position(a);
301 archive_read_finish(a);
303 /* Re-open archive for writing */
304 a = archive_write_new();
305 archive_write_set_compression_none(a);
307 * Set the format to be used for writing. To allow people to
308 * extend empty files, we need to allow them to specify the format,
309 * which opens the possibility that they will specify a format that
310 * doesn't match the existing format. Hence, the following bit
311 * of arcane ugliness.
314 if (bsdtar->create_format != NULL) {
315 /* If the user requested a format, use that, but ... */
316 archive_write_set_format_by_name(a,
317 bsdtar->create_format);
318 /* ... complain if it's not compatible. */
319 format &= ARCHIVE_FORMAT_BASE_MASK;
320 if (format != (int)(archive_format(a) & ARCHIVE_FORMAT_BASE_MASK)
321 && format != ARCHIVE_FORMAT_EMPTY) {
322 lafe_errc(1, 0,
323 "Format %s is incompatible with the archive %s.",
324 bsdtar->create_format, bsdtar->filename);
326 } else {
328 * Just preserve the current format, with a little care
329 * for formats that libarchive can't write.
331 if (format == ARCHIVE_FORMAT_TAR_GNUTAR)
332 /* TODO: When gtar supports pax, use pax restricted. */
333 format = ARCHIVE_FORMAT_TAR_USTAR;
334 if (format == ARCHIVE_FORMAT_EMPTY)
335 format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
336 archive_write_set_format(a, format);
338 if (lseek(bsdtar->fd, end_offset, SEEK_SET) < 0)
339 lafe_errc(1, errno, "Could not seek to archive end");
340 if (ARCHIVE_OK != archive_write_set_options(a, bsdtar->option_options))
341 lafe_errc(1, 0, "%s", archive_error_string(a));
342 if (ARCHIVE_OK != archive_write_open_fd(a, bsdtar->fd))
343 lafe_errc(1, 0, "%s", archive_error_string(a));
345 write_archive(a, bsdtar); /* XXX check return val XXX */
347 close(bsdtar->fd);
348 bsdtar->fd = -1;
351 void
352 tar_mode_u(struct bsdtar *bsdtar)
354 #ifndef __minix
355 int64_t end_offset;
356 #else
357 off_t end_offset;
358 #endif
359 struct archive *a;
360 struct archive_entry *entry;
361 int format;
362 struct archive_dir_entry *p;
363 struct archive_dir archive_dir;
365 bsdtar->archive_dir = &archive_dir;
366 memset(&archive_dir, 0, sizeof(archive_dir));
368 format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
370 /* Sanity-test some arguments and the file. */
371 test_for_append(bsdtar);
373 bsdtar->fd = open(bsdtar->filename, O_RDWR | O_BINARY);
374 if (bsdtar->fd < 0)
375 lafe_errc(1, errno,
376 "Cannot open %s", bsdtar->filename);
378 a = archive_read_new();
379 archive_read_support_compression_all(a);
380 archive_read_support_format_tar(a);
381 archive_read_support_format_gnutar(a);
382 if (archive_read_open_fd(a, bsdtar->fd,
383 bsdtar->bytes_per_block != 0 ? bsdtar->bytes_per_block :
384 DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK) {
385 lafe_errc(1, 0,
386 "Can't open %s: %s", bsdtar->filename,
387 archive_error_string(a));
390 /* Build a list of all entries and their recorded mod times. */
391 while (0 == archive_read_next_header(a, &entry)) {
392 if (archive_compression(a) != ARCHIVE_COMPRESSION_NONE) {
393 archive_read_finish(a);
394 close(bsdtar->fd);
395 lafe_errc(1, 0,
396 "Cannot append to compressed archive.");
398 add_dir_list(bsdtar, archive_entry_pathname(entry),
399 archive_entry_mtime(entry),
400 archive_entry_mtime_nsec(entry));
401 /* Record the last format determination we see */
402 format = archive_format(a);
403 /* Keep going until we hit end-of-archive */
406 end_offset = archive_read_header_position(a);
407 archive_read_finish(a);
409 /* Re-open archive for writing. */
410 a = archive_write_new();
411 archive_write_set_compression_none(a);
413 * Set format to same one auto-detected above, except that
414 * we don't write GNU tar format, so use ustar instead.
416 if (format == ARCHIVE_FORMAT_TAR_GNUTAR)
417 format = ARCHIVE_FORMAT_TAR_USTAR;
418 archive_write_set_format(a, format);
419 if (bsdtar->bytes_per_block != 0) {
420 archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
421 archive_write_set_bytes_in_last_block(a,
422 bsdtar->bytes_per_block);
423 } else
424 archive_write_set_bytes_per_block(a, DEFAULT_BYTES_PER_BLOCK);
425 if (lseek(bsdtar->fd, end_offset, SEEK_SET) < 0)
426 lafe_errc(1, errno, "Could not seek to archive end");
427 if (ARCHIVE_OK != archive_write_set_options(a, bsdtar->option_options))
428 lafe_errc(1, 0, "%s", archive_error_string(a));
429 if (ARCHIVE_OK != archive_write_open_fd(a, bsdtar->fd))
430 lafe_errc(1, 0, "%s", archive_error_string(a));
432 write_archive(a, bsdtar);
434 close(bsdtar->fd);
435 bsdtar->fd = -1;
437 while (bsdtar->archive_dir->head != NULL) {
438 p = bsdtar->archive_dir->head->next;
439 free(bsdtar->archive_dir->head->name);
440 free(bsdtar->archive_dir->head);
441 bsdtar->archive_dir->head = p;
443 bsdtar->archive_dir->tail = NULL;
448 * Write user-specified files/dirs to opened archive.
450 static void
451 write_archive(struct archive *a, struct bsdtar *bsdtar)
453 const char *arg;
454 struct archive_entry *entry, *sparse_entry;
456 /* Allocate a buffer for file data. */
457 if ((bsdtar->buff = malloc(FILEDATABUFLEN)) == NULL)
458 lafe_errc(1, 0, "cannot allocate memory");
460 if ((bsdtar->resolver = archive_entry_linkresolver_new()) == NULL)
461 lafe_errc(1, 0, "cannot create link resolver");
462 archive_entry_linkresolver_set_strategy(bsdtar->resolver,
463 archive_format(a));
464 if ((bsdtar->diskreader = archive_read_disk_new()) == NULL)
465 lafe_errc(1, 0, "Cannot create read_disk object");
466 archive_read_disk_set_standard_lookup(bsdtar->diskreader);
468 if (bsdtar->names_from_file != NULL)
469 archive_names_from_file(bsdtar, a);
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;
485 set_chdir(bsdtar, arg);
486 } else {
487 if (*arg != '/' && (arg[0] != '@' || arg[1] != '/'))
488 do_chdir(bsdtar); /* Handle a deferred -C */
489 if (*arg == '@') {
490 if (append_archive_filename(bsdtar, a,
491 arg + 1) != 0)
492 break;
493 } else
494 write_hierarchy(bsdtar, a, arg);
496 bsdtar->argv++;
499 entry = NULL;
500 archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
501 while (entry != NULL) {
502 write_entry_backend(bsdtar, a, entry);
503 archive_entry_free(entry);
504 entry = NULL;
505 archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
508 if (archive_write_close(a)) {
509 lafe_warnc(0, "%s", archive_error_string(a));
510 bsdtar->return_value = 1;
513 cleanup:
514 /* Free file data buffer. */
515 free(bsdtar->buff);
516 archive_entry_linkresolver_free(bsdtar->resolver);
517 bsdtar->resolver = NULL;
518 archive_read_finish(bsdtar->diskreader);
519 bsdtar->diskreader = NULL;
521 if (bsdtar->option_totals) {
522 fprintf(stderr, "Total bytes written: %s\n",
523 tar_i64toa(archive_position_compressed(a)));
526 archive_write_finish(a);
530 * Archive names specified in file.
532 * Unless --null was specified, a line containing exactly "-C" will
533 * cause the next line to be a directory to pass to chdir(). If
534 * --null is specified, then a line "-C" is just another filename.
536 static void
537 archive_names_from_file(struct bsdtar *bsdtar, struct archive *a)
539 struct lafe_line_reader *lr;
540 const char *line;
542 bsdtar->next_line_is_dir = 0;
544 lr = lafe_line_reader(bsdtar->names_from_file, bsdtar->option_null);
545 while ((line = lafe_line_reader_next(lr)) != NULL) {
546 if (bsdtar->next_line_is_dir) {
547 set_chdir(bsdtar, line);
548 bsdtar->next_line_is_dir = 0;
549 } else if (!bsdtar->option_null && strcmp(line, "-C") == 0)
550 bsdtar->next_line_is_dir = 1;
551 else {
552 if (*line != '/')
553 do_chdir(bsdtar); /* Handle a deferred -C */
554 write_hierarchy(bsdtar, a, line);
557 lafe_line_reader_free(lr);
558 if (bsdtar->next_line_is_dir)
559 lafe_errc(1, errno,
560 "Unexpected end of filename list; "
561 "directory expected after -C");
565 * Copy from specified archive to current archive. Returns non-zero
566 * for write errors (which force us to terminate the entire archiving
567 * operation). If there are errors reading the input archive, we set
568 * bsdtar->return_value but return zero, so the overall archiving
569 * operation will complete and return non-zero.
571 static int
572 append_archive_filename(struct bsdtar *bsdtar, struct archive *a,
573 const char *filename)
575 struct archive *ina;
576 int rc;
578 if (strcmp(filename, "-") == 0)
579 filename = NULL; /* Library uses NULL for stdio. */
581 ina = archive_read_new();
582 archive_read_support_format_all(ina);
583 archive_read_support_compression_all(ina);
584 if (archive_read_open_file(ina, filename, 10240)) {
585 lafe_warnc(0, "%s", archive_error_string(ina));
586 bsdtar->return_value = 1;
587 return (0);
590 rc = append_archive(bsdtar, a, ina);
592 if (rc != ARCHIVE_OK) {
593 lafe_warnc(0, "Error reading archive %s: %s",
594 filename, archive_error_string(ina));
595 bsdtar->return_value = 1;
597 archive_read_finish(ina);
599 return (rc);
602 static int
603 append_archive(struct bsdtar *bsdtar, struct archive *a, struct archive *ina)
605 struct archive_entry *in_entry;
606 int e;
608 while (0 == archive_read_next_header(ina, &in_entry)) {
609 if (!new_enough(bsdtar, archive_entry_pathname(in_entry),
610 archive_entry_stat(in_entry)))
611 continue;
612 if (lafe_excluded(bsdtar->matching, archive_entry_pathname(in_entry)))
613 continue;
614 if (bsdtar->option_interactive &&
615 !yes("copy '%s'", archive_entry_pathname(in_entry)))
616 continue;
617 if (bsdtar->verbose)
618 safe_fprintf(stderr, "a %s",
619 archive_entry_pathname(in_entry));
620 if (need_report())
621 report_write(bsdtar, a, in_entry, 0);
623 e = archive_write_header(a, in_entry);
624 if (e != ARCHIVE_OK) {
625 if (!bsdtar->verbose)
626 lafe_warnc(0, "%s: %s",
627 archive_entry_pathname(in_entry),
628 archive_error_string(a));
629 else
630 fprintf(stderr, ": %s", archive_error_string(a));
632 if (e == ARCHIVE_FATAL)
633 exit(1);
635 if (e >= ARCHIVE_WARN) {
636 if (archive_entry_size(in_entry) == 0)
637 archive_read_data_skip(ina);
638 else if (copy_file_data(bsdtar, a, ina, in_entry))
639 exit(1);
642 if (bsdtar->verbose)
643 fprintf(stderr, "\n");
646 /* Note: If we got here, we saw no write errors, so return success. */
647 return (0);
650 /* Helper function to copy data between archives. */
651 static int
652 copy_file_data(struct bsdtar *bsdtar, struct archive *a,
653 struct archive *ina, struct archive_entry *entry)
655 ssize_t bytes_read;
656 ssize_t bytes_written;
657 #ifndef __minix
658 int64_t progress = 0;
659 #else
660 int32_t progress = 0;
661 #endif
662 bytes_read = archive_read_data(ina, bsdtar->buff, FILEDATABUFLEN);
663 while (bytes_read > 0) {
664 if (need_report())
665 report_write(bsdtar, a, entry, progress);
667 bytes_written = archive_write_data(a, bsdtar->buff,
668 bytes_read);
669 if (bytes_written < bytes_read) {
670 lafe_warnc(0, "%s", archive_error_string(a));
671 return (-1);
673 progress += bytes_written;
674 bytes_read = archive_read_data(ina, bsdtar->buff,
675 FILEDATABUFLEN);
678 return (0);
682 * Add the file or dir hierarchy named by 'path' to the archive
684 static void
685 write_hierarchy(struct bsdtar *bsdtar, struct archive *a, const char *path)
687 struct archive_entry *entry = NULL, *spare_entry = NULL;
688 struct tree *tree;
689 char symlink_mode = bsdtar->symlink_mode;
690 dev_t first_dev = 0;
691 int dev_recorded = 0;
692 int tree_ret;
694 tree = tree_open(path);
696 if (!tree) {
697 lafe_warnc(errno, "%s: Cannot open", path);
698 bsdtar->return_value = 1;
699 return;
702 while ((tree_ret = tree_next(tree)) != 0) {
703 int r;
704 const char *name = tree_current_path(tree);
705 const struct stat *st = NULL; /* info to use for this entry */
706 const struct stat *lst = NULL; /* lstat() information */
707 int descend;
709 if (tree_ret == TREE_ERROR_FATAL)
710 lafe_errc(1, tree_errno(tree),
711 "%s: Unable to continue traversing directory tree",
712 name);
713 if (tree_ret == TREE_ERROR_DIR) {
714 lafe_warnc(errno,
715 "%s: Couldn't visit directory", name);
716 bsdtar->return_value = 1;
718 if (tree_ret != TREE_REGULAR)
719 continue;
722 * If this file/dir is excluded by a filename
723 * pattern, skip it.
725 if (lafe_excluded(bsdtar->matching, name))
726 continue;
729 * Get lstat() info from the tree library.
731 lst = tree_current_lstat(tree);
732 if (lst == NULL) {
733 /* Couldn't lstat(); must not exist. */
734 lafe_warnc(errno, "%s: Cannot stat", name);
735 /* Return error if files disappear during traverse. */
736 bsdtar->return_value = 1;
737 continue;
741 * Distinguish 'L'/'P'/'H' symlink following.
743 switch(symlink_mode) {
744 case 'H':
745 /* 'H': After the first item, rest like 'P'. */
746 symlink_mode = 'P';
747 /* 'H': First item (from command line) like 'L'. */
748 /* FALLTHROUGH */
749 case 'L':
750 /* 'L': Do descend through a symlink to dir. */
751 descend = tree_current_is_dir(tree);
752 /* 'L': Follow symlinks to files. */
753 archive_read_disk_set_symlink_logical(bsdtar->diskreader);
754 /* 'L': Archive symlinks as targets, if we can. */
755 st = tree_current_stat(tree);
756 if (st != NULL)
757 break;
758 /* If stat fails, we have a broken symlink;
759 * in that case, don't follow the link. */
760 /* FALLTHROUGH */
761 default:
762 /* 'P': Don't descend through a symlink to dir. */
763 descend = tree_current_is_physical_dir(tree);
764 /* 'P': Don't follow symlinks to files. */
765 archive_read_disk_set_symlink_physical(bsdtar->diskreader);
766 /* 'P': Archive symlinks as symlinks. */
767 st = lst;
768 break;
772 * Are we about to cross to a new filesystem?
774 if (!dev_recorded) {
775 /* This is the initial file system. */
776 first_dev = lst->st_dev;
777 dev_recorded = 1;
778 } else if (lst->st_dev == first_dev) {
779 /* The starting file system is always acceptable. */
780 } else if (descend == 0) {
781 /* We're not descending, so no need to check. */
782 } else if (bsdtar->option_dont_traverse_mounts) {
783 /* User has asked us not to cross mount points. */
784 descend = 0;
785 } else {
786 /* We're prepared to cross a mount point. */
788 /* XXX TODO: check whether this filesystem is
789 * synthetic and/or local. Add a new
790 * --local-only option to skip non-local
791 * filesystems. Skip synthetic filesystems
792 * regardless.
794 * The results should be cached, since
795 * tree.c doesn't usually visit a directory
796 * and the directory contents together. A simple
797 * move-to-front list should perform quite well.
799 * This is going to be heavily OS dependent:
800 * FreeBSD's statfs() in conjunction with getvfsbyname()
801 * provides all of this; NetBSD's statvfs() does
802 * most of it; other systems will vary.
807 * In -u mode, check that the file is newer than what's
808 * already in the archive; in all modes, obey --newerXXX flags.
810 if (!new_enough(bsdtar, name, st))
811 continue;
813 archive_entry_free(entry);
814 entry = archive_entry_new();
816 archive_entry_set_pathname(entry, name);
817 archive_entry_copy_sourcepath(entry,
818 tree_current_access_path(tree));
820 /* Populate the archive_entry with metadata from the disk. */
821 /* XXX TODO: Arrange to open a regular file before
822 * calling this so we can pass in an fd and shorten
823 * the race to query metadata. The linkify dance
824 * makes this more complex than it might sound. */
825 #if defined(_WIN32) && !defined(__CYGWIN__)
826 /* TODO: tree.c uses stat(), which is badly broken
827 * on Windows. To fix this, we should
828 * deprecate tree_current_stat() and provide a new
829 * call tree_populate_entry(t, entry). This call
830 * would use stat() internally on POSIX and
831 * GetInfoByFileHandle() internally on Windows.
832 * This would be another step towards a tree-walker
833 * that can be integrated deep into libarchive.
834 * For now, just set st to NULL on Windows;
835 * archive_read_disk_entry_from_file() should
836 * be smart enough to use platform-appropriate
837 * ways to probe file information.
839 st = NULL;
840 #endif
841 r = archive_read_disk_entry_from_file(bsdtar->diskreader,
842 entry, -1, st);
843 if (r != ARCHIVE_OK)
844 lafe_warnc(archive_errno(bsdtar->diskreader),
845 "%s", archive_error_string(bsdtar->diskreader));
846 if (r < ARCHIVE_WARN)
847 continue;
849 /* XXX TODO: Just use flag data from entry; avoid the
850 * duplicate check here. */
853 * If this file/dir is flagged "nodump" and we're
854 * honoring such flags, skip this file/dir.
856 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
857 /* BSD systems store flags in struct stat */
858 if (bsdtar->option_honor_nodump &&
859 (lst->st_flags & UF_NODUMP))
860 continue;
861 #endif
863 #if defined(EXT2_IOC_GETFLAGS) && defined(EXT2_NODUMP_FL)
864 /* Linux uses ioctl to read flags. */
865 if (bsdtar->option_honor_nodump) {
866 int fd = open(name, O_RDONLY | O_NONBLOCK | O_BINARY);
867 if (fd >= 0) {
868 unsigned long fflags;
869 int r = ioctl(fd, EXT2_IOC_GETFLAGS, &fflags);
870 close(fd);
871 if (r >= 0 && (fflags & EXT2_NODUMP_FL))
872 continue;
875 #endif
878 * If the user vetoes this file/directory, skip it.
879 * We want this to be fairly late; if some other
880 * check would veto this file, we shouldn't bother
881 * the user with it.
883 if (bsdtar->option_interactive &&
884 !yes("add '%s'", name))
885 continue;
887 /* Note: if user vetoes, we won't descend. */
888 if (descend && !bsdtar->option_no_subdirs)
889 tree_descend(tree);
892 * Rewrite the pathname to be archived. If rewrite
893 * fails, skip the entry.
895 if (edit_pathname(bsdtar, entry))
896 continue;
898 /* Display entry as we process it.
899 * This format is required by SUSv2. */
900 if (bsdtar->verbose)
901 safe_fprintf(stderr, "a %s",
902 archive_entry_pathname(entry));
904 /* Non-regular files get archived with zero size. */
905 if (archive_entry_filetype(entry) != AE_IFREG)
906 archive_entry_set_size(entry, 0);
908 archive_entry_linkify(bsdtar->resolver, &entry, &spare_entry);
910 while (entry != NULL) {
911 write_entry_backend(bsdtar, a, entry);
912 archive_entry_free(entry);
913 entry = spare_entry;
914 spare_entry = NULL;
917 if (bsdtar->verbose)
918 fprintf(stderr, "\n");
920 archive_entry_free(entry);
921 tree_close(tree);
925 * Backend for write_entry.
927 static void
928 write_entry_backend(struct bsdtar *bsdtar, struct archive *a,
929 struct archive_entry *entry)
931 int fd = -1;
932 int e;
934 if (archive_entry_size(entry) > 0) {
935 const char *pathname = archive_entry_sourcepath(entry);
936 fd = open(pathname, O_RDONLY | O_BINARY);
937 if (fd == -1) {
938 if (!bsdtar->verbose)
939 lafe_warnc(errno,
940 "%s: could not open file", pathname);
941 else
942 fprintf(stderr, ": %s", strerror(errno));
943 return;
947 e = archive_write_header(a, entry);
948 if (e != ARCHIVE_OK) {
949 if (!bsdtar->verbose)
950 lafe_warnc(0, "%s: %s",
951 archive_entry_pathname(entry),
952 archive_error_string(a));
953 else
954 fprintf(stderr, ": %s", archive_error_string(a));
957 if (e == ARCHIVE_FATAL)
958 exit(1);
961 * If we opened a file earlier, write it out now. Note that
962 * the format handler might have reset the size field to zero
963 * to inform us that the archive body won't get stored. In
964 * that case, just skip the write.
966 if (e >= ARCHIVE_WARN && fd >= 0 && archive_entry_size(entry) > 0) {
967 if (write_file_data(bsdtar, a, entry, fd))
968 exit(1);
972 * If we opened a file, close it now even if there was an error
973 * which made us decide not to write the archive body.
975 if (fd >= 0)
976 close(fd);
979 #ifndef __minix
980 static void
981 report_write(struct bsdtar *bsdtar, struct archive *a,
982 struct archive_entry *entry, int64_t progress)
984 uint64_t comp, uncomp;
985 if (bsdtar->verbose)
986 fprintf(stderr, "\n");
987 comp = archive_position_compressed(a);
988 uncomp = archive_position_uncompressed(a);
989 fprintf(stderr, "In: %d files, %s bytes;",
990 archive_file_count(a), tar_i64toa(uncomp));
991 fprintf(stderr,
992 " Out: %s bytes, compression %d%%\n",
993 tar_i64toa(comp), (int)((uncomp - comp) * 100 / uncomp));
994 /* Can't have two calls to tar_i64toa() pending, so split the output. */
995 safe_fprintf(stderr, "Current: %s (%s",
996 archive_entry_pathname(entry),
997 tar_i64toa(progress));
998 fprintf(stderr, "/%s bytes)\n",
999 tar_i64toa(archive_entry_size(entry)));
1001 #else
1002 static void
1003 report_write(struct bsdtar *bsdtar, struct archive *a,
1004 struct archive_entry *entry, int32_t progress)
1006 size_t comp, uncomp;
1007 if (bsdtar->verbose)
1008 fprintf(stderr, "\n");
1009 comp = archive_position_compressed(a);
1010 uncomp = archive_position_uncompressed(a);
1011 fprintf(stderr, "In: %d files, %s bytes;",
1012 archive_file_count(a), tar_i64toa(uncomp));
1013 fprintf(stderr,
1014 " Out: %s bytes, compression %d%%\n",
1015 tar_i64toa(comp), (int)((uncomp - comp) * 100 / uncomp));
1016 /* Can't have two calls to tar_i64toa() pending, so split the output. */
1017 safe_fprintf(stderr, "Current: %s (%s",
1018 archive_entry_pathname(entry),
1019 tar_i64toa(progress));
1020 fprintf(stderr, "/%s bytes)\n",
1021 tar_i64toa(archive_entry_size(entry)));
1023 #endif
1025 /* Helper function to copy file to archive. */
1026 static int
1027 write_file_data(struct bsdtar *bsdtar, struct archive *a,
1028 struct archive_entry *entry, int fd)
1030 ssize_t bytes_read;
1031 ssize_t bytes_written;
1032 #ifndef __minix
1033 int64_t progress = 0;
1034 #else
1035 int32_t progress = 0;
1036 #endif
1037 bytes_read = read(fd, bsdtar->buff, FILEDATABUFLEN);
1038 while (bytes_read > 0) {
1039 if (need_report())
1040 report_write(bsdtar, a, entry, progress);
1042 bytes_written = archive_write_data(a, bsdtar->buff,
1043 bytes_read);
1044 if (bytes_written < 0) {
1045 /* Write failed; this is bad */
1046 lafe_warnc(0, "%s", archive_error_string(a));
1047 return (-1);
1049 if (bytes_written < bytes_read) {
1050 /* Write was truncated; warn but continue. */
1051 lafe_warnc(0,
1052 "%s: Truncated write; file may have grown while being archived.",
1053 archive_entry_pathname(entry));
1054 return (0);
1056 progress += bytes_written;
1057 bytes_read = read(fd, bsdtar->buff, FILEDATABUFLEN);
1059 return 0;
1063 * Test if the specified file is new enough to include in the archive.
1065 static int
1066 new_enough(struct bsdtar *bsdtar, const char *path, const struct stat *st)
1068 struct archive_dir_entry *p;
1071 * If this file/dir is excluded by a time comparison, skip it.
1073 if (bsdtar->newer_ctime_sec > 0) {
1074 if (st->st_ctime < bsdtar->newer_ctime_sec)
1075 return (0); /* Too old, skip it. */
1076 if (st->st_ctime == bsdtar->newer_ctime_sec
1077 && ARCHIVE_STAT_CTIME_NANOS(st)
1078 <= bsdtar->newer_ctime_nsec)
1079 return (0); /* Too old, skip it. */
1081 if (bsdtar->newer_mtime_sec > 0) {
1082 if (st->st_mtime < bsdtar->newer_mtime_sec)
1083 return (0); /* Too old, skip it. */
1084 if (st->st_mtime == bsdtar->newer_mtime_sec
1085 && ARCHIVE_STAT_MTIME_NANOS(st)
1086 <= bsdtar->newer_mtime_nsec)
1087 return (0); /* Too old, skip it. */
1091 * In -u mode, we only write an entry if it's newer than
1092 * what was already in the archive.
1094 if (bsdtar->archive_dir != NULL &&
1095 bsdtar->archive_dir->head != NULL) {
1096 for (p = bsdtar->archive_dir->head; p != NULL; p = p->next) {
1097 if (pathcmp(path, p->name)==0)
1098 return (p->mtime_sec < st->st_mtime ||
1099 (p->mtime_sec == st->st_mtime &&
1100 p->mtime_nsec
1101 < ARCHIVE_STAT_MTIME_NANOS(st)));
1105 /* If the file wasn't rejected, include it. */
1106 return (1);
1110 * Add an entry to the dir list for 'u' mode.
1112 * XXX TODO: Make this fast.
1114 static void
1115 add_dir_list(struct bsdtar *bsdtar, const char *path,
1116 time_t mtime_sec, int mtime_nsec)
1118 struct archive_dir_entry *p;
1121 * Search entire list to see if this file has appeared before.
1122 * If it has, override the timestamp data.
1124 p = bsdtar->archive_dir->head;
1125 while (p != NULL) {
1126 if (strcmp(path, p->name)==0) {
1127 p->mtime_sec = mtime_sec;
1128 p->mtime_nsec = mtime_nsec;
1129 return;
1131 p = p->next;
1134 p = malloc(sizeof(*p));
1135 if (p == NULL)
1136 lafe_errc(1, ENOMEM, "Can't read archive directory");
1138 p->name = strdup(path);
1139 if (p->name == NULL)
1140 lafe_errc(1, ENOMEM, "Can't read archive directory");
1141 p->mtime_sec = mtime_sec;
1142 p->mtime_nsec = mtime_nsec;
1143 p->next = NULL;
1144 if (bsdtar->archive_dir->tail == NULL) {
1145 bsdtar->archive_dir->head = bsdtar->archive_dir->tail = p;
1146 } else {
1147 bsdtar->archive_dir->tail->next = p;
1148 bsdtar->archive_dir->tail = p;
1152 static void
1153 test_for_append(struct bsdtar *bsdtar)
1155 struct stat s;
1157 if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
1158 lafe_errc(1, 0, "no files or directories specified");
1159 if (bsdtar->filename == NULL)
1160 lafe_errc(1, 0, "Cannot append to stdout.");
1162 if (bsdtar->create_compression != 0)
1163 lafe_errc(1, 0,
1164 "Cannot append to %s with compression", bsdtar->filename);
1166 if (stat(bsdtar->filename, &s) != 0)
1167 return;
1169 if (!S_ISREG(s.st_mode) && !S_ISBLK(s.st_mode))
1170 lafe_errc(1, 0,
1171 "Cannot append to %s: not a regular file.",
1172 bsdtar->filename);
1174 /* Is this an appropriate check here on Windows? */
1176 if (GetFileType(handle) != FILE_TYPE_DISK)
1177 lafe_errc(1, 0, "Cannot append");