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