]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/tar/write.c
merge fix for boot-time hang on centos' xen
[FreeBSD/FreeBSD.git] / usr.bin / tar / write.c
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$");
28
29 #ifdef HAVE_SYS_TYPES_H
30 #include <sys/types.h>
31 #endif
32 #ifdef HAVE_SYS_ACL_H
33 #include <sys/acl.h>
34 #endif
35 #ifdef HAVE_SYS_IOCTL_H
36 #include <sys/ioctl.h>
37 #endif
38 #ifdef HAVE_SYS_STAT_H
39 #include <sys/stat.h>
40 #endif
41 #ifdef HAVE_ATTR_XATTR_H
42 #include <attr/xattr.h>
43 #endif
44 #ifdef HAVE_ERRNO_H
45 #include <errno.h>
46 #endif
47 #ifdef HAVE_EXT2FS_EXT2_FS_H
48 #include <ext2fs/ext2_fs.h>
49 #endif
50 #ifdef HAVE_FCNTL_H
51 #include <fcntl.h>
52 #endif
53 #ifdef HAVE_FNMATCH_H
54 #include <fnmatch.h>
55 #endif
56 #ifdef HAVE_GRP_H
57 #include <grp.h>
58 #endif
59 #ifdef HAVE_LIMITS_H
60 #include <limits.h>
61 #endif
62 #ifdef HAVE_LINUX_FS_H
63 #include <linux/fs.h>   /* for Linux file flags */
64 #endif
65 #ifdef HAVE_PWD_H
66 #include <pwd.h>
67 #endif
68 #include <stdio.h>
69 #ifdef HAVE_STDLIB_H
70 #include <stdlib.h>
71 #endif
72 #ifdef HAVE_STRING_H
73 #include <string.h>
74 #endif
75 #ifdef HAVE_UNISTD_H
76 #include <unistd.h>
77 #endif
78
79 #include "bsdtar.h"
80 #include "tree.h"
81
82 /* Size of buffer for holding file data prior to writing. */
83 #define FILEDATABUFLEN  65536
84
85 /* Fixed size of uname/gname caches. */
86 #define name_cache_size 101
87
88 static const char * const NO_NAME = "(noname)";
89
90 struct archive_dir_entry {
91         struct archive_dir_entry        *next;
92         time_t                   mtime_sec;
93         int                      mtime_nsec;
94         char                    *name;
95 };
96
97 struct archive_dir {
98         struct archive_dir_entry *head, *tail;
99 };
100
101 struct name_cache {
102         int     probes;
103         int     hits;
104         size_t  size;
105         struct {
106                 id_t id;
107                 const char *name;
108         } cache[name_cache_size];
109 };
110
111 static void              add_dir_list(struct bsdtar *bsdtar, const char *path,
112                              time_t mtime_sec, int mtime_nsec);
113 static int               append_archive(struct bsdtar *, struct archive *,
114                              struct archive *ina);
115 static int               append_archive_filename(struct bsdtar *,
116                              struct archive *, const char *fname);
117 static void              archive_names_from_file(struct bsdtar *bsdtar,
118                              struct archive *a);
119 static int               archive_names_from_file_helper(struct bsdtar *bsdtar,
120                              const char *line);
121 static int               copy_file_data(struct bsdtar *bsdtar,
122                              struct archive *a, struct archive *ina);
123 static void              create_cleanup(struct bsdtar *);
124 static void              free_cache(struct name_cache *cache);
125 static const char *      lookup_gname(struct bsdtar *bsdtar, gid_t gid);
126 static int               lookup_gname_helper(struct bsdtar *bsdtar,
127                              const char **name, id_t gid);
128 static const char *      lookup_uname(struct bsdtar *bsdtar, uid_t uid);
129 static int               lookup_uname_helper(struct bsdtar *bsdtar,
130                              const char **name, id_t uid);
131 static int               new_enough(struct bsdtar *, const char *path,
132                              const struct stat *);
133 static void              setup_acls(struct bsdtar *, struct archive_entry *,
134                              const char *path);
135 static void              setup_xattrs(struct bsdtar *, struct archive_entry *,
136                              const char *path);
137 static void              test_for_append(struct bsdtar *);
138 static void              write_archive(struct archive *, struct bsdtar *);
139 static void              write_entry(struct bsdtar *, struct archive *,
140                              const struct stat *, const char *pathname,
141                              const char *accpath);
142 static void              write_entry_backend(struct bsdtar *, struct archive *,
143                              struct archive_entry *);
144 static int               write_file_data(struct bsdtar *, struct archive *,
145                              struct archive_entry *, int fd);
146 static void              write_hierarchy(struct bsdtar *, struct archive *,
147                              const char *);
148
149 void
150 tar_mode_c(struct bsdtar *bsdtar)
151 {
152         struct archive *a;
153         int r;
154
155         if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
156                 bsdtar_errc(bsdtar, 1, 0, "no files or directories specified");
157
158         a = archive_write_new();
159
160         /* Support any format that the library supports. */
161         if (bsdtar->create_format == NULL) {
162                 r = archive_write_set_format_pax_restricted(a);
163                 bsdtar->create_format = "pax restricted";
164         } else {
165                 r = archive_write_set_format_by_name(a, bsdtar->create_format);
166         }
167         if (r != ARCHIVE_OK) {
168                 fprintf(stderr, "Can't use format %s: %s\n",
169                     bsdtar->create_format,
170                     archive_error_string(a));
171                 usage(bsdtar);
172         }
173
174         /*
175          * If user explicitly set the block size, then assume they
176          * want the last block padded as well.  Otherwise, use the
177          * default block size and accept archive_write_open_file()'s
178          * default padding decisions.
179          */
180         if (bsdtar->bytes_per_block != 0) {
181                 archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
182                 archive_write_set_bytes_in_last_block(a,
183                     bsdtar->bytes_per_block);
184         } else
185                 archive_write_set_bytes_per_block(a, DEFAULT_BYTES_PER_BLOCK);
186
187         if (bsdtar->compress_program) {
188                 archive_write_set_compression_program(a, bsdtar->compress_program);
189         } else {
190                 switch (bsdtar->create_compression) {
191                 case 0:
192                         archive_write_set_compression_none(a);
193                         break;
194 #ifdef HAVE_LIBBZ2
195                 case 'j': case 'y':
196                         archive_write_set_compression_bzip2(a);
197                         break;
198 #endif
199 #ifdef HAVE_LIBZ
200                 case 'z':
201                         archive_write_set_compression_gzip(a);
202                         break;
203 #endif
204                 case 'Z':
205                         archive_write_set_compression_compress(a);
206                         break;
207                 default:
208                         bsdtar_errc(bsdtar, 1, 0,
209                             "Unrecognized compression option -%c",
210                             bsdtar->create_compression);
211                 }
212         }
213
214         r = archive_write_open_file(a, bsdtar->filename);
215         if (r != ARCHIVE_OK)
216                 bsdtar_errc(bsdtar, 1, 0, archive_error_string(a));
217
218         write_archive(a, bsdtar);
219 }
220
221 /*
222  * Same as 'c', except we only support tar or empty formats in
223  * uncompressed files on disk.
224  */
225 void
226 tar_mode_r(struct bsdtar *bsdtar)
227 {
228         off_t   end_offset;
229         int     format;
230         struct archive *a;
231         struct archive_entry *entry;
232         int     r;
233
234         /* Sanity-test some arguments and the file. */
235         test_for_append(bsdtar);
236
237         format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
238
239         bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT, 0666);
240         if (bsdtar->fd < 0)
241                 bsdtar_errc(bsdtar, 1, errno,
242                     "Cannot open %s", bsdtar->filename);
243
244         a = archive_read_new();
245         archive_read_support_compression_all(a);
246         archive_read_support_format_tar(a);
247         archive_read_support_format_gnutar(a);
248         r = archive_read_open_fd(a, bsdtar->fd, 10240);
249         if (r != ARCHIVE_OK)
250                 bsdtar_errc(bsdtar, 1, archive_errno(a),
251                     "Can't read archive %s: %s", bsdtar->filename,
252                     archive_error_string(a));
253         while (0 == archive_read_next_header(a, &entry)) {
254                 if (archive_compression(a) != ARCHIVE_COMPRESSION_NONE) {
255                         archive_read_finish(a);
256                         close(bsdtar->fd);
257                         bsdtar_errc(bsdtar, 1, 0,
258                             "Cannot append to compressed archive.");
259                 }
260                 /* Keep going until we hit end-of-archive */
261                 format = archive_format(a);
262         }
263
264         end_offset = archive_read_header_position(a);
265         archive_read_finish(a);
266
267         /* Re-open archive for writing */
268         a = archive_write_new();
269         archive_write_set_compression_none(a);
270         /*
271          * Set the format to be used for writing.  To allow people to
272          * extend empty files, we need to allow them to specify the format,
273          * which opens the possibility that they will specify a format that
274          * doesn't match the existing format.  Hence, the following bit
275          * of arcane ugliness.
276          */
277
278         if (bsdtar->create_format != NULL) {
279                 /* If the user requested a format, use that, but ... */
280                 archive_write_set_format_by_name(a,
281                     bsdtar->create_format);
282                 /* ... complain if it's not compatible. */
283                 format &= ARCHIVE_FORMAT_BASE_MASK;
284                 if (format != (int)(archive_format(a) & ARCHIVE_FORMAT_BASE_MASK)
285                     && format != ARCHIVE_FORMAT_EMPTY) {
286                         bsdtar_errc(bsdtar, 1, 0,
287                             "Format %s is incompatible with the archive %s.",
288                             bsdtar->create_format, bsdtar->filename);
289                 }
290         } else {
291                 /*
292                  * Just preserve the current format, with a little care
293                  * for formats that libarchive can't write.
294                  */
295                 if (format == ARCHIVE_FORMAT_TAR_GNUTAR)
296                         /* TODO: When gtar supports pax, use pax restricted. */
297                         format = ARCHIVE_FORMAT_TAR_USTAR;
298                 if (format == ARCHIVE_FORMAT_EMPTY)
299                         format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
300                 archive_write_set_format(a, format);
301         }
302         lseek(bsdtar->fd, end_offset, SEEK_SET); /* XXX check return val XXX */
303         archive_write_open_fd(a, bsdtar->fd); /* XXX check return val XXX */
304
305         write_archive(a, bsdtar); /* XXX check return val XXX */
306
307         close(bsdtar->fd);
308         bsdtar->fd = -1;
309 }
310
311 void
312 tar_mode_u(struct bsdtar *bsdtar)
313 {
314         off_t                    end_offset;
315         struct archive          *a;
316         struct archive_entry    *entry;
317         int                      format;
318         struct archive_dir_entry        *p;
319         struct archive_dir       archive_dir;
320
321         bsdtar->archive_dir = &archive_dir;
322         memset(&archive_dir, 0, sizeof(archive_dir));
323
324         format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
325
326         /* Sanity-test some arguments and the file. */
327         test_for_append(bsdtar);
328
329         bsdtar->fd = open(bsdtar->filename, O_RDWR);
330         if (bsdtar->fd < 0)
331                 bsdtar_errc(bsdtar, 1, errno,
332                     "Cannot open %s", bsdtar->filename);
333
334         a = archive_read_new();
335         archive_read_support_compression_all(a);
336         archive_read_support_format_tar(a);
337         archive_read_support_format_gnutar(a);
338         if (archive_read_open_fd(a, bsdtar->fd,
339             bsdtar->bytes_per_block != 0 ? bsdtar->bytes_per_block :
340                 DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK) {
341                 bsdtar_errc(bsdtar, 1, 0,
342                     "Can't open %s: %s", bsdtar->filename,
343                     archive_error_string(a));
344         }
345
346         /* Build a list of all entries and their recorded mod times. */
347         while (0 == archive_read_next_header(a, &entry)) {
348                 if (archive_compression(a) != ARCHIVE_COMPRESSION_NONE) {
349                         archive_read_finish(a);
350                         close(bsdtar->fd);
351                         bsdtar_errc(bsdtar, 1, 0,
352                             "Cannot append to compressed archive.");
353                 }
354                 add_dir_list(bsdtar, archive_entry_pathname(entry),
355                     archive_entry_mtime(entry),
356                     archive_entry_mtime_nsec(entry));
357                 /* Record the last format determination we see */
358                 format = archive_format(a);
359                 /* Keep going until we hit end-of-archive */
360         }
361
362         end_offset = archive_read_header_position(a);
363         archive_read_finish(a);
364
365         /* Re-open archive for writing. */
366         a = archive_write_new();
367         archive_write_set_compression_none(a);
368         /*
369          * Set format to same one auto-detected above, except that
370          * we don't write GNU tar format, so use ustar instead.
371          */
372         if (format == ARCHIVE_FORMAT_TAR_GNUTAR)
373                 format = ARCHIVE_FORMAT_TAR_USTAR;
374         archive_write_set_format(a, format);
375         if (bsdtar->bytes_per_block != 0) {
376                 archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
377                 archive_write_set_bytes_in_last_block(a,
378                     bsdtar->bytes_per_block);
379         } else
380                 archive_write_set_bytes_per_block(a, DEFAULT_BYTES_PER_BLOCK);
381         lseek(bsdtar->fd, end_offset, SEEK_SET);
382         ftruncate(bsdtar->fd, end_offset);
383         archive_write_open_fd(a, bsdtar->fd);
384
385         write_archive(a, bsdtar);
386
387         close(bsdtar->fd);
388         bsdtar->fd = -1;
389
390         while (bsdtar->archive_dir->head != NULL) {
391                 p = bsdtar->archive_dir->head->next;
392                 free(bsdtar->archive_dir->head->name);
393                 free(bsdtar->archive_dir->head);
394                 bsdtar->archive_dir->head = p;
395         }
396         bsdtar->archive_dir->tail = NULL;
397 }
398
399
400 /*
401  * Write user-specified files/dirs to opened archive.
402  */
403 static void
404 write_archive(struct archive *a, struct bsdtar *bsdtar)
405 {
406         const char *arg;
407         struct archive_entry *entry, *sparse_entry;
408
409         /* We want to catch SIGINFO and SIGUSR1. */
410         siginfo_init(bsdtar);
411
412         /* Allocate a buffer for file data. */
413         if ((bsdtar->buff = malloc(FILEDATABUFLEN)) == NULL)
414                 bsdtar_errc(bsdtar, 1, 0, "cannot allocate memory");
415
416         if ((bsdtar->resolver = archive_entry_linkresolver_new()) == NULL)
417                 bsdtar_errc(bsdtar, 1, 0, "cannot create link resolver");
418         archive_entry_linkresolver_set_strategy(bsdtar->resolver,
419             archive_format(a));
420
421         if (bsdtar->names_from_file != NULL)
422                 archive_names_from_file(bsdtar, a);
423
424         while (*bsdtar->argv) {
425                 arg = *bsdtar->argv;
426                 if (arg[0] == '-' && arg[1] == 'C') {
427                         arg += 2;
428                         if (*arg == '\0') {
429                                 bsdtar->argv++;
430                                 arg = *bsdtar->argv;
431                                 if (arg == NULL) {
432                                         bsdtar_warnc(bsdtar, 1, 0,
433                                             "Missing argument for -C");
434                                         bsdtar->return_value = 1;
435                                         goto cleanup;
436                                 }
437                         }
438                         set_chdir(bsdtar, arg);
439                 } else {
440                         if (*arg != '/' && (arg[0] != '@' || arg[1] != '/'))
441                                 do_chdir(bsdtar); /* Handle a deferred -C */
442                         if (*arg == '@') {
443                                 if (append_archive_filename(bsdtar, a,
444                                     arg + 1) != 0)
445                                         break;
446                         } else
447                                 write_hierarchy(bsdtar, a, arg);
448                 }
449                 bsdtar->argv++;
450         }
451
452         entry = NULL;
453         archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
454         while (entry != NULL) {
455                 write_entry_backend(bsdtar, a, entry);
456                 archive_entry_free(entry);
457                 entry = NULL;
458                 archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
459         }
460
461         create_cleanup(bsdtar);
462         if (archive_write_close(a)) {
463                 bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(a));
464                 bsdtar->return_value = 1;
465         }
466
467 cleanup:
468         /* Free file data buffer. */
469         free(bsdtar->buff);
470
471         if (bsdtar->option_totals) {
472                 fprintf(stderr, "Total bytes written: " BSDTAR_FILESIZE_PRINTF "\n",
473                     (BSDTAR_FILESIZE_TYPE)archive_position_compressed(a));
474         }
475
476         archive_write_finish(a);
477
478         /* Restore old SIGINFO + SIGUSR1 handlers. */
479         siginfo_done(bsdtar);
480 }
481
482 /*
483  * Archive names specified in file.
484  *
485  * Unless --null was specified, a line containing exactly "-C" will
486  * cause the next line to be a directory to pass to chdir().  If
487  * --null is specified, then a line "-C" is just another filename.
488  */
489 void
490 archive_names_from_file(struct bsdtar *bsdtar, struct archive *a)
491 {
492         bsdtar->archive = a;
493
494         bsdtar->next_line_is_dir = 0;
495         process_lines(bsdtar, bsdtar->names_from_file,
496             archive_names_from_file_helper);
497         if (bsdtar->next_line_is_dir)
498                 bsdtar_errc(bsdtar, 1, errno,
499                     "Unexpected end of filename list; "
500                     "directory expected after -C");
501 }
502
503 static int
504 archive_names_from_file_helper(struct bsdtar *bsdtar, const char *line)
505 {
506         if (bsdtar->next_line_is_dir) {
507                 set_chdir(bsdtar, line);
508                 bsdtar->next_line_is_dir = 0;
509         } else if (!bsdtar->option_null && strcmp(line, "-C") == 0)
510                 bsdtar->next_line_is_dir = 1;
511         else {
512                 if (*line != '/')
513                         do_chdir(bsdtar); /* Handle a deferred -C */
514                 write_hierarchy(bsdtar, bsdtar->archive, line);
515         }
516         return (0);
517 }
518
519 /*
520  * Copy from specified archive to current archive.  Returns non-zero
521  * for write errors (which force us to terminate the entire archiving
522  * operation).  If there are errors reading the input archive, we set
523  * bsdtar->return_value but return zero, so the overall archiving
524  * operation will complete and return non-zero.
525  */
526 static int
527 append_archive_filename(struct bsdtar *bsdtar, struct archive *a,
528     const char *filename)
529 {
530         struct archive *ina;
531         int rc;
532
533         if (strcmp(filename, "-") == 0)
534                 filename = NULL; /* Library uses NULL for stdio. */
535
536         ina = archive_read_new();
537         archive_read_support_format_all(ina);
538         archive_read_support_compression_all(ina);
539         if (archive_read_open_file(ina, filename, 10240)) {
540                 bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(ina));
541                 bsdtar->return_value = 1;
542                 return (0);
543         }
544
545         rc = append_archive(bsdtar, a, ina);
546
547         if (archive_errno(ina)) {
548                 bsdtar_warnc(bsdtar, 0, "Error reading archive %s: %s",
549                     filename, archive_error_string(ina));
550                 bsdtar->return_value = 1;
551         }
552         archive_read_finish(ina);
553
554         return (rc);
555 }
556
557 static int
558 append_archive(struct bsdtar *bsdtar, struct archive *a, struct archive *ina)
559 {
560         struct archive_entry *in_entry;
561         int e;
562
563         while (0 == archive_read_next_header(ina, &in_entry)) {
564                 if (!new_enough(bsdtar, archive_entry_pathname(in_entry),
565                         archive_entry_stat(in_entry)))
566                         continue;
567                 if (excluded(bsdtar, archive_entry_pathname(in_entry)))
568                         continue;
569                 if (bsdtar->option_interactive &&
570                     !yes("copy '%s'", archive_entry_pathname(in_entry)))
571                         continue;
572                 if (bsdtar->verbose)
573                         safe_fprintf(stderr, "a %s",
574                             archive_entry_pathname(in_entry));
575                 siginfo_setinfo(bsdtar, "copying",
576                     archive_entry_pathname(in_entry),
577                     archive_entry_size(in_entry));
578                 siginfo_printinfo(bsdtar, 0);
579
580                 e = archive_write_header(a, in_entry);
581                 if (e != ARCHIVE_OK) {
582                         if (!bsdtar->verbose)
583                                 bsdtar_warnc(bsdtar, 0, "%s: %s",
584                                     archive_entry_pathname(in_entry),
585                                     archive_error_string(a));
586                         else
587                                 fprintf(stderr, ": %s", archive_error_string(a));
588                 }
589                 if (e == ARCHIVE_FATAL)
590                         exit(1);
591
592                 if (e >= ARCHIVE_WARN) {
593                         if (archive_entry_size(in_entry) == 0)
594                                 archive_read_data_skip(ina);
595                         else if (copy_file_data(bsdtar, a, ina))
596                                 exit(1);
597                 }
598
599                 if (bsdtar->verbose)
600                         fprintf(stderr, "\n");
601         }
602
603         /* Note: If we got here, we saw no write errors, so return success. */
604         return (0);
605 }
606
607 /* Helper function to copy data between archives. */
608 static int
609 copy_file_data(struct bsdtar *bsdtar, struct archive *a, struct archive *ina)
610 {
611         ssize_t bytes_read;
612         ssize_t bytes_written;
613         off_t   progress = 0;
614
615         bytes_read = archive_read_data(ina, bsdtar->buff, FILEDATABUFLEN);
616         while (bytes_read > 0) {
617                 siginfo_printinfo(bsdtar, progress);
618
619                 bytes_written = archive_write_data(a, bsdtar->buff,
620                     bytes_read);
621                 if (bytes_written < bytes_read) {
622                         bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(a));
623                         return (-1);
624                 }
625                 progress += bytes_written;
626                 bytes_read = archive_read_data(ina, bsdtar->buff,
627                     FILEDATABUFLEN);
628         }
629
630         return (0);
631 }
632
633 /*
634  * Add the file or dir hierarchy named by 'path' to the archive
635  */
636 static void
637 write_hierarchy(struct bsdtar *bsdtar, struct archive *a, const char *path)
638 {
639         struct tree *tree;
640         char symlink_mode = bsdtar->symlink_mode;
641         dev_t first_dev = 0;
642         int dev_recorded = 0;
643         int tree_ret;
644 #ifdef __linux
645         int      fd, r;
646         unsigned long fflags;
647 #endif
648
649         tree = tree_open(path);
650
651         if (!tree) {
652                 bsdtar_warnc(bsdtar, errno, "%s: Cannot open", path);
653                 bsdtar->return_value = 1;
654                 return;
655         }
656
657         while ((tree_ret = tree_next(tree))) {
658                 const char *name = tree_current_path(tree);
659                 const struct stat *st = NULL, *lst = NULL;
660                 int descend;
661
662                 if (tree_ret == TREE_ERROR_DIR)
663                         bsdtar_warnc(bsdtar, errno, "%s: Couldn't visit directory", name);
664                 if (tree_ret != TREE_REGULAR)
665                         continue;
666                 lst = tree_current_lstat(tree);
667                 if (lst == NULL) {
668                         /* Couldn't lstat(); must not exist. */
669                         bsdtar_warnc(bsdtar, errno, "%s: Cannot stat", name);
670
671                         /*
672                          * Report an error via the exit code if the failed
673                          * path is a prefix of what the user provided via
674                          * the command line.  (Testing for string equality
675                          * here won't work due to trailing '/' characters.)
676                          */
677                         if (memcmp(name, path, strlen(name)) == 0)
678                                 bsdtar->return_value = 1;
679
680                         continue;
681                 }
682                 if (S_ISLNK(lst->st_mode))
683                         st = tree_current_stat(tree);
684                 /* Default: descend into any dir or symlink to dir. */
685                 /* We'll adjust this later on. */
686                 descend = 0;
687                 if ((st != NULL) && S_ISDIR(st->st_mode))
688                         descend = 1;
689                 if ((lst != NULL) && S_ISDIR(lst->st_mode))
690                         descend = 1;
691
692                 /*
693                  * If user has asked us not to cross mount points,
694                  * then don't descend into into a dir on a different
695                  * device.
696                  */
697                 if (!dev_recorded) {
698                         first_dev = lst->st_dev;
699                         dev_recorded = 1;
700                 }
701                 if (bsdtar->option_dont_traverse_mounts) {
702                         if (lst != NULL && lst->st_dev != first_dev)
703                                 descend = 0;
704                 }
705
706                 /*
707                  * If this file/dir is flagged "nodump" and we're
708                  * honoring such flags, skip this file/dir.
709                  */
710 #ifdef HAVE_CHFLAGS
711                 if (bsdtar->option_honor_nodump &&
712                     (lst->st_flags & UF_NODUMP))
713                         continue;
714 #endif
715
716 #ifdef __linux
717                 /*
718                  * Linux has a nodump flag too but to read it
719                  * we have to open() the file/dir and do an ioctl on it...
720                  */
721                 if (bsdtar->option_honor_nodump &&
722                     ((fd = open(name, O_RDONLY|O_NONBLOCK)) >= 0) &&
723                     ((r = ioctl(fd, EXT2_IOC_GETFLAGS, &fflags)),
724                         close(fd), r) >= 0 &&
725                     (fflags & EXT2_NODUMP_FL))
726                         continue;
727 #endif
728
729                 /*
730                  * If this file/dir is excluded by a filename
731                  * pattern, skip it.
732                  */
733                 if (excluded(bsdtar, name))
734                         continue;
735
736                 /*
737                  * If the user vetoes this file/directory, skip it.
738                  */
739                 if (bsdtar->option_interactive &&
740                     !yes("add '%s'", name))
741                         continue;
742
743                 /*
744                  * If this is a dir, decide whether or not to recurse.
745                  */
746                 if (bsdtar->option_no_subdirs)
747                         descend = 0;
748
749                 /*
750                  * Distinguish 'L'/'P'/'H' symlink following.
751                  */
752                 switch(symlink_mode) {
753                 case 'H':
754                         /* 'H': After the first item, rest like 'P'. */
755                         symlink_mode = 'P';
756                         /* 'H': First item (from command line) like 'L'. */
757                         /* FALLTHROUGH */
758                 case 'L':
759                         /* 'L': Do descend through a symlink to dir. */
760                         /* 'L': Archive symlink to file as file. */
761                         lst = tree_current_stat(tree);
762                         /* If stat fails, we have a broken symlink;
763                          * in that case, archive the link as such. */
764                         if (lst == NULL)
765                                 lst = tree_current_lstat(tree);
766                         break;
767                 default:
768                         /* 'P': Don't descend through a symlink to dir. */
769                         if (!S_ISDIR(lst->st_mode))
770                                 descend = 0;
771                         /* 'P': Archive symlink to file as symlink. */
772                         /* lst = tree_current_lstat(tree); */
773                         break;
774                 }
775
776                 if (descend)
777                         tree_descend(tree);
778
779                 /*
780                  * Write the entry.  Note that write_entry() handles
781                  * pathname editing and newness testing.
782                  */
783                 write_entry(bsdtar, a, lst, name,
784                     tree_current_access_path(tree));
785         }
786         tree_close(tree);
787 }
788
789 /*
790  * Backend for write_entry.
791  */
792 static void
793 write_entry_backend(struct bsdtar *bsdtar, struct archive *a,
794     struct archive_entry *entry)
795 {
796         int fd = -1;
797         int e;
798
799         if (archive_entry_size(entry) > 0) {
800                 const char *pathname = archive_entry_sourcepath(entry);
801                 fd = open(pathname, O_RDONLY);
802                 if (fd == -1) {
803                         if (!bsdtar->verbose)
804                                 bsdtar_warnc(bsdtar, errno,
805                                     "%s: could not open file", pathname);
806                         else
807                                 fprintf(stderr, ": %s", strerror(errno));
808                         return;
809                 }
810         }
811
812         e = archive_write_header(a, entry);
813         if (e != ARCHIVE_OK) {
814                 if (!bsdtar->verbose)
815                         bsdtar_warnc(bsdtar, 0, "%s: %s",
816                             archive_entry_pathname(entry),
817                             archive_error_string(a));
818                 else
819                         fprintf(stderr, ": %s", archive_error_string(a));
820         }
821
822         if (e == ARCHIVE_FATAL)
823                 exit(1);
824
825         /*
826          * If we opened a file earlier, write it out now.  Note that
827          * the format handler might have reset the size field to zero
828          * to inform us that the archive body won't get stored.  In
829          * that case, just skip the write.
830          */
831         if (e >= ARCHIVE_WARN && fd >= 0 && archive_entry_size(entry) > 0) {
832                 if (write_file_data(bsdtar, a, entry, fd))
833                         exit(1);
834         }
835
836         /*
837          * If we opened a file, close it now even if there was an error
838          * which made us decide not to write the archive body.
839          */
840         if (fd >= 0)
841                 close(fd);
842 }
843
844 /*
845  * Add a single filesystem object to the archive.
846  */
847 static void
848 write_entry(struct bsdtar *bsdtar, struct archive *a, const struct stat *st,
849     const char *pathname, const char *accpath)
850 {
851         struct archive_entry    *entry, *sparse_entry;
852 #ifdef __linux
853         int                      r;
854         unsigned long            stflags;
855 #endif
856         static char              linkbuffer[PATH_MAX+1];
857
858         entry = archive_entry_new();
859
860         archive_entry_set_pathname(entry, pathname);
861         archive_entry_copy_sourcepath(entry, accpath);
862
863         /*
864          * Rewrite the pathname to be archived.  If rewrite
865          * fails, skip the entry.
866          */
867         if (edit_pathname(bsdtar, entry))
868                 goto abort;
869
870         /*
871          * In -u mode, check that the file is newer than what's
872          * already in the archive; in all modes, obey --newerXXX flags.
873          */
874         if (!new_enough(bsdtar, archive_entry_pathname(entry), st))
875                 goto abort;
876
877         /* Display entry as we process it. This format is required by SUSv2. */
878         if (bsdtar->verbose)
879                 safe_fprintf(stderr, "a %s", archive_entry_pathname(entry));
880
881         /* Read symbolic link information. */
882         if ((st->st_mode & S_IFMT) == S_IFLNK) {
883                 int lnklen;
884
885                 lnklen = readlink(accpath, linkbuffer, PATH_MAX);
886                 if (lnklen < 0) {
887                         if (!bsdtar->verbose)
888                                 bsdtar_warnc(bsdtar, errno,
889                                     "%s: Couldn't read symbolic link",
890                                     pathname);
891                         else
892                                 safe_fprintf(stderr,
893                                     ": Couldn't read symbolic link: %s",
894                                     strerror(errno));
895                         goto cleanup;
896                 }
897                 linkbuffer[lnklen] = 0;
898                 archive_entry_set_symlink(entry, linkbuffer);
899         }
900
901         /* Look up username and group name. */
902         archive_entry_set_uname(entry, lookup_uname(bsdtar, st->st_uid));
903         archive_entry_set_gname(entry, lookup_gname(bsdtar, st->st_gid));
904
905 #ifdef HAVE_CHFLAGS
906         if (st->st_flags != 0)
907                 archive_entry_set_fflags(entry, st->st_flags, 0);
908 #endif
909
910 #ifdef __linux
911         int fd;
912         if ((S_ISREG(st->st_mode) || S_ISDIR(st->st_mode)) &&
913             ((fd = open(accpath, O_RDONLY|O_NONBLOCK)) >= 0) &&
914             ((r = ioctl(fd, EXT2_IOC_GETFLAGS, &stflags)), close(fd), (fd = -1), r) >= 0 &&
915             stflags) {
916                 archive_entry_set_fflags(entry, stflags, 0);
917         }
918 #endif
919
920         archive_entry_copy_stat(entry, st);
921         setup_acls(bsdtar, entry, accpath);
922         setup_xattrs(bsdtar, entry, accpath);
923
924         /* Non-regular files get archived with zero size. */
925         if (!S_ISREG(st->st_mode))
926                 archive_entry_set_size(entry, 0);
927
928         /* Record what we're doing, for the benefit of SIGINFO / SIGUSR1. */
929         siginfo_setinfo(bsdtar, "adding", archive_entry_pathname(entry),
930             archive_entry_size(entry));
931         archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
932
933         /* Handle SIGINFO / SIGUSR1 request if one was made. */
934         siginfo_printinfo(bsdtar, 0);
935
936         while (entry != NULL) {
937                 write_entry_backend(bsdtar, a, entry);
938                 archive_entry_free(entry);
939                 entry = sparse_entry;
940                 sparse_entry = NULL;
941         }
942
943 cleanup:
944         if (bsdtar->verbose)
945                 fprintf(stderr, "\n");
946
947 abort:
948         if (entry != NULL)
949                 archive_entry_free(entry);
950 }
951
952
953 /* Helper function to copy file to archive. */
954 static int
955 write_file_data(struct bsdtar *bsdtar, struct archive *a,
956     struct archive_entry *entry, int fd)
957 {
958         ssize_t bytes_read;
959         ssize_t bytes_written;
960         off_t   progress = 0;
961
962         bytes_read = read(fd, bsdtar->buff, FILEDATABUFLEN);
963         while (bytes_read > 0) {
964                 siginfo_printinfo(bsdtar, progress);
965
966                 bytes_written = archive_write_data(a, bsdtar->buff,
967                     FILEDATABUFLEN);
968                 if (bytes_written < 0) {
969                         /* Write failed; this is bad */
970                         bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(a));
971                         return (-1);
972                 }
973                 if (bytes_written < bytes_read) {
974                         /* Write was truncated; warn but continue. */
975                         bsdtar_warnc(bsdtar, 0,
976                             "%s: Truncated write; file may have grown while being archived.",
977                             archive_entry_pathname(entry));
978                         return (0);
979                 }
980                 progress += bytes_written;
981                 bytes_read = read(fd, bsdtar->buff, FILEDATABUFLEN);
982         }
983         return 0;
984 }
985
986
987 static void
988 create_cleanup(struct bsdtar *bsdtar)
989 {
990         free_cache(bsdtar->uname_cache);
991         bsdtar->uname_cache = NULL;
992         free_cache(bsdtar->gname_cache);
993         bsdtar->gname_cache = NULL;
994 }
995
996 #ifdef HAVE_POSIX_ACL
997 static void             setup_acl(struct bsdtar *bsdtar,
998                              struct archive_entry *entry, const char *accpath,
999                              int acl_type, int archive_entry_acl_type);
1000
1001 static void
1002 setup_acls(struct bsdtar *bsdtar, struct archive_entry *entry,
1003     const char *accpath)
1004 {
1005         archive_entry_acl_clear(entry);
1006
1007         setup_acl(bsdtar, entry, accpath,
1008             ACL_TYPE_ACCESS, ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1009         /* Only directories can have default ACLs. */
1010         if (S_ISDIR(archive_entry_mode(entry)))
1011                 setup_acl(bsdtar, entry, accpath,
1012                     ACL_TYPE_DEFAULT, ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1013 }
1014
1015 static void
1016 setup_acl(struct bsdtar *bsdtar, struct archive_entry *entry,
1017     const char *accpath, int acl_type, int archive_entry_acl_type)
1018 {
1019         acl_t            acl;
1020         acl_tag_t        acl_tag;
1021         acl_entry_t      acl_entry;
1022         acl_permset_t    acl_permset;
1023         int              s, ae_id, ae_tag, ae_perm;
1024         const char      *ae_name;
1025
1026         /* Retrieve access ACL from file. */
1027         acl = acl_get_file(accpath, acl_type);
1028         if (acl != NULL) {
1029                 s = acl_get_entry(acl, ACL_FIRST_ENTRY, &acl_entry);
1030                 while (s == 1) {
1031                         ae_id = -1;
1032                         ae_name = NULL;
1033
1034                         acl_get_tag_type(acl_entry, &acl_tag);
1035                         if (acl_tag == ACL_USER) {
1036                                 ae_id = (int)*(uid_t *)acl_get_qualifier(acl_entry);
1037                                 ae_name = lookup_uname(bsdtar, ae_id);
1038                                 ae_tag = ARCHIVE_ENTRY_ACL_USER;
1039                         } else if (acl_tag == ACL_GROUP) {
1040                                 ae_id = (int)*(gid_t *)acl_get_qualifier(acl_entry);
1041                                 ae_name = lookup_gname(bsdtar, ae_id);
1042                                 ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
1043                         } else if (acl_tag == ACL_MASK) {
1044                                 ae_tag = ARCHIVE_ENTRY_ACL_MASK;
1045                         } else if (acl_tag == ACL_USER_OBJ) {
1046                                 ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
1047                         } else if (acl_tag == ACL_GROUP_OBJ) {
1048                                 ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
1049                         } else if (acl_tag == ACL_OTHER) {
1050                                 ae_tag = ARCHIVE_ENTRY_ACL_OTHER;
1051                         } else {
1052                                 /* Skip types that libarchive can't support. */
1053                                 continue;
1054                         }
1055
1056                         acl_get_permset(acl_entry, &acl_permset);
1057                         ae_perm = 0;
1058                         /*
1059                          * acl_get_perm() is spelled differently on different
1060                          * platforms; see bsdtar_platform.h for details.
1061                          */
1062                         if (ACL_GET_PERM(acl_permset, ACL_EXECUTE))
1063                                 ae_perm |= ARCHIVE_ENTRY_ACL_EXECUTE;
1064                         if (ACL_GET_PERM(acl_permset, ACL_READ))
1065                                 ae_perm |= ARCHIVE_ENTRY_ACL_READ;
1066                         if (ACL_GET_PERM(acl_permset, ACL_WRITE))
1067                                 ae_perm |= ARCHIVE_ENTRY_ACL_WRITE;
1068
1069                         archive_entry_acl_add_entry(entry,
1070                             archive_entry_acl_type, ae_perm, ae_tag,
1071                             ae_id, ae_name);
1072
1073                         s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
1074                 }
1075                 acl_free(acl);
1076         }
1077 }
1078 #else
1079 static void
1080 setup_acls(struct bsdtar *bsdtar, struct archive_entry *entry,
1081     const char *accpath)
1082 {
1083         (void)bsdtar;
1084         (void)entry;
1085         (void)accpath;
1086 }
1087 #endif
1088
1089 #if HAVE_LISTXATTR && HAVE_LLISTXATTR && HAVE_GETXATTR && HAVE_LGETXATTR
1090
1091 static void
1092 setup_xattr(struct bsdtar *bsdtar, struct archive_entry *entry,
1093     const char *accpath, const char *name)
1094 {
1095         size_t size;
1096         void *value = NULL;
1097         char symlink_mode = bsdtar->symlink_mode;
1098
1099         if (symlink_mode == 'H')
1100                 size = getxattr(accpath, name, NULL, 0);
1101         else
1102                 size = lgetxattr(accpath, name, NULL, 0);
1103
1104         if (size == -1) {
1105                 bsdtar_warnc(bsdtar, errno, "Couldn't get extended attribute");
1106                 return;
1107         }
1108
1109         if (size > 0 && (value = malloc(size)) == NULL) {
1110                 bsdtar_errc(bsdtar, 1, errno, "Out of memory");
1111                 return;
1112         }
1113
1114         if (symlink_mode == 'H')
1115                 size = getxattr(accpath, name, value, size);
1116         else
1117                 size = lgetxattr(accpath, name, value, size);
1118
1119         if (size == -1) {
1120                 bsdtar_warnc(bsdtar, errno, "Couldn't get extended attribute");
1121                 return;
1122         }
1123
1124         archive_entry_xattr_add_entry(entry, name, value, size);
1125
1126         free(value);
1127 }
1128
1129 /*
1130  * Linux extended attribute support
1131  */
1132 static void
1133 setup_xattrs(struct bsdtar *bsdtar, struct archive_entry *entry,
1134     const char *accpath)
1135 {
1136         char *list, *p;
1137         size_t list_size;
1138         char symlink_mode = bsdtar->symlink_mode;
1139
1140         if (symlink_mode == 'H')
1141                 list_size = listxattr(accpath, NULL, 0);
1142         else
1143                 list_size = llistxattr(accpath, NULL, 0);
1144
1145         if (list_size == -1) {
1146                 bsdtar_warnc(bsdtar, errno,
1147                         "Couldn't list extended attributes");
1148                 return;
1149         } else if (list_size == 0)
1150                 return;
1151
1152         if ((list = malloc(list_size)) == NULL) {
1153                 bsdtar_errc(bsdtar, 1, errno, "Out of memory");
1154                 return;
1155         }
1156
1157         if (symlink_mode == 'H')
1158                 list_size = listxattr(accpath, list, list_size);
1159         else
1160                 list_size = llistxattr(accpath, list, list_size);
1161
1162         if (list_size == -1) {
1163                 bsdtar_warnc(bsdtar, errno,
1164                         "Couldn't list extended attributes");
1165                 free(list);
1166                 return;
1167         }
1168
1169         for (p = list; (p - list) < list_size; p += strlen(p) + 1) {
1170                 if (strncmp(p, "system.", 7) == 0 ||
1171                                 strncmp(p, "xfsroot.", 8) == 0)
1172                         continue;
1173
1174                 setup_xattr(bsdtar, entry, accpath, p);
1175         }
1176
1177         free(list);
1178 }
1179
1180 #else
1181
1182 /*
1183  * Generic (stub) extended attribute support.
1184  */
1185 static void
1186 setup_xattrs(struct bsdtar *bsdtar, struct archive_entry *entry,
1187     const char *accpath)
1188 {
1189         (void)bsdtar; /* UNUSED */
1190         (void)entry; /* UNUSED */
1191         (void)accpath; /* UNUSED */
1192 }
1193
1194 #endif
1195
1196 static void
1197 free_cache(struct name_cache *cache)
1198 {
1199         size_t i;
1200
1201         if (cache != NULL) {
1202                 for (i = 0; i < cache->size; i++) {
1203                         if (cache->cache[i].name != NULL &&
1204                             cache->cache[i].name != NO_NAME)
1205                                 free((void *)(uintptr_t)cache->cache[i].name);
1206                 }
1207                 free(cache);
1208         }
1209 }
1210
1211 /*
1212  * Lookup uid/gid from uname/gname, return NULL if no match.
1213  */
1214 static const char *
1215 lookup_name(struct bsdtar *bsdtar, struct name_cache **name_cache_variable,
1216     int (*lookup_fn)(struct bsdtar *, const char **, id_t), id_t id)
1217 {
1218         struct name_cache       *cache;
1219         const char *name;
1220         int slot;
1221
1222
1223         if (*name_cache_variable == NULL) {
1224                 *name_cache_variable = malloc(sizeof(struct name_cache));
1225                 if (*name_cache_variable == NULL)
1226                         bsdtar_errc(bsdtar, 1, ENOMEM, "No more memory");
1227                 memset(*name_cache_variable, 0, sizeof(struct name_cache));
1228                 (*name_cache_variable)->size = name_cache_size;
1229         }
1230
1231         cache = *name_cache_variable;
1232         cache->probes++;
1233
1234         slot = id % cache->size;
1235         if (cache->cache[slot].name != NULL) {
1236                 if (cache->cache[slot].id == id) {
1237                         cache->hits++;
1238                         if (cache->cache[slot].name == NO_NAME)
1239                                 return (NULL);
1240                         return (cache->cache[slot].name);
1241                 }
1242                 if (cache->cache[slot].name != NO_NAME)
1243                         free((void *)(uintptr_t)cache->cache[slot].name);
1244                 cache->cache[slot].name = NULL;
1245         }
1246
1247         if (lookup_fn(bsdtar, &name, id) == 0) {
1248                 if (name == NULL || name[0] == '\0') {
1249                         /* Cache the negative response. */
1250                         cache->cache[slot].name = NO_NAME;
1251                         cache->cache[slot].id = id;
1252                 } else {
1253                         cache->cache[slot].name = strdup(name);
1254                         if (cache->cache[slot].name != NULL) {
1255                                 cache->cache[slot].id = id;
1256                                 return (cache->cache[slot].name);
1257                         }
1258                         /*
1259                          * Conveniently, NULL marks an empty slot, so
1260                          * if the strdup() fails, we've just failed to
1261                          * cache it.  No recovery necessary.
1262                          */
1263                 }
1264         }
1265         return (NULL);
1266 }
1267
1268 static const char *
1269 lookup_uname(struct bsdtar *bsdtar, uid_t uid)
1270 {
1271         return (lookup_name(bsdtar, &bsdtar->uname_cache,
1272                     &lookup_uname_helper, (id_t)uid));
1273 }
1274
1275 static int
1276 lookup_uname_helper(struct bsdtar *bsdtar, const char **name, id_t id)
1277 {
1278         struct passwd   *pwent;
1279
1280         (void)bsdtar; /* UNUSED */
1281
1282         errno = 0;
1283         pwent = getpwuid((uid_t)id);
1284         if (pwent == NULL) {
1285                 *name = NULL;
1286                 if (errno != 0)
1287                         bsdtar_warnc(bsdtar, errno, "getpwuid(%d) failed", id);
1288                 return (errno);
1289         }
1290
1291         *name = pwent->pw_name;
1292         return (0);
1293 }
1294
1295 static const char *
1296 lookup_gname(struct bsdtar *bsdtar, gid_t gid)
1297 {
1298         return (lookup_name(bsdtar, &bsdtar->gname_cache,
1299                     &lookup_gname_helper, (id_t)gid));
1300 }
1301
1302 static int
1303 lookup_gname_helper(struct bsdtar *bsdtar, const char **name, id_t id)
1304 {
1305         struct group    *grent;
1306
1307         (void)bsdtar; /* UNUSED */
1308
1309         errno = 0;
1310         grent = getgrgid((gid_t)id);
1311         if (grent == NULL) {
1312                 *name = NULL;
1313                 if (errno != 0)
1314                         bsdtar_warnc(bsdtar, errno, "getgrgid(%d) failed", id);
1315                 return (errno);
1316         }
1317
1318         *name = grent->gr_name;
1319         return (0);
1320 }
1321
1322 /*
1323  * Test if the specified file is new enough to include in the archive.
1324  */
1325 int
1326 new_enough(struct bsdtar *bsdtar, const char *path, const struct stat *st)
1327 {
1328         struct archive_dir_entry *p;
1329
1330         /*
1331          * If this file/dir is excluded by a time comparison, skip it.
1332          */
1333         if (bsdtar->newer_ctime_sec > 0) {
1334                 if (st->st_ctime < bsdtar->newer_ctime_sec)
1335                         return (0); /* Too old, skip it. */
1336                 if (st->st_ctime == bsdtar->newer_ctime_sec
1337                     && ARCHIVE_STAT_CTIME_NANOS(st)
1338                     <= bsdtar->newer_ctime_nsec)
1339                         return (0); /* Too old, skip it. */
1340         }
1341         if (bsdtar->newer_mtime_sec > 0) {
1342                 if (st->st_mtime < bsdtar->newer_mtime_sec)
1343                         return (0); /* Too old, skip it. */
1344                 if (st->st_mtime == bsdtar->newer_mtime_sec
1345                     && ARCHIVE_STAT_MTIME_NANOS(st)
1346                     <= bsdtar->newer_mtime_nsec)
1347                         return (0); /* Too old, skip it. */
1348         }
1349
1350         /*
1351          * In -u mode, we only write an entry if it's newer than
1352          * what was already in the archive.
1353          */
1354         if (bsdtar->archive_dir != NULL &&
1355             bsdtar->archive_dir->head != NULL) {
1356                 for (p = bsdtar->archive_dir->head; p != NULL; p = p->next) {
1357                         if (pathcmp(path, p->name)==0)
1358                                 return (p->mtime_sec < st->st_mtime ||
1359                                     (p->mtime_sec == st->st_mtime &&
1360                                         p->mtime_nsec
1361                                         < ARCHIVE_STAT_MTIME_NANOS(st)));
1362                 }
1363         }
1364
1365         /* If the file wasn't rejected, include it. */
1366         return (1);
1367 }
1368
1369 /*
1370  * Add an entry to the dir list for 'u' mode.
1371  *
1372  * XXX TODO: Make this fast.
1373  */
1374 static void
1375 add_dir_list(struct bsdtar *bsdtar, const char *path,
1376     time_t mtime_sec, int mtime_nsec)
1377 {
1378         struct archive_dir_entry        *p;
1379
1380         /*
1381          * Search entire list to see if this file has appeared before.
1382          * If it has, override the timestamp data.
1383          */
1384         p = bsdtar->archive_dir->head;
1385         while (p != NULL) {
1386                 if (strcmp(path, p->name)==0) {
1387                         p->mtime_sec = mtime_sec;
1388                         p->mtime_nsec = mtime_nsec;
1389                         return;
1390                 }
1391                 p = p->next;
1392         }
1393
1394         p = malloc(sizeof(*p));
1395         if (p == NULL)
1396                 bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read archive directory");
1397
1398         p->name = strdup(path);
1399         if (p->name == NULL)
1400                 bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read archive directory");
1401         p->mtime_sec = mtime_sec;
1402         p->mtime_nsec = mtime_nsec;
1403         p->next = NULL;
1404         if (bsdtar->archive_dir->tail == NULL) {
1405                 bsdtar->archive_dir->head = bsdtar->archive_dir->tail = p;
1406         } else {
1407                 bsdtar->archive_dir->tail->next = p;
1408                 bsdtar->archive_dir->tail = p;
1409         }
1410 }
1411
1412 void
1413 test_for_append(struct bsdtar *bsdtar)
1414 {
1415         struct stat s;
1416
1417         if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
1418                 bsdtar_errc(bsdtar, 1, 0, "no files or directories specified");
1419         if (bsdtar->filename == NULL)
1420                 bsdtar_errc(bsdtar, 1, 0, "Cannot append to stdout.");
1421
1422         if (bsdtar->create_compression != 0)
1423                 bsdtar_errc(bsdtar, 1, 0,
1424                     "Cannot append to %s with compression", bsdtar->filename);
1425
1426         if (stat(bsdtar->filename, &s) != 0)
1427                 return;
1428
1429         if (!S_ISREG(s.st_mode) && !S_ISBLK(s.st_mode))
1430                 bsdtar_errc(bsdtar, 1, 0,
1431                     "Cannot append to %s: not a regular file.",
1432                     bsdtar->filename);
1433 }