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