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