]> CyberLeo.Net >> Repos - FreeBSD/releng/7.2.git/blob - usr.bin/tar/write.c
Create releng/7.2 from stable/7 in preparation for 7.2-RELEASE.
[FreeBSD/releng/7.2.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                         bsdtar->return_value = 1;
665                 }
666                 if (tree_ret != TREE_REGULAR)
667                         continue;
668                 lst = tree_current_lstat(tree);
669                 if (lst == NULL) {
670                         /* Couldn't lstat(); must not exist. */
671                         bsdtar_warnc(bsdtar, errno, "%s: Cannot stat", name);
672
673                         /*
674                          * Report an error via the exit code if the failed
675                          * path is a prefix of what the user provided via
676                          * the command line.  (Testing for string equality
677                          * here won't work due to trailing '/' characters.)
678                          */
679                         if (memcmp(name, path, strlen(name)) == 0)
680                                 bsdtar->return_value = 1;
681
682                         continue;
683                 }
684                 if (S_ISLNK(lst->st_mode))
685                         st = tree_current_stat(tree);
686                 /* Default: descend into any dir or symlink to dir. */
687                 /* We'll adjust this later on. */
688                 descend = 0;
689                 if ((st != NULL) && S_ISDIR(st->st_mode))
690                         descend = 1;
691                 if ((lst != NULL) && S_ISDIR(lst->st_mode))
692                         descend = 1;
693
694                 /*
695                  * If user has asked us not to cross mount points,
696                  * then don't descend into into a dir on a different
697                  * device.
698                  */
699                 if (!dev_recorded) {
700                         first_dev = lst->st_dev;
701                         dev_recorded = 1;
702                 }
703                 if (bsdtar->option_dont_traverse_mounts) {
704                         if (lst != NULL && lst->st_dev != first_dev)
705                                 descend = 0;
706                 }
707
708                 /*
709                  * If this file/dir is flagged "nodump" and we're
710                  * honoring such flags, skip this file/dir.
711                  */
712 #ifdef HAVE_CHFLAGS
713                 if (bsdtar->option_honor_nodump &&
714                     (lst->st_flags & UF_NODUMP))
715                         continue;
716 #endif
717
718 #ifdef __linux
719                 /*
720                  * Linux has a nodump flag too but to read it
721                  * we have to open() the file/dir and do an ioctl on it...
722                  */
723                 if (bsdtar->option_honor_nodump &&
724                     ((fd = open(name, O_RDONLY|O_NONBLOCK)) >= 0) &&
725                     ((r = ioctl(fd, EXT2_IOC_GETFLAGS, &fflags)),
726                         close(fd), r) >= 0 &&
727                     (fflags & EXT2_NODUMP_FL))
728                         continue;
729 #endif
730
731                 /*
732                  * If this file/dir is excluded by a filename
733                  * pattern, skip it.
734                  */
735                 if (excluded(bsdtar, name))
736                         continue;
737
738                 /*
739                  * If the user vetoes this file/directory, skip it.
740                  */
741                 if (bsdtar->option_interactive &&
742                     !yes("add '%s'", name))
743                         continue;
744
745                 /*
746                  * If this is a dir, decide whether or not to recurse.
747                  */
748                 if (bsdtar->option_no_subdirs)
749                         descend = 0;
750
751                 /*
752                  * Distinguish 'L'/'P'/'H' symlink following.
753                  */
754                 switch(symlink_mode) {
755                 case 'H':
756                         /* 'H': After the first item, rest like 'P'. */
757                         symlink_mode = 'P';
758                         /* 'H': First item (from command line) like 'L'. */
759                         /* FALLTHROUGH */
760                 case 'L':
761                         /* 'L': Do descend through a symlink to dir. */
762                         /* 'L': Archive symlink to file as file. */
763                         lst = tree_current_stat(tree);
764                         /* If stat fails, we have a broken symlink;
765                          * in that case, archive the link as such. */
766                         if (lst == NULL)
767                                 lst = tree_current_lstat(tree);
768                         break;
769                 default:
770                         /* 'P': Don't descend through a symlink to dir. */
771                         if (!S_ISDIR(lst->st_mode))
772                                 descend = 0;
773                         /* 'P': Archive symlink to file as symlink. */
774                         /* lst = tree_current_lstat(tree); */
775                         break;
776                 }
777
778                 if (descend)
779                         tree_descend(tree);
780
781                 /*
782                  * Write the entry.  Note that write_entry() handles
783                  * pathname editing and newness testing.
784                  */
785                 write_entry(bsdtar, a, lst, name,
786                     tree_current_access_path(tree));
787         }
788         tree_close(tree);
789 }
790
791 /*
792  * Backend for write_entry.
793  */
794 static void
795 write_entry_backend(struct bsdtar *bsdtar, struct archive *a,
796     struct archive_entry *entry)
797 {
798         int fd = -1;
799         int e;
800
801         if (archive_entry_size(entry) > 0) {
802                 const char *pathname = archive_entry_sourcepath(entry);
803                 fd = open(pathname, O_RDONLY);
804                 if (fd == -1) {
805                         if (!bsdtar->verbose)
806                                 bsdtar_warnc(bsdtar, errno,
807                                     "%s: could not open file", pathname);
808                         else
809                                 fprintf(stderr, ": %s", strerror(errno));
810                         return;
811                 }
812         }
813
814         e = archive_write_header(a, entry);
815         if (e != ARCHIVE_OK) {
816                 if (!bsdtar->verbose)
817                         bsdtar_warnc(bsdtar, 0, "%s: %s",
818                             archive_entry_pathname(entry),
819                             archive_error_string(a));
820                 else
821                         fprintf(stderr, ": %s", archive_error_string(a));
822         }
823
824         if (e == ARCHIVE_FATAL)
825                 exit(1);
826
827         /*
828          * If we opened a file earlier, write it out now.  Note that
829          * the format handler might have reset the size field to zero
830          * to inform us that the archive body won't get stored.  In
831          * that case, just skip the write.
832          */
833         if (e >= ARCHIVE_WARN && fd >= 0 && archive_entry_size(entry) > 0) {
834                 if (write_file_data(bsdtar, a, entry, fd))
835                         exit(1);
836         }
837
838         /*
839          * If we opened a file, close it now even if there was an error
840          * which made us decide not to write the archive body.
841          */
842         if (fd >= 0)
843                 close(fd);
844 }
845
846 /*
847  * Add a single filesystem object to the archive.
848  */
849 static void
850 write_entry(struct bsdtar *bsdtar, struct archive *a, const struct stat *st,
851     const char *pathname, const char *accpath)
852 {
853         struct archive_entry    *entry, *sparse_entry;
854 #ifdef __linux
855         int                      r;
856         unsigned long            stflags;
857 #endif
858         static char              linkbuffer[PATH_MAX+1];
859
860         entry = archive_entry_new();
861
862         archive_entry_set_pathname(entry, pathname);
863         archive_entry_copy_sourcepath(entry, accpath);
864
865         /*
866          * Rewrite the pathname to be archived.  If rewrite
867          * fails, skip the entry.
868          */
869         if (edit_pathname(bsdtar, entry))
870                 goto abort;
871
872         /*
873          * In -u mode, check that the file is newer than what's
874          * already in the archive; in all modes, obey --newerXXX flags.
875          */
876         if (!new_enough(bsdtar, archive_entry_pathname(entry), st))
877                 goto abort;
878
879         /* Display entry as we process it. This format is required by SUSv2. */
880         if (bsdtar->verbose)
881                 safe_fprintf(stderr, "a %s", archive_entry_pathname(entry));
882
883         /* Read symbolic link information. */
884         if ((st->st_mode & S_IFMT) == S_IFLNK) {
885                 int lnklen;
886
887                 lnklen = readlink(accpath, linkbuffer, PATH_MAX);
888                 if (lnklen < 0) {
889                         if (!bsdtar->verbose)
890                                 bsdtar_warnc(bsdtar, errno,
891                                     "%s: Couldn't read symbolic link",
892                                     pathname);
893                         else
894                                 safe_fprintf(stderr,
895                                     ": Couldn't read symbolic link: %s",
896                                     strerror(errno));
897                         goto cleanup;
898                 }
899                 linkbuffer[lnklen] = 0;
900                 archive_entry_set_symlink(entry, linkbuffer);
901         }
902
903         /* Look up username and group name. */
904         archive_entry_set_uname(entry, lookup_uname(bsdtar, st->st_uid));
905         archive_entry_set_gname(entry, lookup_gname(bsdtar, st->st_gid));
906
907 #ifdef HAVE_CHFLAGS
908         if (st->st_flags != 0)
909                 archive_entry_set_fflags(entry, st->st_flags, 0);
910 #endif
911
912 #ifdef __linux
913         int fd;
914         if ((S_ISREG(st->st_mode) || S_ISDIR(st->st_mode)) &&
915             ((fd = open(accpath, O_RDONLY|O_NONBLOCK)) >= 0) &&
916             ((r = ioctl(fd, EXT2_IOC_GETFLAGS, &stflags)), close(fd), (fd = -1), r) >= 0 &&
917             stflags) {
918                 archive_entry_set_fflags(entry, stflags, 0);
919         }
920 #endif
921
922         archive_entry_copy_stat(entry, st);
923         setup_acls(bsdtar, entry, accpath);
924         setup_xattrs(bsdtar, entry, accpath);
925
926         /* Non-regular files get archived with zero size. */
927         if (!S_ISREG(st->st_mode))
928                 archive_entry_set_size(entry, 0);
929
930         /* Record what we're doing, for the benefit of SIGINFO / SIGUSR1. */
931         siginfo_setinfo(bsdtar, "adding", archive_entry_pathname(entry),
932             archive_entry_size(entry));
933         archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
934
935         /* Handle SIGINFO / SIGUSR1 request if one was made. */
936         siginfo_printinfo(bsdtar, 0);
937
938         while (entry != NULL) {
939                 write_entry_backend(bsdtar, a, entry);
940                 archive_entry_free(entry);
941                 entry = sparse_entry;
942                 sparse_entry = NULL;
943         }
944
945 cleanup:
946         if (bsdtar->verbose)
947                 fprintf(stderr, "\n");
948
949 abort:
950         if (entry != NULL)
951                 archive_entry_free(entry);
952 }
953
954
955 /* Helper function to copy file to archive. */
956 static int
957 write_file_data(struct bsdtar *bsdtar, struct archive *a,
958     struct archive_entry *entry, int fd)
959 {
960         ssize_t bytes_read;
961         ssize_t bytes_written;
962         off_t   progress = 0;
963
964         bytes_read = read(fd, bsdtar->buff, FILEDATABUFLEN);
965         while (bytes_read > 0) {
966                 siginfo_printinfo(bsdtar, progress);
967
968                 bytes_written = archive_write_data(a, bsdtar->buff,
969                     bytes_read);
970                 if (bytes_written < 0) {
971                         /* Write failed; this is bad */
972                         bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(a));
973                         return (-1);
974                 }
975                 if (bytes_written < bytes_read) {
976                         /* Write was truncated; warn but continue. */
977                         bsdtar_warnc(bsdtar, 0,
978                             "%s: Truncated write; file may have grown while being archived.",
979                             archive_entry_pathname(entry));
980                         return (0);
981                 }
982                 progress += bytes_written;
983                 bytes_read = read(fd, bsdtar->buff, FILEDATABUFLEN);
984         }
985         return 0;
986 }
987
988
989 static void
990 create_cleanup(struct bsdtar *bsdtar)
991 {
992         free_cache(bsdtar->uname_cache);
993         bsdtar->uname_cache = NULL;
994         free_cache(bsdtar->gname_cache);
995         bsdtar->gname_cache = NULL;
996 }
997
998 #ifdef HAVE_POSIX_ACL
999 static void             setup_acl(struct bsdtar *bsdtar,
1000                              struct archive_entry *entry, const char *accpath,
1001                              int acl_type, int archive_entry_acl_type);
1002
1003 static void
1004 setup_acls(struct bsdtar *bsdtar, struct archive_entry *entry,
1005     const char *accpath)
1006 {
1007         archive_entry_acl_clear(entry);
1008
1009         setup_acl(bsdtar, entry, accpath,
1010             ACL_TYPE_ACCESS, ARCHIVE_ENTRY_ACL_TYPE_ACCESS);
1011         /* Only directories can have default ACLs. */
1012         if (S_ISDIR(archive_entry_mode(entry)))
1013                 setup_acl(bsdtar, entry, accpath,
1014                     ACL_TYPE_DEFAULT, ARCHIVE_ENTRY_ACL_TYPE_DEFAULT);
1015 }
1016
1017 static void
1018 setup_acl(struct bsdtar *bsdtar, struct archive_entry *entry,
1019     const char *accpath, int acl_type, int archive_entry_acl_type)
1020 {
1021         acl_t            acl;
1022         acl_tag_t        acl_tag;
1023         acl_entry_t      acl_entry;
1024         acl_permset_t    acl_permset;
1025         int              s, ae_id, ae_tag, ae_perm;
1026         const char      *ae_name;
1027
1028         /* Retrieve access ACL from file. */
1029         acl = acl_get_file(accpath, acl_type);
1030         if (acl != NULL) {
1031                 s = acl_get_entry(acl, ACL_FIRST_ENTRY, &acl_entry);
1032                 while (s == 1) {
1033                         ae_id = -1;
1034                         ae_name = NULL;
1035
1036                         acl_get_tag_type(acl_entry, &acl_tag);
1037                         if (acl_tag == ACL_USER) {
1038                                 ae_id = (int)*(uid_t *)acl_get_qualifier(acl_entry);
1039                                 ae_name = lookup_uname(bsdtar, ae_id);
1040                                 ae_tag = ARCHIVE_ENTRY_ACL_USER;
1041                         } else if (acl_tag == ACL_GROUP) {
1042                                 ae_id = (int)*(gid_t *)acl_get_qualifier(acl_entry);
1043                                 ae_name = lookup_gname(bsdtar, ae_id);
1044                                 ae_tag = ARCHIVE_ENTRY_ACL_GROUP;
1045                         } else if (acl_tag == ACL_MASK) {
1046                                 ae_tag = ARCHIVE_ENTRY_ACL_MASK;
1047                         } else if (acl_tag == ACL_USER_OBJ) {
1048                                 ae_tag = ARCHIVE_ENTRY_ACL_USER_OBJ;
1049                         } else if (acl_tag == ACL_GROUP_OBJ) {
1050                                 ae_tag = ARCHIVE_ENTRY_ACL_GROUP_OBJ;
1051                         } else if (acl_tag == ACL_OTHER) {
1052                                 ae_tag = ARCHIVE_ENTRY_ACL_OTHER;
1053                         } else {
1054                                 /* Skip types that libarchive can't support. */
1055                                 continue;
1056                         }
1057
1058                         acl_get_permset(acl_entry, &acl_permset);
1059                         ae_perm = 0;
1060                         /*
1061                          * acl_get_perm() is spelled differently on different
1062                          * platforms; see bsdtar_platform.h for details.
1063                          */
1064                         if (ACL_GET_PERM(acl_permset, ACL_EXECUTE))
1065                                 ae_perm |= ARCHIVE_ENTRY_ACL_EXECUTE;
1066                         if (ACL_GET_PERM(acl_permset, ACL_READ))
1067                                 ae_perm |= ARCHIVE_ENTRY_ACL_READ;
1068                         if (ACL_GET_PERM(acl_permset, ACL_WRITE))
1069                                 ae_perm |= ARCHIVE_ENTRY_ACL_WRITE;
1070
1071                         archive_entry_acl_add_entry(entry,
1072                             archive_entry_acl_type, ae_perm, ae_tag,
1073                             ae_id, ae_name);
1074
1075                         s = acl_get_entry(acl, ACL_NEXT_ENTRY, &acl_entry);
1076                 }
1077                 acl_free(acl);
1078         }
1079 }
1080 #else
1081 static void
1082 setup_acls(struct bsdtar *bsdtar, struct archive_entry *entry,
1083     const char *accpath)
1084 {
1085         (void)bsdtar;
1086         (void)entry;
1087         (void)accpath;
1088 }
1089 #endif
1090
1091 #if HAVE_LISTXATTR && HAVE_LLISTXATTR && HAVE_GETXATTR && HAVE_LGETXATTR
1092
1093 static void
1094 setup_xattr(struct bsdtar *bsdtar, struct archive_entry *entry,
1095     const char *accpath, const char *name)
1096 {
1097         size_t size;
1098         void *value = NULL;
1099         char symlink_mode = bsdtar->symlink_mode;
1100
1101         if (symlink_mode == 'H')
1102                 size = getxattr(accpath, name, NULL, 0);
1103         else
1104                 size = lgetxattr(accpath, name, NULL, 0);
1105
1106         if (size == -1) {
1107                 bsdtar_warnc(bsdtar, errno, "Couldn't get extended attribute");
1108                 return;
1109         }
1110
1111         if (size > 0 && (value = malloc(size)) == NULL) {
1112                 bsdtar_errc(bsdtar, 1, errno, "Out of memory");
1113                 return;
1114         }
1115
1116         if (symlink_mode == 'H')
1117                 size = getxattr(accpath, name, value, size);
1118         else
1119                 size = lgetxattr(accpath, name, value, size);
1120
1121         if (size == -1) {
1122                 bsdtar_warnc(bsdtar, errno, "Couldn't get extended attribute");
1123                 return;
1124         }
1125
1126         archive_entry_xattr_add_entry(entry, name, value, size);
1127
1128         free(value);
1129 }
1130
1131 /*
1132  * Linux extended attribute support
1133  */
1134 static void
1135 setup_xattrs(struct bsdtar *bsdtar, struct archive_entry *entry,
1136     const char *accpath)
1137 {
1138         char *list, *p;
1139         size_t list_size;
1140         char symlink_mode = bsdtar->symlink_mode;
1141
1142         if (symlink_mode == 'H')
1143                 list_size = listxattr(accpath, NULL, 0);
1144         else
1145                 list_size = llistxattr(accpath, NULL, 0);
1146
1147         if (list_size == -1) {
1148                 bsdtar_warnc(bsdtar, errno,
1149                         "Couldn't list extended attributes");
1150                 return;
1151         } else if (list_size == 0)
1152                 return;
1153
1154         if ((list = malloc(list_size)) == NULL) {
1155                 bsdtar_errc(bsdtar, 1, errno, "Out of memory");
1156                 return;
1157         }
1158
1159         if (symlink_mode == 'H')
1160                 list_size = listxattr(accpath, list, list_size);
1161         else
1162                 list_size = llistxattr(accpath, list, list_size);
1163
1164         if (list_size == -1) {
1165                 bsdtar_warnc(bsdtar, errno,
1166                         "Couldn't list extended attributes");
1167                 free(list);
1168                 return;
1169         }
1170
1171         for (p = list; (p - list) < list_size; p += strlen(p) + 1) {
1172                 if (strncmp(p, "system.", 7) == 0 ||
1173                                 strncmp(p, "xfsroot.", 8) == 0)
1174                         continue;
1175
1176                 setup_xattr(bsdtar, entry, accpath, p);
1177         }
1178
1179         free(list);
1180 }
1181
1182 #else
1183
1184 /*
1185  * Generic (stub) extended attribute support.
1186  */
1187 static void
1188 setup_xattrs(struct bsdtar *bsdtar, struct archive_entry *entry,
1189     const char *accpath)
1190 {
1191         (void)bsdtar; /* UNUSED */
1192         (void)entry; /* UNUSED */
1193         (void)accpath; /* UNUSED */
1194 }
1195
1196 #endif
1197
1198 static void
1199 free_cache(struct name_cache *cache)
1200 {
1201         size_t i;
1202
1203         if (cache != NULL) {
1204                 for (i = 0; i < cache->size; i++) {
1205                         if (cache->cache[i].name != NULL &&
1206                             cache->cache[i].name != NO_NAME)
1207                                 free((void *)(uintptr_t)cache->cache[i].name);
1208                 }
1209                 free(cache);
1210         }
1211 }
1212
1213 /*
1214  * Lookup uid/gid from uname/gname, return NULL if no match.
1215  */
1216 static const char *
1217 lookup_name(struct bsdtar *bsdtar, struct name_cache **name_cache_variable,
1218     int (*lookup_fn)(struct bsdtar *, const char **, id_t), id_t id)
1219 {
1220         struct name_cache       *cache;
1221         const char *name;
1222         int slot;
1223
1224
1225         if (*name_cache_variable == NULL) {
1226                 *name_cache_variable = malloc(sizeof(struct name_cache));
1227                 if (*name_cache_variable == NULL)
1228                         bsdtar_errc(bsdtar, 1, ENOMEM, "No more memory");
1229                 memset(*name_cache_variable, 0, sizeof(struct name_cache));
1230                 (*name_cache_variable)->size = name_cache_size;
1231         }
1232
1233         cache = *name_cache_variable;
1234         cache->probes++;
1235
1236         slot = id % cache->size;
1237         if (cache->cache[slot].name != NULL) {
1238                 if (cache->cache[slot].id == id) {
1239                         cache->hits++;
1240                         if (cache->cache[slot].name == NO_NAME)
1241                                 return (NULL);
1242                         return (cache->cache[slot].name);
1243                 }
1244                 if (cache->cache[slot].name != NO_NAME)
1245                         free((void *)(uintptr_t)cache->cache[slot].name);
1246                 cache->cache[slot].name = NULL;
1247         }
1248
1249         if (lookup_fn(bsdtar, &name, id) == 0) {
1250                 if (name == NULL || name[0] == '\0') {
1251                         /* Cache the negative response. */
1252                         cache->cache[slot].name = NO_NAME;
1253                         cache->cache[slot].id = id;
1254                 } else {
1255                         cache->cache[slot].name = strdup(name);
1256                         if (cache->cache[slot].name != NULL) {
1257                                 cache->cache[slot].id = id;
1258                                 return (cache->cache[slot].name);
1259                         }
1260                         /*
1261                          * Conveniently, NULL marks an empty slot, so
1262                          * if the strdup() fails, we've just failed to
1263                          * cache it.  No recovery necessary.
1264                          */
1265                 }
1266         }
1267         return (NULL);
1268 }
1269
1270 static const char *
1271 lookup_uname(struct bsdtar *bsdtar, uid_t uid)
1272 {
1273         return (lookup_name(bsdtar, &bsdtar->uname_cache,
1274                     &lookup_uname_helper, (id_t)uid));
1275 }
1276
1277 static int
1278 lookup_uname_helper(struct bsdtar *bsdtar, const char **name, id_t id)
1279 {
1280         struct passwd   *pwent;
1281
1282         (void)bsdtar; /* UNUSED */
1283
1284         errno = 0;
1285         pwent = getpwuid((uid_t)id);
1286         if (pwent == NULL) {
1287                 *name = NULL;
1288                 if (errno != 0)
1289                         bsdtar_warnc(bsdtar, errno, "getpwuid(%d) failed", id);
1290                 return (errno);
1291         }
1292
1293         *name = pwent->pw_name;
1294         return (0);
1295 }
1296
1297 static const char *
1298 lookup_gname(struct bsdtar *bsdtar, gid_t gid)
1299 {
1300         return (lookup_name(bsdtar, &bsdtar->gname_cache,
1301                     &lookup_gname_helper, (id_t)gid));
1302 }
1303
1304 static int
1305 lookup_gname_helper(struct bsdtar *bsdtar, const char **name, id_t id)
1306 {
1307         struct group    *grent;
1308
1309         (void)bsdtar; /* UNUSED */
1310
1311         errno = 0;
1312         grent = getgrgid((gid_t)id);
1313         if (grent == NULL) {
1314                 *name = NULL;
1315                 if (errno != 0)
1316                         bsdtar_warnc(bsdtar, errno, "getgrgid(%d) failed", id);
1317                 return (errno);
1318         }
1319
1320         *name = grent->gr_name;
1321         return (0);
1322 }
1323
1324 /*
1325  * Test if the specified file is new enough to include in the archive.
1326  */
1327 int
1328 new_enough(struct bsdtar *bsdtar, const char *path, const struct stat *st)
1329 {
1330         struct archive_dir_entry *p;
1331
1332         /*
1333          * If this file/dir is excluded by a time comparison, skip it.
1334          */
1335         if (bsdtar->newer_ctime_sec > 0) {
1336                 if (st->st_ctime < bsdtar->newer_ctime_sec)
1337                         return (0); /* Too old, skip it. */
1338                 if (st->st_ctime == bsdtar->newer_ctime_sec
1339                     && ARCHIVE_STAT_CTIME_NANOS(st)
1340                     <= bsdtar->newer_ctime_nsec)
1341                         return (0); /* Too old, skip it. */
1342         }
1343         if (bsdtar->newer_mtime_sec > 0) {
1344                 if (st->st_mtime < bsdtar->newer_mtime_sec)
1345                         return (0); /* Too old, skip it. */
1346                 if (st->st_mtime == bsdtar->newer_mtime_sec
1347                     && ARCHIVE_STAT_MTIME_NANOS(st)
1348                     <= bsdtar->newer_mtime_nsec)
1349                         return (0); /* Too old, skip it. */
1350         }
1351
1352         /*
1353          * In -u mode, we only write an entry if it's newer than
1354          * what was already in the archive.
1355          */
1356         if (bsdtar->archive_dir != NULL &&
1357             bsdtar->archive_dir->head != NULL) {
1358                 for (p = bsdtar->archive_dir->head; p != NULL; p = p->next) {
1359                         if (pathcmp(path, p->name)==0)
1360                                 return (p->mtime_sec < st->st_mtime ||
1361                                     (p->mtime_sec == st->st_mtime &&
1362                                         p->mtime_nsec
1363                                         < ARCHIVE_STAT_MTIME_NANOS(st)));
1364                 }
1365         }
1366
1367         /* If the file wasn't rejected, include it. */
1368         return (1);
1369 }
1370
1371 /*
1372  * Add an entry to the dir list for 'u' mode.
1373  *
1374  * XXX TODO: Make this fast.
1375  */
1376 static void
1377 add_dir_list(struct bsdtar *bsdtar, const char *path,
1378     time_t mtime_sec, int mtime_nsec)
1379 {
1380         struct archive_dir_entry        *p;
1381
1382         /*
1383          * Search entire list to see if this file has appeared before.
1384          * If it has, override the timestamp data.
1385          */
1386         p = bsdtar->archive_dir->head;
1387         while (p != NULL) {
1388                 if (strcmp(path, p->name)==0) {
1389                         p->mtime_sec = mtime_sec;
1390                         p->mtime_nsec = mtime_nsec;
1391                         return;
1392                 }
1393                 p = p->next;
1394         }
1395
1396         p = malloc(sizeof(*p));
1397         if (p == NULL)
1398                 bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read archive directory");
1399
1400         p->name = strdup(path);
1401         if (p->name == NULL)
1402                 bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read archive directory");
1403         p->mtime_sec = mtime_sec;
1404         p->mtime_nsec = mtime_nsec;
1405         p->next = NULL;
1406         if (bsdtar->archive_dir->tail == NULL) {
1407                 bsdtar->archive_dir->head = bsdtar->archive_dir->tail = p;
1408         } else {
1409                 bsdtar->archive_dir->tail->next = p;
1410                 bsdtar->archive_dir->tail = p;
1411         }
1412 }
1413
1414 void
1415 test_for_append(struct bsdtar *bsdtar)
1416 {
1417         struct stat s;
1418
1419         if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
1420                 bsdtar_errc(bsdtar, 1, 0, "no files or directories specified");
1421         if (bsdtar->filename == NULL)
1422                 bsdtar_errc(bsdtar, 1, 0, "Cannot append to stdout.");
1423
1424         if (bsdtar->create_compression != 0)
1425                 bsdtar_errc(bsdtar, 1, 0,
1426                     "Cannot append to %s with compression", bsdtar->filename);
1427
1428         if (stat(bsdtar->filename, &s) != 0)
1429                 return;
1430
1431         if (!S_ISREG(s.st_mode) && !S_ISBLK(s.st_mode))
1432                 bsdtar_errc(bsdtar, 1, 0,
1433                     "Cannot append to %s: not a regular file.",
1434                     bsdtar->filename);
1435 }