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