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