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