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