]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - usr.bin/tar/write.c
Merge r529 from libarchive.googlecode.com: Fix how we read ext2fs_fs.h
[FreeBSD/FreeBSD.git] / usr.bin / tar / write.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
22  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
23  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
24  */
25
26 #include "bsdtar_platform.h"
27 __FBSDID("$FreeBSD$");
28
29 #ifdef HAVE_SYS_TYPES_H
30 #include <sys/types.h>
31 #endif
32 #ifdef HAVE_SYS_ACL_H
33 #include <sys/acl.h>
34 #endif
35 #ifdef HAVE_SYS_IOCTL_H
36 #include <sys/ioctl.h>
37 #endif
38 #ifdef HAVE_SYS_STAT_H
39 #include <sys/stat.h>
40 #endif
41 #ifdef HAVE_ATTR_XATTR_H
42 #include <attr/xattr.h>
43 #endif
44 #ifdef HAVE_ERRNO_H
45 #include <errno.h>
46 #endif
47 #ifdef HAVE_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 /*
63  * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
64  * As the include guards don't agree, the order of include is important.
65  */
66 #ifdef HAVE_LINUX_EXT2_FS_H
67 #include <linux/ext2_fs.h>      /* for Linux file flags */
68 #endif
69 #if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
70 /* This header exists but is broken on Cygwin. */
71 #include <ext2fs/ext2_fs.h>
72 #endif
73 #ifdef HAVE_PWD_H
74 #include <pwd.h>
75 #endif
76 #include <stdio.h>
77 #ifdef HAVE_STDLIB_H
78 #include <stdlib.h>
79 #endif
80 #ifdef HAVE_STRING_H
81 #include <string.h>
82 #endif
83 #ifdef HAVE_UNISTD_H
84 #include <unistd.h>
85 #endif
86
87 #include "bsdtar.h"
88 #include "tree.h"
89
90 /* Size of buffer for holding file data prior to writing. */
91 #define FILEDATABUFLEN  65536
92
93 /* Fixed size of uname/gname caches. */
94 #define name_cache_size 101
95
96 static const char * const NO_NAME = "(noname)";
97
98 struct archive_dir_entry {
99         struct archive_dir_entry        *next;
100         time_t                   mtime_sec;
101         int                      mtime_nsec;
102         char                    *name;
103 };
104
105 struct archive_dir {
106         struct archive_dir_entry *head, *tail;
107 };
108
109 struct name_cache {
110         int     probes;
111         int     hits;
112         size_t  size;
113         struct {
114                 id_t id;
115                 const char *name;
116         } cache[name_cache_size];
117 };
118
119 static void              add_dir_list(struct bsdtar *bsdtar, const char *path,
120                              time_t mtime_sec, int mtime_nsec);
121 static int               append_archive(struct bsdtar *, struct archive *,
122                              struct archive *ina);
123 static int               append_archive_filename(struct bsdtar *,
124                              struct archive *, const char *fname);
125 static void              archive_names_from_file(struct bsdtar *bsdtar,
126                              struct archive *a);
127 static int               archive_names_from_file_helper(struct bsdtar *bsdtar,
128                              const char *line);
129 static int               copy_file_data(struct bsdtar *bsdtar,
130                              struct archive *a, struct archive *ina);
131 static int               new_enough(struct bsdtar *, const char *path,
132                              const struct stat *);
133 static void              test_for_append(struct bsdtar *);
134 static void              write_archive(struct archive *, struct bsdtar *);
135 static void              write_entry_backend(struct bsdtar *, struct archive *,
136                              struct archive_entry *);
137 static int               write_file_data(struct bsdtar *, struct archive *,
138                              struct archive_entry *, int fd);
139 static void              write_hierarchy(struct bsdtar *, struct archive *,
140                              const char *);
141
142 void
143 tar_mode_c(struct bsdtar *bsdtar)
144 {
145         struct archive *a;
146         int r;
147
148         if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
149                 bsdtar_errc(bsdtar, 1, 0, "no files or directories specified");
150
151         a = archive_write_new();
152
153         /* Support any format that the library supports. */
154         if (bsdtar->create_format == NULL) {
155                 r = archive_write_set_format_pax_restricted(a);
156                 bsdtar->create_format = "pax restricted";
157         } else {
158                 r = archive_write_set_format_by_name(a, bsdtar->create_format);
159         }
160         if (r != ARCHIVE_OK) {
161                 fprintf(stderr, "Can't use format %s: %s\n",
162                     bsdtar->create_format,
163                     archive_error_string(a));
164                 usage(bsdtar);
165         }
166
167         /*
168          * If user explicitly set the block size, then assume they
169          * want the last block padded as well.  Otherwise, use the
170          * default block size and accept archive_write_open_file()'s
171          * default padding decisions.
172          */
173         if (bsdtar->bytes_per_block != 0) {
174                 archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
175                 archive_write_set_bytes_in_last_block(a,
176                     bsdtar->bytes_per_block);
177         } else
178                 archive_write_set_bytes_per_block(a, DEFAULT_BYTES_PER_BLOCK);
179
180         if (bsdtar->compress_program) {
181                 archive_write_set_compression_program(a, bsdtar->compress_program);
182         } else {
183                 switch (bsdtar->create_compression) {
184                 case 0:
185                         archive_write_set_compression_none(a);
186                         break;
187 #ifdef HAVE_LIBBZ2
188                 case 'j': case 'y':
189                         archive_write_set_compression_bzip2(a);
190                         break;
191 #endif
192 #ifdef HAVE_LIBZ
193                 case 'z':
194                         archive_write_set_compression_gzip(a);
195                         break;
196 #endif
197                 case 'Z':
198                         archive_write_set_compression_compress(a);
199                         break;
200                 default:
201                         bsdtar_errc(bsdtar, 1, 0,
202                             "Unrecognized compression option -%c",
203                             bsdtar->create_compression);
204                 }
205         }
206
207         r = archive_write_open_file(a, bsdtar->filename);
208         if (r != ARCHIVE_OK)
209                 bsdtar_errc(bsdtar, 1, 0, archive_error_string(a));
210
211         write_archive(a, bsdtar);
212 }
213
214 /*
215  * Same as 'c', except we only support tar or empty formats in
216  * uncompressed files on disk.
217  */
218 void
219 tar_mode_r(struct bsdtar *bsdtar)
220 {
221         off_t   end_offset;
222         int     format;
223         struct archive *a;
224         struct archive_entry *entry;
225         int     r;
226
227         /* Sanity-test some arguments and the file. */
228         test_for_append(bsdtar);
229
230         format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
231
232         bsdtar->fd = open(bsdtar->filename, O_RDWR | O_CREAT, 0666);
233         if (bsdtar->fd < 0)
234                 bsdtar_errc(bsdtar, 1, errno,
235                     "Cannot open %s", bsdtar->filename);
236
237         a = archive_read_new();
238         archive_read_support_compression_all(a);
239         archive_read_support_format_tar(a);
240         archive_read_support_format_gnutar(a);
241         r = archive_read_open_fd(a, bsdtar->fd, 10240);
242         if (r != ARCHIVE_OK)
243                 bsdtar_errc(bsdtar, 1, archive_errno(a),
244                     "Can't read archive %s: %s", bsdtar->filename,
245                     archive_error_string(a));
246         while (0 == archive_read_next_header(a, &entry)) {
247                 if (archive_compression(a) != ARCHIVE_COMPRESSION_NONE) {
248                         archive_read_finish(a);
249                         close(bsdtar->fd);
250                         bsdtar_errc(bsdtar, 1, 0,
251                             "Cannot append to compressed archive.");
252                 }
253                 /* Keep going until we hit end-of-archive */
254                 format = archive_format(a);
255         }
256
257         end_offset = archive_read_header_position(a);
258         archive_read_finish(a);
259
260         /* Re-open archive for writing */
261         a = archive_write_new();
262         archive_write_set_compression_none(a);
263         /*
264          * Set the format to be used for writing.  To allow people to
265          * extend empty files, we need to allow them to specify the format,
266          * which opens the possibility that they will specify a format that
267          * doesn't match the existing format.  Hence, the following bit
268          * of arcane ugliness.
269          */
270
271         if (bsdtar->create_format != NULL) {
272                 /* If the user requested a format, use that, but ... */
273                 archive_write_set_format_by_name(a,
274                     bsdtar->create_format);
275                 /* ... complain if it's not compatible. */
276                 format &= ARCHIVE_FORMAT_BASE_MASK;
277                 if (format != (int)(archive_format(a) & ARCHIVE_FORMAT_BASE_MASK)
278                     && format != ARCHIVE_FORMAT_EMPTY) {
279                         bsdtar_errc(bsdtar, 1, 0,
280                             "Format %s is incompatible with the archive %s.",
281                             bsdtar->create_format, bsdtar->filename);
282                 }
283         } else {
284                 /*
285                  * Just preserve the current format, with a little care
286                  * for formats that libarchive can't write.
287                  */
288                 if (format == ARCHIVE_FORMAT_TAR_GNUTAR)
289                         /* TODO: When gtar supports pax, use pax restricted. */
290                         format = ARCHIVE_FORMAT_TAR_USTAR;
291                 if (format == ARCHIVE_FORMAT_EMPTY)
292                         format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
293                 archive_write_set_format(a, format);
294         }
295         lseek(bsdtar->fd, end_offset, SEEK_SET); /* XXX check return val XXX */
296         archive_write_open_fd(a, bsdtar->fd); /* XXX check return val XXX */
297
298         write_archive(a, bsdtar); /* XXX check return val XXX */
299
300         close(bsdtar->fd);
301         bsdtar->fd = -1;
302 }
303
304 void
305 tar_mode_u(struct bsdtar *bsdtar)
306 {
307         off_t                    end_offset;
308         struct archive          *a;
309         struct archive_entry    *entry;
310         int                      format;
311         struct archive_dir_entry        *p;
312         struct archive_dir       archive_dir;
313
314         bsdtar->archive_dir = &archive_dir;
315         memset(&archive_dir, 0, sizeof(archive_dir));
316
317         format = ARCHIVE_FORMAT_TAR_PAX_RESTRICTED;
318
319         /* Sanity-test some arguments and the file. */
320         test_for_append(bsdtar);
321
322         bsdtar->fd = open(bsdtar->filename, O_RDWR);
323         if (bsdtar->fd < 0)
324                 bsdtar_errc(bsdtar, 1, errno,
325                     "Cannot open %s", bsdtar->filename);
326
327         a = archive_read_new();
328         archive_read_support_compression_all(a);
329         archive_read_support_format_tar(a);
330         archive_read_support_format_gnutar(a);
331         if (archive_read_open_fd(a, bsdtar->fd,
332             bsdtar->bytes_per_block != 0 ? bsdtar->bytes_per_block :
333                 DEFAULT_BYTES_PER_BLOCK) != ARCHIVE_OK) {
334                 bsdtar_errc(bsdtar, 1, 0,
335                     "Can't open %s: %s", bsdtar->filename,
336                     archive_error_string(a));
337         }
338
339         /* Build a list of all entries and their recorded mod times. */
340         while (0 == archive_read_next_header(a, &entry)) {
341                 if (archive_compression(a) != ARCHIVE_COMPRESSION_NONE) {
342                         archive_read_finish(a);
343                         close(bsdtar->fd);
344                         bsdtar_errc(bsdtar, 1, 0,
345                             "Cannot append to compressed archive.");
346                 }
347                 add_dir_list(bsdtar, archive_entry_pathname(entry),
348                     archive_entry_mtime(entry),
349                     archive_entry_mtime_nsec(entry));
350                 /* Record the last format determination we see */
351                 format = archive_format(a);
352                 /* Keep going until we hit end-of-archive */
353         }
354
355         end_offset = archive_read_header_position(a);
356         archive_read_finish(a);
357
358         /* Re-open archive for writing. */
359         a = archive_write_new();
360         archive_write_set_compression_none(a);
361         /*
362          * Set format to same one auto-detected above, except that
363          * we don't write GNU tar format, so use ustar instead.
364          */
365         if (format == ARCHIVE_FORMAT_TAR_GNUTAR)
366                 format = ARCHIVE_FORMAT_TAR_USTAR;
367         archive_write_set_format(a, format);
368         if (bsdtar->bytes_per_block != 0) {
369                 archive_write_set_bytes_per_block(a, bsdtar->bytes_per_block);
370                 archive_write_set_bytes_in_last_block(a,
371                     bsdtar->bytes_per_block);
372         } else
373                 archive_write_set_bytes_per_block(a, DEFAULT_BYTES_PER_BLOCK);
374         lseek(bsdtar->fd, end_offset, SEEK_SET);
375         ftruncate(bsdtar->fd, end_offset);
376         archive_write_open_fd(a, bsdtar->fd);
377
378         write_archive(a, bsdtar);
379
380         close(bsdtar->fd);
381         bsdtar->fd = -1;
382
383         while (bsdtar->archive_dir->head != NULL) {
384                 p = bsdtar->archive_dir->head->next;
385                 free(bsdtar->archive_dir->head->name);
386                 free(bsdtar->archive_dir->head);
387                 bsdtar->archive_dir->head = p;
388         }
389         bsdtar->archive_dir->tail = NULL;
390 }
391
392
393 /*
394  * Write user-specified files/dirs to opened archive.
395  */
396 static void
397 write_archive(struct archive *a, struct bsdtar *bsdtar)
398 {
399         const char *arg;
400         struct archive_entry *entry, *sparse_entry;
401
402         /* We want to catch SIGINFO and SIGUSR1. */
403         siginfo_init(bsdtar);
404
405         /* Allocate a buffer for file data. */
406         if ((bsdtar->buff = malloc(FILEDATABUFLEN)) == NULL)
407                 bsdtar_errc(bsdtar, 1, 0, "cannot allocate memory");
408
409         if ((bsdtar->resolver = archive_entry_linkresolver_new()) == NULL)
410                 bsdtar_errc(bsdtar, 1, 0, "cannot create link resolver");
411         archive_entry_linkresolver_set_strategy(bsdtar->resolver,
412             archive_format(a));
413         if ((bsdtar->diskreader = archive_read_disk_new()) == NULL)
414                 bsdtar_errc(bsdtar, 1, 0, "Cannot create read_disk object");
415         archive_read_disk_set_standard_lookup(bsdtar->diskreader);
416
417         if (bsdtar->names_from_file != NULL)
418                 archive_names_from_file(bsdtar, a);
419
420         while (*bsdtar->argv) {
421                 arg = *bsdtar->argv;
422                 if (arg[0] == '-' && arg[1] == 'C') {
423                         arg += 2;
424                         if (*arg == '\0') {
425                                 bsdtar->argv++;
426                                 arg = *bsdtar->argv;
427                                 if (arg == NULL) {
428                                         bsdtar_warnc(bsdtar, 1, 0,
429                                             "Missing argument for -C");
430                                         bsdtar->return_value = 1;
431                                         goto cleanup;
432                                 }
433                         }
434                         set_chdir(bsdtar, arg);
435                 } else {
436                         if (*arg != '/' && (arg[0] != '@' || arg[1] != '/'))
437                                 do_chdir(bsdtar); /* Handle a deferred -C */
438                         if (*arg == '@') {
439                                 if (append_archive_filename(bsdtar, a,
440                                     arg + 1) != 0)
441                                         break;
442                         } else
443                                 write_hierarchy(bsdtar, a, arg);
444                 }
445                 bsdtar->argv++;
446         }
447
448         entry = NULL;
449         archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
450         while (entry != NULL) {
451                 write_entry_backend(bsdtar, a, entry);
452                 archive_entry_free(entry);
453                 entry = NULL;
454                 archive_entry_linkify(bsdtar->resolver, &entry, &sparse_entry);
455         }
456
457         if (archive_write_close(a)) {
458                 bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(a));
459                 bsdtar->return_value = 1;
460         }
461
462 cleanup:
463         /* Free file data buffer. */
464         free(bsdtar->buff);
465         archive_entry_linkresolver_free(bsdtar->resolver);
466         bsdtar->resolver = NULL;
467         archive_read_finish(bsdtar->diskreader);
468         bsdtar->diskreader = NULL;
469
470         if (bsdtar->option_totals) {
471                 fprintf(stderr, "Total bytes written: " BSDTAR_FILESIZE_PRINTF "\n",
472                     (BSDTAR_FILESIZE_TYPE)archive_position_compressed(a));
473         }
474
475         archive_write_finish(a);
476
477         /* Restore old SIGINFO + SIGUSR1 handlers. */
478         siginfo_done(bsdtar);
479 }
480
481 /*
482  * Archive names specified in file.
483  *
484  * Unless --null was specified, a line containing exactly "-C" will
485  * cause the next line to be a directory to pass to chdir().  If
486  * --null is specified, then a line "-C" is just another filename.
487  */
488 void
489 archive_names_from_file(struct bsdtar *bsdtar, struct archive *a)
490 {
491         bsdtar->archive = a;
492
493         bsdtar->next_line_is_dir = 0;
494         process_lines(bsdtar, bsdtar->names_from_file,
495             archive_names_from_file_helper);
496         if (bsdtar->next_line_is_dir)
497                 bsdtar_errc(bsdtar, 1, errno,
498                     "Unexpected end of filename list; "
499                     "directory expected after -C");
500 }
501
502 static int
503 archive_names_from_file_helper(struct bsdtar *bsdtar, const char *line)
504 {
505         if (bsdtar->next_line_is_dir) {
506                 set_chdir(bsdtar, line);
507                 bsdtar->next_line_is_dir = 0;
508         } else if (!bsdtar->option_null && strcmp(line, "-C") == 0)
509                 bsdtar->next_line_is_dir = 1;
510         else {
511                 if (*line != '/')
512                         do_chdir(bsdtar); /* Handle a deferred -C */
513                 write_hierarchy(bsdtar, bsdtar->archive, line);
514         }
515         return (0);
516 }
517
518 /*
519  * Copy from specified archive to current archive.  Returns non-zero
520  * for write errors (which force us to terminate the entire archiving
521  * operation).  If there are errors reading the input archive, we set
522  * bsdtar->return_value but return zero, so the overall archiving
523  * operation will complete and return non-zero.
524  */
525 static int
526 append_archive_filename(struct bsdtar *bsdtar, struct archive *a,
527     const char *filename)
528 {
529         struct archive *ina;
530         int rc;
531
532         if (strcmp(filename, "-") == 0)
533                 filename = NULL; /* Library uses NULL for stdio. */
534
535         ina = archive_read_new();
536         archive_read_support_format_all(ina);
537         archive_read_support_compression_all(ina);
538         if (archive_read_open_file(ina, filename, 10240)) {
539                 bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(ina));
540                 bsdtar->return_value = 1;
541                 return (0);
542         }
543
544         rc = append_archive(bsdtar, a, ina);
545
546         if (archive_errno(ina)) {
547                 bsdtar_warnc(bsdtar, 0, "Error reading archive %s: %s",
548                     filename, archive_error_string(ina));
549                 bsdtar->return_value = 1;
550         }
551         archive_read_finish(ina);
552
553         return (rc);
554 }
555
556 static int
557 append_archive(struct bsdtar *bsdtar, struct archive *a, struct archive *ina)
558 {
559         struct archive_entry *in_entry;
560         int e;
561
562         while (0 == archive_read_next_header(ina, &in_entry)) {
563                 if (!new_enough(bsdtar, archive_entry_pathname(in_entry),
564                         archive_entry_stat(in_entry)))
565                         continue;
566                 if (excluded(bsdtar, archive_entry_pathname(in_entry)))
567                         continue;
568                 if (bsdtar->option_interactive &&
569                     !yes("copy '%s'", archive_entry_pathname(in_entry)))
570                         continue;
571                 if (bsdtar->verbose)
572                         safe_fprintf(stderr, "a %s",
573                             archive_entry_pathname(in_entry));
574                 siginfo_setinfo(bsdtar, "copying",
575                     archive_entry_pathname(in_entry),
576                     archive_entry_size(in_entry));
577                 siginfo_printinfo(bsdtar, 0);
578
579                 e = archive_write_header(a, in_entry);
580                 if (e != ARCHIVE_OK) {
581                         if (!bsdtar->verbose)
582                                 bsdtar_warnc(bsdtar, 0, "%s: %s",
583                                     archive_entry_pathname(in_entry),
584                                     archive_error_string(a));
585                         else
586                                 fprintf(stderr, ": %s", archive_error_string(a));
587                 }
588                 if (e == ARCHIVE_FATAL)
589                         exit(1);
590
591                 if (e >= ARCHIVE_WARN) {
592                         if (archive_entry_size(in_entry) == 0)
593                                 archive_read_data_skip(ina);
594                         else if (copy_file_data(bsdtar, a, ina))
595                                 exit(1);
596                 }
597
598                 if (bsdtar->verbose)
599                         fprintf(stderr, "\n");
600         }
601
602         /* Note: If we got here, we saw no write errors, so return success. */
603         return (0);
604 }
605
606 /* Helper function to copy data between archives. */
607 static int
608 copy_file_data(struct bsdtar *bsdtar, struct archive *a, struct archive *ina)
609 {
610         ssize_t bytes_read;
611         ssize_t bytes_written;
612         off_t   progress = 0;
613
614         bytes_read = archive_read_data(ina, bsdtar->buff, FILEDATABUFLEN);
615         while (bytes_read > 0) {
616                 siginfo_printinfo(bsdtar, progress);
617
618                 bytes_written = archive_write_data(a, bsdtar->buff,
619                     bytes_read);
620                 if (bytes_written < bytes_read) {
621                         bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(a));
622                         return (-1);
623                 }
624                 progress += bytes_written;
625                 bytes_read = archive_read_data(ina, bsdtar->buff,
626                     FILEDATABUFLEN);
627         }
628
629         return (0);
630 }
631
632 /*
633  * Add the file or dir hierarchy named by 'path' to the archive
634  */
635 static void
636 write_hierarchy(struct bsdtar *bsdtar, struct archive *a, const char *path)
637 {
638         struct archive_entry *entry = NULL, *spare_entry = NULL;
639         struct tree *tree;
640         char symlink_mode = bsdtar->symlink_mode;
641         dev_t first_dev = 0;
642         int dev_recorded = 0;
643         int tree_ret;
644
645         tree = tree_open(path);
646
647         if (!tree) {
648                 bsdtar_warnc(bsdtar, errno, "%s: Cannot open", path);
649                 bsdtar->return_value = 1;
650                 return;
651         }
652
653         while ((tree_ret = tree_next(tree))) {
654                 int r;
655                 const char *name = tree_current_path(tree);
656                 const struct stat *st = NULL; /* info to use for this entry */
657                 const struct stat *lst = NULL; /* lstat() information */
658                 int descend;
659
660                 if (tree_ret == TREE_ERROR_FATAL)
661                         bsdtar_errc(bsdtar, 1, tree_errno(tree),
662                             "%s: Unable to continue traversing directory tree",
663                             name);
664                 if (tree_ret == TREE_ERROR_DIR) {
665                         bsdtar_warnc(bsdtar, errno,
666                             "%s: Couldn't visit directory", name);
667                         bsdtar->return_value = 1;
668                 }
669                 if (tree_ret != TREE_REGULAR)
670                         continue;
671
672                 /*
673                  * If this file/dir is excluded by a filename
674                  * pattern, skip it.
675                  */
676                 if (excluded(bsdtar, name))
677                         continue;
678
679                 /*
680                  * Get lstat() info from the tree library.
681                  */
682                 lst = tree_current_lstat(tree);
683                 if (lst == NULL) {
684                         /* Couldn't lstat(); must not exist. */
685                         bsdtar_warnc(bsdtar, errno, "%s: Cannot stat", name);
686                         /* Return error if files disappear during traverse. */
687                         bsdtar->return_value = 1;
688                         continue;
689                 }
690
691                 /*
692                  * Distinguish 'L'/'P'/'H' symlink following.
693                  */
694                 switch(symlink_mode) {
695                 case 'H':
696                         /* 'H': After the first item, rest like 'P'. */
697                         symlink_mode = 'P';
698                         /* 'H': First item (from command line) like 'L'. */
699                         /* FALLTHROUGH */
700                 case 'L':
701                         /* 'L': Do descend through a symlink to dir. */
702                         descend = tree_current_is_dir(tree);
703                         /* 'L': Follow symlinks to files. */
704                         archive_read_disk_set_symlink_logical(bsdtar->diskreader);
705                         /* 'L': Archive symlinks as targets, if we can. */
706                         st = tree_current_stat(tree);
707                         if (st != NULL)
708                                 break;
709                         /* If stat fails, we have a broken symlink;
710                          * in that case, don't follow the link. */
711                         /* FALLTHROUGH */
712                 default:
713                         /* 'P': Don't descend through a symlink to dir. */
714                         descend = tree_current_is_physical_dir(tree);
715                         /* 'P': Don't follow symlinks to files. */
716                         archive_read_disk_set_symlink_physical(bsdtar->diskreader);
717                         /* 'P': Archive symlinks as symlinks. */
718                         st = lst;
719                         break;
720                 }
721
722                 /*
723                  * If user has asked us not to cross mount points,
724                  * then don't descend into into a dir on a different
725                  * device.
726                  */
727                 if (!dev_recorded) {
728                         first_dev = lst->st_dev;
729                         dev_recorded = 1;
730                 }
731                 if (bsdtar->option_dont_traverse_mounts) {
732                         if (lst->st_dev != first_dev)
733                                 descend = 0;
734                 }
735
736                 /*
737                  * In -u mode, check that the file is newer than what's
738                  * already in the archive; in all modes, obey --newerXXX flags.
739                  */
740                 if (!new_enough(bsdtar, name, st))
741                         continue;
742
743                 archive_entry_free(entry);
744                 entry = archive_entry_new();
745
746                 archive_entry_set_pathname(entry, name);
747                 archive_entry_copy_sourcepath(entry,
748                     tree_current_access_path(tree));
749
750                 /* Populate the archive_entry with metadata from the disk. */
751                 /* XXX TODO: Arrange to open a regular file before
752                  * calling this so we can pass in an fd and shorten
753                  * the race to query metadata.  The linkify dance
754                  * makes this more complex than it might sound. */
755                 r = archive_read_disk_entry_from_file(bsdtar->diskreader,
756                     entry, -1, st);
757                 if (r != ARCHIVE_OK)
758                         bsdtar_warnc(bsdtar, archive_errno(bsdtar->diskreader),
759                             archive_error_string(bsdtar->diskreader));
760                 if (r < ARCHIVE_WARN)
761                         continue;
762
763                 /* XXX TODO: Just use flag data from entry; avoid the
764                  * duplicate check here. */
765
766                 /*
767                  * If this file/dir is flagged "nodump" and we're
768                  * honoring such flags, skip this file/dir.
769                  */
770 #ifdef HAVE_STRUCT_STAT_ST_FLAGS
771                 /* BSD systems store flags in struct stat */
772                 if (bsdtar->option_honor_nodump &&
773                     (lst->st_flags & UF_NODUMP))
774                         continue;
775 #endif
776
777 #if defined(EXT2_IOC_GETFLAGS) && defined(EXT2_NODUMP_FL)
778                 /* Linux uses ioctl to read flags. */
779                 if (bsdtar->option_honor_nodump) {
780                         int fd = open(name, O_RDONLY | O_NONBLOCK);
781                         if (fd >= 0) {
782                                 unsigned long fflags;
783                                 int r = ioctl(fd, EXT2_IOC_GETFLAGS, &fflags);
784                                 close(fd);
785                                 if (r >= 0 && (fflags & EXT2_NODUMP_FL))
786                                         continue;
787                         }
788                 }
789 #endif
790
791                 /*
792                  * If the user vetoes this file/directory, skip it.
793                  * We want this to be fairly late; if some other
794                  * check would veto this file, we shouldn't bother
795                  * the user with it.
796                  */
797                 if (bsdtar->option_interactive &&
798                     !yes("add '%s'", name))
799                         continue;
800
801                 /* Note: if user vetoes, we won't descend. */
802                 if (descend && !bsdtar->option_no_subdirs)
803                         tree_descend(tree);
804
805                 /*
806                  * Rewrite the pathname to be archived.  If rewrite
807                  * fails, skip the entry.
808                  */
809                 if (edit_pathname(bsdtar, entry))
810                         continue;
811
812                 /* Display entry as we process it.
813                  * This format is required by SUSv2. */
814                 if (bsdtar->verbose)
815                         safe_fprintf(stderr, "a %s",
816                             archive_entry_pathname(entry));
817
818                 /* Non-regular files get archived with zero size. */
819                 if (!S_ISREG(st->st_mode))
820                         archive_entry_set_size(entry, 0);
821
822                 /* Record what we're doing, for SIGINFO / SIGUSR1. */
823                 siginfo_setinfo(bsdtar, "adding",
824                     archive_entry_pathname(entry), archive_entry_size(entry));
825                 archive_entry_linkify(bsdtar->resolver, &entry, &spare_entry);
826
827                 /* Handle SIGINFO / SIGUSR1 request if one was made. */
828                 siginfo_printinfo(bsdtar, 0);
829
830                 while (entry != NULL) {
831                         write_entry_backend(bsdtar, a, entry);
832                         archive_entry_free(entry);
833                         entry = spare_entry;
834                         spare_entry = NULL;
835                 }
836
837                 if (bsdtar->verbose)
838                         fprintf(stderr, "\n");
839         }
840         archive_entry_free(entry);
841         tree_close(tree);
842 }
843
844 /*
845  * Backend for write_entry.
846  */
847 static void
848 write_entry_backend(struct bsdtar *bsdtar, struct archive *a,
849     struct archive_entry *entry)
850 {
851         int fd = -1;
852         int e;
853
854         if (archive_entry_size(entry) > 0) {
855                 const char *pathname = archive_entry_sourcepath(entry);
856                 fd = open(pathname, O_RDONLY);
857                 if (fd == -1) {
858                         if (!bsdtar->verbose)
859                                 bsdtar_warnc(bsdtar, errno,
860                                     "%s: could not open file", pathname);
861                         else
862                                 fprintf(stderr, ": %s", strerror(errno));
863                         return;
864                 }
865         }
866
867         e = archive_write_header(a, entry);
868         if (e != ARCHIVE_OK) {
869                 if (!bsdtar->verbose)
870                         bsdtar_warnc(bsdtar, 0, "%s: %s",
871                             archive_entry_pathname(entry),
872                             archive_error_string(a));
873                 else
874                         fprintf(stderr, ": %s", archive_error_string(a));
875         }
876
877         if (e == ARCHIVE_FATAL)
878                 exit(1);
879
880         /*
881          * If we opened a file earlier, write it out now.  Note that
882          * the format handler might have reset the size field to zero
883          * to inform us that the archive body won't get stored.  In
884          * that case, just skip the write.
885          */
886         if (e >= ARCHIVE_WARN && fd >= 0 && archive_entry_size(entry) > 0) {
887                 if (write_file_data(bsdtar, a, entry, fd))
888                         exit(1);
889         }
890
891         /*
892          * If we opened a file, close it now even if there was an error
893          * which made us decide not to write the archive body.
894          */
895         if (fd >= 0)
896                 close(fd);
897 }
898
899
900 /* Helper function to copy file to archive. */
901 static int
902 write_file_data(struct bsdtar *bsdtar, struct archive *a,
903     struct archive_entry *entry, int fd)
904 {
905         ssize_t bytes_read;
906         ssize_t bytes_written;
907         off_t   progress = 0;
908
909         bytes_read = read(fd, bsdtar->buff, FILEDATABUFLEN);
910         while (bytes_read > 0) {
911                 siginfo_printinfo(bsdtar, progress);
912
913                 bytes_written = archive_write_data(a, bsdtar->buff,
914                     bytes_read);
915                 if (bytes_written < 0) {
916                         /* Write failed; this is bad */
917                         bsdtar_warnc(bsdtar, 0, "%s", archive_error_string(a));
918                         return (-1);
919                 }
920                 if (bytes_written < bytes_read) {
921                         /* Write was truncated; warn but continue. */
922                         bsdtar_warnc(bsdtar, 0,
923                             "%s: Truncated write; file may have grown while being archived.",
924                             archive_entry_pathname(entry));
925                         return (0);
926                 }
927                 progress += bytes_written;
928                 bytes_read = read(fd, bsdtar->buff, FILEDATABUFLEN);
929         }
930         return 0;
931 }
932
933 /*
934  * Test if the specified file is new enough to include in the archive.
935  */
936 int
937 new_enough(struct bsdtar *bsdtar, const char *path, const struct stat *st)
938 {
939         struct archive_dir_entry *p;
940
941         /*
942          * If this file/dir is excluded by a time comparison, skip it.
943          */
944         if (bsdtar->newer_ctime_sec > 0) {
945                 if (st->st_ctime < bsdtar->newer_ctime_sec)
946                         return (0); /* Too old, skip it. */
947                 if (st->st_ctime == bsdtar->newer_ctime_sec
948                     && ARCHIVE_STAT_CTIME_NANOS(st)
949                     <= bsdtar->newer_ctime_nsec)
950                         return (0); /* Too old, skip it. */
951         }
952         if (bsdtar->newer_mtime_sec > 0) {
953                 if (st->st_mtime < bsdtar->newer_mtime_sec)
954                         return (0); /* Too old, skip it. */
955                 if (st->st_mtime == bsdtar->newer_mtime_sec
956                     && ARCHIVE_STAT_MTIME_NANOS(st)
957                     <= bsdtar->newer_mtime_nsec)
958                         return (0); /* Too old, skip it. */
959         }
960
961         /*
962          * In -u mode, we only write an entry if it's newer than
963          * what was already in the archive.
964          */
965         if (bsdtar->archive_dir != NULL &&
966             bsdtar->archive_dir->head != NULL) {
967                 for (p = bsdtar->archive_dir->head; p != NULL; p = p->next) {
968                         if (pathcmp(path, p->name)==0)
969                                 return (p->mtime_sec < st->st_mtime ||
970                                     (p->mtime_sec == st->st_mtime &&
971                                         p->mtime_nsec
972                                         < ARCHIVE_STAT_MTIME_NANOS(st)));
973                 }
974         }
975
976         /* If the file wasn't rejected, include it. */
977         return (1);
978 }
979
980 /*
981  * Add an entry to the dir list for 'u' mode.
982  *
983  * XXX TODO: Make this fast.
984  */
985 static void
986 add_dir_list(struct bsdtar *bsdtar, const char *path,
987     time_t mtime_sec, int mtime_nsec)
988 {
989         struct archive_dir_entry        *p;
990
991         /*
992          * Search entire list to see if this file has appeared before.
993          * If it has, override the timestamp data.
994          */
995         p = bsdtar->archive_dir->head;
996         while (p != NULL) {
997                 if (strcmp(path, p->name)==0) {
998                         p->mtime_sec = mtime_sec;
999                         p->mtime_nsec = mtime_nsec;
1000                         return;
1001                 }
1002                 p = p->next;
1003         }
1004
1005         p = malloc(sizeof(*p));
1006         if (p == NULL)
1007                 bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read archive directory");
1008
1009         p->name = strdup(path);
1010         if (p->name == NULL)
1011                 bsdtar_errc(bsdtar, 1, ENOMEM, "Can't read archive directory");
1012         p->mtime_sec = mtime_sec;
1013         p->mtime_nsec = mtime_nsec;
1014         p->next = NULL;
1015         if (bsdtar->archive_dir->tail == NULL) {
1016                 bsdtar->archive_dir->head = bsdtar->archive_dir->tail = p;
1017         } else {
1018                 bsdtar->archive_dir->tail->next = p;
1019                 bsdtar->archive_dir->tail = p;
1020         }
1021 }
1022
1023 void
1024 test_for_append(struct bsdtar *bsdtar)
1025 {
1026         struct stat s;
1027
1028         if (*bsdtar->argv == NULL && bsdtar->names_from_file == NULL)
1029                 bsdtar_errc(bsdtar, 1, 0, "no files or directories specified");
1030         if (bsdtar->filename == NULL)
1031                 bsdtar_errc(bsdtar, 1, 0, "Cannot append to stdout.");
1032
1033         if (bsdtar->create_compression != 0)
1034                 bsdtar_errc(bsdtar, 1, 0,
1035                     "Cannot append to %s with compression", bsdtar->filename);
1036
1037         if (stat(bsdtar->filename, &s) != 0)
1038                 return;
1039
1040         if (!S_ISREG(s.st_mode) && !S_ISBLK(s.st_mode))
1041                 bsdtar_errc(bsdtar, 1, 0,
1042                     "Cannot append to %s: not a regular file.",
1043                     bsdtar->filename);
1044 }