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