Merge branch 'vendor/DHCPCD'
[dragonfly.git] / contrib / libarchive / libarchive / archive_read_disk_posix.c
1 /*-
2  * Copyright (c) 2003-2009 Tim Kientzle
3  * Copyright (c) 2010-2012 Michihiro NAKAJIMA
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer
11  *    in this position and unchanged.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  *
16  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
17  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
18  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
19  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
20  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
21  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
22  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
23  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
24  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
25  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
26  */
27
28 /* This is the tree-walking code for POSIX systems. */
29 #if !defined(_WIN32) || defined(__CYGWIN__)
30
31 #include "archive_platform.h"
32 __FBSDID("$FreeBSD$");
33
34 #ifdef HAVE_SYS_PARAM_H
35 #include <sys/param.h>
36 #endif
37 #ifdef HAVE_SYS_MOUNT_H
38 #include <sys/mount.h>
39 #endif
40 #ifdef HAVE_SYS_STAT_H
41 #include <sys/stat.h>
42 #endif
43 #ifdef HAVE_SYS_STATFS_H
44 #include <sys/statfs.h>
45 #endif
46 #ifdef HAVE_SYS_STATVFS_H
47 #include <sys/statvfs.h>
48 #endif
49 #ifdef HAVE_SYS_TIME_H
50 #include <sys/time.h>
51 #endif
52 #ifdef HAVE_LINUX_MAGIC_H
53 #include <linux/magic.h>
54 #endif
55 #ifdef HAVE_LINUX_FS_H
56 #include <linux/fs.h>
57 #endif
58 /*
59  * Some Linux distributions have both linux/ext2_fs.h and ext2fs/ext2_fs.h.
60  * As the include guards don't agree, the order of include is important.
61  */
62 #ifdef HAVE_LINUX_EXT2_FS_H
63 #include <linux/ext2_fs.h>      /* for Linux file flags */
64 #endif
65 #if defined(HAVE_EXT2FS_EXT2_FS_H) && !defined(__CYGWIN__)
66 #include <ext2fs/ext2_fs.h>     /* Linux file flags, broken on Cygwin */
67 #endif
68 #ifdef HAVE_DIRECT_H
69 #include <direct.h>
70 #endif
71 #ifdef HAVE_DIRENT_H
72 #include <dirent.h>
73 #endif
74 #ifdef HAVE_ERRNO_H
75 #include <errno.h>
76 #endif
77 #ifdef HAVE_FCNTL_H
78 #include <fcntl.h>
79 #endif
80 #ifdef HAVE_LIMITS_H
81 #include <limits.h>
82 #endif
83 #ifdef HAVE_STDLIB_H
84 #include <stdlib.h>
85 #endif
86 #ifdef HAVE_STRING_H
87 #include <string.h>
88 #endif
89 #ifdef HAVE_UNISTD_H
90 #include <unistd.h>
91 #endif
92 #ifdef HAVE_SYS_IOCTL_H
93 #include <sys/ioctl.h>
94 #endif
95
96 #include "archive.h"
97 #include "archive_string.h"
98 #include "archive_entry.h"
99 #include "archive_private.h"
100 #include "archive_read_disk_private.h"
101
102 #ifndef HAVE_FCHDIR
103 #error fchdir function required.
104 #endif
105 #ifndef O_BINARY
106 #define O_BINARY        0
107 #endif
108 #ifndef O_CLOEXEC
109 #define O_CLOEXEC       0
110 #endif
111
112 /*-
113  * This is a new directory-walking system that addresses a number
114  * of problems I've had with fts(3).  In particular, it has no
115  * pathname-length limits (other than the size of 'int'), handles
116  * deep logical traversals, uses considerably less memory, and has
117  * an opaque interface (easier to modify in the future).
118  *
119  * Internally, it keeps a single list of "tree_entry" items that
120  * represent filesystem objects that require further attention.
121  * Non-directories are not kept in memory: they are pulled from
122  * readdir(), returned to the client, then freed as soon as possible.
123  * Any directory entry to be traversed gets pushed onto the stack.
124  *
125  * There is surprisingly little information that needs to be kept for
126  * each item on the stack.  Just the name, depth (represented here as the
127  * string length of the parent directory's pathname), and some markers
128  * indicating how to get back to the parent (via chdir("..") for a
129  * regular dir or via fchdir(2) for a symlink).
130  */
131 /*
132  * TODO:
133  *    1) Loop checking.
134  *    3) Arbitrary logical traversals by closing/reopening intermediate fds.
135  */
136
137 struct restore_time {
138         const char              *name;
139         time_t                   mtime;
140         long                     mtime_nsec;
141         time_t                   atime;
142         long                     atime_nsec;
143         mode_t                   filetype;
144         int                      noatime;
145 };
146
147 struct tree_entry {
148         int                      depth;
149         struct tree_entry       *next;
150         struct tree_entry       *parent;
151         struct archive_string    name;
152         size_t                   dirname_length;
153         int64_t                  dev;
154         int64_t                  ino;
155         int                      flags;
156         int                      filesystem_id;
157         /* How to return back to the parent of a symlink. */
158         int                      symlink_parent_fd;
159         /* How to restore time of a directory. */
160         struct restore_time      restore_time;
161 };
162
163 struct filesystem {
164         int64_t         dev;
165         int             synthetic;
166         int             remote;
167         int             noatime;
168 #if defined(USE_READDIR_R)
169         size_t          name_max;
170 #endif
171         long            incr_xfer_size;
172         long            max_xfer_size;
173         long            min_xfer_size;
174         long            xfer_align;
175
176         /*
177          * Buffer used for reading file contents.
178          */
179         /* Exactly allocated memory pointer. */
180         unsigned char   *allocation_ptr;
181         /* Pointer adjusted to the filesystem alignment . */
182         unsigned char   *buff;
183         size_t           buff_size;
184 };
185
186 /* Definitions for tree_entry.flags bitmap. */
187 #define isDir           1  /* This entry is a regular directory. */
188 #define isDirLink       2  /* This entry is a symbolic link to a directory. */
189 #define needsFirstVisit 4  /* This is an initial entry. */
190 #define needsDescent    8  /* This entry needs to be previsited. */
191 #define needsOpen       16 /* This is a directory that needs to be opened. */
192 #define needsAscent     32 /* This entry needs to be postvisited. */
193
194 /*
195  * Local data for this package.
196  */
197 struct tree {
198         struct tree_entry       *stack;
199         struct tree_entry       *current;
200         DIR                     *d;
201 #define INVALID_DIR_HANDLE NULL
202         struct dirent           *de;
203 #if defined(USE_READDIR_R)
204         struct dirent           *dirent;
205         size_t                   dirent_allocated;
206 #endif
207         int                      flags;
208         int                      visit_type;
209         /* Error code from last failed operation. */
210         int                      tree_errno;
211
212         /* Dynamically-sized buffer for holding path */
213         struct archive_string    path;
214
215         /* Last path element */
216         const char              *basename;
217         /* Leading dir length */
218         size_t                   dirname_length;
219
220         int                      depth;
221         int                      openCount;
222         int                      maxOpenCount;
223         int                      initial_dir_fd;
224         int                      working_dir_fd;
225
226         struct stat              lst;
227         struct stat              st;
228         int                      descend;
229         int                      nlink;
230         /* How to restore time of a file. */
231         struct restore_time      restore_time;
232
233         struct entry_sparse {
234                 int64_t          length;
235                 int64_t          offset;
236         }                       *sparse_list, *current_sparse;
237         int                      sparse_count;
238         int                      sparse_list_size;
239
240         char                     initial_symlink_mode;
241         char                     symlink_mode;
242         struct filesystem       *current_filesystem;
243         struct filesystem       *filesystem_table;
244         int                      initial_filesystem_id;
245         int                      current_filesystem_id;
246         int                      max_filesystem_id;
247         int                      allocated_filesystem;
248
249         int                      entry_fd;
250         int                      entry_eof;
251         int64_t                  entry_remaining_bytes;
252         int64_t                  entry_total;
253         unsigned char           *entry_buff;
254         size_t                   entry_buff_size;
255 };
256
257 /* Definitions for tree.flags bitmap. */
258 #define hasStat         16 /* The st entry is valid. */
259 #define hasLstat        32 /* The lst entry is valid. */
260 #define onWorkingDir    64 /* We are on the working dir where we are
261                             * reading directory entry at this time. */
262 #define needsRestoreTimes 128
263 #define onInitialDir    256 /* We are on the initial dir. */
264
265 static int
266 tree_dir_next_posix(struct tree *t);
267
268 #ifdef HAVE_DIRENT_D_NAMLEN
269 /* BSD extension; avoids need for a strlen() call. */
270 #define D_NAMELEN(dp)   (dp)->d_namlen
271 #else
272 #define D_NAMELEN(dp)   (strlen((dp)->d_name))
273 #endif
274
275 /* Initiate/terminate a tree traversal. */
276 static struct tree *tree_open(const char *, int, int);
277 static struct tree *tree_reopen(struct tree *, const char *, int);
278 static void tree_close(struct tree *);
279 static void tree_free(struct tree *);
280 static void tree_push(struct tree *, const char *, int, int64_t, int64_t,
281                 struct restore_time *);
282 static int tree_enter_initial_dir(struct tree *);
283 static int tree_enter_working_dir(struct tree *);
284 static int tree_current_dir_fd(struct tree *);
285
286 /*
287  * tree_next() returns Zero if there is no next entry, non-zero if
288  * there is.  Note that directories are visited three times.
289  * Directories are always visited first as part of enumerating their
290  * parent; that is a "regular" visit.  If tree_descend() is invoked at
291  * that time, the directory is added to a work list and will
292  * subsequently be visited two more times: once just after descending
293  * into the directory ("postdescent") and again just after ascending
294  * back to the parent ("postascent").
295  *
296  * TREE_ERROR_DIR is returned if the descent failed (because the
297  * directory couldn't be opened, for instance).  This is returned
298  * instead of TREE_POSTDESCENT/TREE_POSTASCENT.  TREE_ERROR_DIR is not a
299  * fatal error, but it does imply that the relevant subtree won't be
300  * visited.  TREE_ERROR_FATAL is returned for an error that left the
301  * traversal completely hosed.  Right now, this is only returned for
302  * chdir() failures during ascent.
303  */
304 #define TREE_REGULAR            1
305 #define TREE_POSTDESCENT        2
306 #define TREE_POSTASCENT         3
307 #define TREE_ERROR_DIR          -1
308 #define TREE_ERROR_FATAL        -2
309
310 static int tree_next(struct tree *);
311
312 /*
313  * Return information about the current entry.
314  */
315
316 /*
317  * The current full pathname, length of the full pathname, and a name
318  * that can be used to access the file.  Because tree does use chdir
319  * extensively, the access path is almost never the same as the full
320  * current path.
321  *
322  * TODO: On platforms that support it, use openat()-style operations
323  * to eliminate the chdir() operations entirely while still supporting
324  * arbitrarily deep traversals.  This makes access_path troublesome to
325  * support, of course, which means we'll need a rich enough interface
326  * that clients can function without it.  (In particular, we'll need
327  * tree_current_open() that returns an open file descriptor.)
328  *
329  */
330 static const char *tree_current_path(struct tree *);
331 static const char *tree_current_access_path(struct tree *);
332
333 /*
334  * Request the lstat() or stat() data for the current path.  Since the
335  * tree package needs to do some of this anyway, and caches the
336  * results, you should take advantage of it here if you need it rather
337  * than make a redundant stat() or lstat() call of your own.
338  */
339 static const struct stat *tree_current_stat(struct tree *);
340 static const struct stat *tree_current_lstat(struct tree *);
341 static int      tree_current_is_symblic_link_target(struct tree *);
342
343 /* The following functions use tricks to avoid a certain number of
344  * stat()/lstat() calls. */
345 /* "is_physical_dir" is equivalent to S_ISDIR(tree_current_lstat()->st_mode) */
346 static int tree_current_is_physical_dir(struct tree *);
347 /* "is_dir" is equivalent to S_ISDIR(tree_current_stat()->st_mode) */
348 static int tree_current_is_dir(struct tree *);
349 static int update_current_filesystem(struct archive_read_disk *a,
350                     int64_t dev);
351 static int setup_current_filesystem(struct archive_read_disk *);
352 static int tree_target_is_same_as_parent(struct tree *, const struct stat *);
353
354 static int      _archive_read_disk_open(struct archive *, const char *);
355 static int      _archive_read_free(struct archive *);
356 static int      _archive_read_close(struct archive *);
357 static int      _archive_read_data_block(struct archive *,
358                     const void **, size_t *, int64_t *);
359 static int      _archive_read_next_header(struct archive *,
360                     struct archive_entry **);
361 static int      _archive_read_next_header2(struct archive *,
362                     struct archive_entry *);
363 static const char *trivial_lookup_gname(void *, int64_t gid);
364 static const char *trivial_lookup_uname(void *, int64_t uid);
365 static int      setup_sparse(struct archive_read_disk *, struct archive_entry *);
366 static int      close_and_restore_time(int fd, struct tree *,
367                     struct restore_time *);
368 static int      open_on_current_dir(struct tree *, const char *, int);
369 static int      tree_dup(int);
370
371
372 static struct archive_vtable *
373 archive_read_disk_vtable(void)
374 {
375         static struct archive_vtable av;
376         static int inited = 0;
377
378         if (!inited) {
379                 av.archive_free = _archive_read_free;
380                 av.archive_close = _archive_read_close;
381                 av.archive_read_data_block = _archive_read_data_block;
382                 av.archive_read_next_header = _archive_read_next_header;
383                 av.archive_read_next_header2 = _archive_read_next_header2;
384                 inited = 1;
385         }
386         return (&av);
387 }
388
389 const char *
390 archive_read_disk_gname(struct archive *_a, la_int64_t gid)
391 {
392         struct archive_read_disk *a = (struct archive_read_disk *)_a;
393         if (ARCHIVE_OK != __archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
394                 ARCHIVE_STATE_ANY, "archive_read_disk_gname"))
395                 return (NULL);
396         if (a->lookup_gname == NULL)
397                 return (NULL);
398         return ((*a->lookup_gname)(a->lookup_gname_data, gid));
399 }
400
401 const char *
402 archive_read_disk_uname(struct archive *_a, la_int64_t uid)
403 {
404         struct archive_read_disk *a = (struct archive_read_disk *)_a;
405         if (ARCHIVE_OK != __archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
406                 ARCHIVE_STATE_ANY, "archive_read_disk_uname"))
407                 return (NULL);
408         if (a->lookup_uname == NULL)
409                 return (NULL);
410         return ((*a->lookup_uname)(a->lookup_uname_data, uid));
411 }
412
413 int
414 archive_read_disk_set_gname_lookup(struct archive *_a,
415     void *private_data,
416     const char * (*lookup_gname)(void *private, la_int64_t gid),
417     void (*cleanup_gname)(void *private))
418 {
419         struct archive_read_disk *a = (struct archive_read_disk *)_a;
420         archive_check_magic(&a->archive, ARCHIVE_READ_DISK_MAGIC,
421             ARCHIVE_STATE_ANY, "archive_read_disk_set_gname_lookup");
422
423         if (a->cleanup_gname != NULL && a->lookup_gname_data != NULL)
424                 (a->cleanup_gname)(a->lookup_gname_data);
425
426         a->lookup_gname = lookup_gname;
427         a->cleanup_gname = cleanup_gname;
428         a->lookup_gname_data = private_data;
429         return (ARCHIVE_OK);
430 }
431
432 int
433 archive_read_disk_set_uname_lookup(struct archive *_a,
434     void *private_data,
435     const char * (*lookup_uname)(void *private, la_int64_t uid),
436     void (*cleanup_uname)(void *private))
437 {
438         struct archive_read_disk *a = (struct archive_read_disk *)_a;
439         archive_check_magic(&a->archive, ARCHIVE_READ_DISK_MAGIC,
440             ARCHIVE_STATE_ANY, "archive_read_disk_set_uname_lookup");
441
442         if (a->cleanup_uname != NULL && a->lookup_uname_data != NULL)
443                 (a->cleanup_uname)(a->lookup_uname_data);
444
445         a->lookup_uname = lookup_uname;
446         a->cleanup_uname = cleanup_uname;
447         a->lookup_uname_data = private_data;
448         return (ARCHIVE_OK);
449 }
450
451 /*
452  * Create a new archive_read_disk object and initialize it with global state.
453  */
454 struct archive *
455 archive_read_disk_new(void)
456 {
457         struct archive_read_disk *a;
458
459         a = (struct archive_read_disk *)calloc(1, sizeof(*a));
460         if (a == NULL)
461                 return (NULL);
462         a->archive.magic = ARCHIVE_READ_DISK_MAGIC;
463         a->archive.state = ARCHIVE_STATE_NEW;
464         a->archive.vtable = archive_read_disk_vtable();
465         a->entry = archive_entry_new2(&a->archive);
466         a->lookup_uname = trivial_lookup_uname;
467         a->lookup_gname = trivial_lookup_gname;
468         a->flags = ARCHIVE_READDISK_MAC_COPYFILE;
469         a->open_on_current_dir = open_on_current_dir;
470         a->tree_current_dir_fd = tree_current_dir_fd;
471         a->tree_enter_working_dir = tree_enter_working_dir;
472         return (&a->archive);
473 }
474
475 static int
476 _archive_read_free(struct archive *_a)
477 {
478         struct archive_read_disk *a = (struct archive_read_disk *)_a;
479         int r;
480
481         if (_a == NULL)
482                 return (ARCHIVE_OK);
483         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
484             ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_free");
485
486         if (a->archive.state != ARCHIVE_STATE_CLOSED)
487                 r = _archive_read_close(&a->archive);
488         else
489                 r = ARCHIVE_OK;
490
491         tree_free(a->tree);
492         if (a->cleanup_gname != NULL && a->lookup_gname_data != NULL)
493                 (a->cleanup_gname)(a->lookup_gname_data);
494         if (a->cleanup_uname != NULL && a->lookup_uname_data != NULL)
495                 (a->cleanup_uname)(a->lookup_uname_data);
496         archive_string_free(&a->archive.error_string);
497         archive_entry_free(a->entry);
498         a->archive.magic = 0;
499         __archive_clean(&a->archive);
500         free(a);
501         return (r);
502 }
503
504 static int
505 _archive_read_close(struct archive *_a)
506 {
507         struct archive_read_disk *a = (struct archive_read_disk *)_a;
508
509         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
510             ARCHIVE_STATE_ANY | ARCHIVE_STATE_FATAL, "archive_read_close");
511
512         if (a->archive.state != ARCHIVE_STATE_FATAL)
513                 a->archive.state = ARCHIVE_STATE_CLOSED;
514
515         tree_close(a->tree);
516
517         return (ARCHIVE_OK);
518 }
519
520 static void
521 setup_symlink_mode(struct archive_read_disk *a, char symlink_mode,
522     int follow_symlinks)
523 {
524         a->symlink_mode = symlink_mode;
525         a->follow_symlinks = follow_symlinks;
526         if (a->tree != NULL) {
527                 a->tree->initial_symlink_mode = a->symlink_mode;
528                 a->tree->symlink_mode = a->symlink_mode;
529         }
530 }
531
532 int
533 archive_read_disk_set_symlink_logical(struct archive *_a)
534 {
535         struct archive_read_disk *a = (struct archive_read_disk *)_a;
536         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
537             ARCHIVE_STATE_ANY, "archive_read_disk_set_symlink_logical");
538         setup_symlink_mode(a, 'L', 1);
539         return (ARCHIVE_OK);
540 }
541
542 int
543 archive_read_disk_set_symlink_physical(struct archive *_a)
544 {
545         struct archive_read_disk *a = (struct archive_read_disk *)_a;
546         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
547             ARCHIVE_STATE_ANY, "archive_read_disk_set_symlink_physical");
548         setup_symlink_mode(a, 'P', 0);
549         return (ARCHIVE_OK);
550 }
551
552 int
553 archive_read_disk_set_symlink_hybrid(struct archive *_a)
554 {
555         struct archive_read_disk *a = (struct archive_read_disk *)_a;
556         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
557             ARCHIVE_STATE_ANY, "archive_read_disk_set_symlink_hybrid");
558         setup_symlink_mode(a, 'H', 1);/* Follow symlinks initially. */
559         return (ARCHIVE_OK);
560 }
561
562 int
563 archive_read_disk_set_atime_restored(struct archive *_a)
564 {
565         struct archive_read_disk *a = (struct archive_read_disk *)_a;
566         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
567             ARCHIVE_STATE_ANY, "archive_read_disk_restore_atime");
568 #ifdef HAVE_UTIMES
569         a->flags |= ARCHIVE_READDISK_RESTORE_ATIME;
570         if (a->tree != NULL)
571                 a->tree->flags |= needsRestoreTimes;
572         return (ARCHIVE_OK);
573 #else
574         /* Display warning and unset flag */
575         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
576             "Cannot restore access time on this system");
577         a->flags &= ~ARCHIVE_READDISK_RESTORE_ATIME;
578         return (ARCHIVE_WARN);
579 #endif
580 }
581
582 int
583 archive_read_disk_set_behavior(struct archive *_a, int flags)
584 {
585         struct archive_read_disk *a = (struct archive_read_disk *)_a;
586         int r = ARCHIVE_OK;
587
588         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
589             ARCHIVE_STATE_ANY, "archive_read_disk_honor_nodump");
590
591         a->flags = flags;
592
593         if (flags & ARCHIVE_READDISK_RESTORE_ATIME)
594                 r = archive_read_disk_set_atime_restored(_a);
595         else {
596                 if (a->tree != NULL)
597                         a->tree->flags &= ~needsRestoreTimes;
598         }
599         return (r);
600 }
601
602 /*
603  * Trivial implementations of gname/uname lookup functions.
604  * These are normally overridden by the client, but these stub
605  * versions ensure that we always have something that works.
606  */
607 static const char *
608 trivial_lookup_gname(void *private_data, int64_t gid)
609 {
610         (void)private_data; /* UNUSED */
611         (void)gid; /* UNUSED */
612         return (NULL);
613 }
614
615 static const char *
616 trivial_lookup_uname(void *private_data, int64_t uid)
617 {
618         (void)private_data; /* UNUSED */
619         (void)uid; /* UNUSED */
620         return (NULL);
621 }
622
623 /*
624  * Allocate memory for the reading buffer adjusted to the filesystem
625  * alignment.
626  */
627 static int
628 setup_suitable_read_buffer(struct archive_read_disk *a)
629 {
630         struct tree *t = a->tree;
631         struct filesystem *cf = t->current_filesystem;
632         size_t asize;
633         size_t s;
634
635         if (cf->allocation_ptr == NULL) {
636                 /* If we couldn't get a filesystem alignment,
637                  * we use 4096 as default value but we won't use
638                  * O_DIRECT to open() and openat() operations. */
639                 long xfer_align = (cf->xfer_align == -1)?4096:cf->xfer_align;
640
641                 if (cf->max_xfer_size != -1)
642                         asize = cf->max_xfer_size + xfer_align;
643                 else {
644                         long incr = cf->incr_xfer_size;
645                         /* Some platform does not set a proper value to
646                          * incr_xfer_size.*/
647                         if (incr < 0)
648                                 incr = cf->min_xfer_size;
649                         if (cf->min_xfer_size < 0) {
650                                 incr = xfer_align;
651                                 asize = xfer_align;
652                         } else
653                                 asize = cf->min_xfer_size;
654
655                         /* Increase a buffer size up to 64K bytes in
656                          * a proper increment size. */
657                         while (asize < 1024*64)
658                                 asize += incr;
659                         /* Take a margin to adjust to the filesystem
660                          * alignment. */
661                         asize += xfer_align;
662                 }
663                 cf->allocation_ptr = malloc(asize);
664                 if (cf->allocation_ptr == NULL) {
665                         archive_set_error(&a->archive, ENOMEM,
666                             "Couldn't allocate memory");
667                         a->archive.state = ARCHIVE_STATE_FATAL;
668                         return (ARCHIVE_FATAL);
669                 }
670
671                 /*
672                  * Calculate proper address for the filesystem.
673                  */
674                 s = (uintptr_t)cf->allocation_ptr;
675                 s %= xfer_align;
676                 if (s > 0)
677                         s = xfer_align - s;
678
679                 /*
680                  * Set a read buffer pointer in the proper alignment of
681                  * the current filesystem.
682                  */
683                 cf->buff = cf->allocation_ptr + s;
684                 cf->buff_size = asize - xfer_align;
685         }
686         return (ARCHIVE_OK);
687 }
688
689 static int
690 _archive_read_data_block(struct archive *_a, const void **buff,
691     size_t *size, int64_t *offset)
692 {
693         struct archive_read_disk *a = (struct archive_read_disk *)_a;
694         struct tree *t = a->tree;
695         int r;
696         ssize_t bytes;
697         int64_t sparse_bytes;
698         size_t buffbytes;
699         int empty_sparse_region = 0;
700
701         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA,
702             "archive_read_data_block");
703
704         if (t->entry_eof || t->entry_remaining_bytes <= 0) {
705                 r = ARCHIVE_EOF;
706                 goto abort_read_data;
707         }
708
709         /*
710          * Open the current file.
711          */
712         if (t->entry_fd < 0) {
713                 int flags = O_RDONLY | O_BINARY | O_CLOEXEC;
714
715                 /*
716                  * Eliminate or reduce cache effects if we can.
717                  *
718                  * Carefully consider this to be enabled.
719                  */
720 #if defined(O_DIRECT) && 0/* Disabled for now */
721                 if (t->current_filesystem->xfer_align != -1 &&
722                     t->nlink == 1)
723                         flags |= O_DIRECT;
724 #endif
725 #if defined(O_NOATIME)
726                 /*
727                  * Linux has O_NOATIME flag; use it if we need.
728                  */
729                 if ((t->flags & needsRestoreTimes) != 0 &&
730                     t->restore_time.noatime == 0)
731                         flags |= O_NOATIME;
732 #endif
733                 t->entry_fd = open_on_current_dir(t,
734                     tree_current_access_path(t), flags);
735                 __archive_ensure_cloexec_flag(t->entry_fd);
736 #if defined(O_NOATIME)
737                 /*
738                  * When we did open the file with O_NOATIME flag,
739                  * if successful, set 1 to t->restore_time.noatime
740                  * not to restore an atime of the file later.
741                  * if failed by EPERM, retry it without O_NOATIME flag.
742                  */
743                 if (flags & O_NOATIME) {
744                         if (t->entry_fd >= 0)
745                                 t->restore_time.noatime = 1;
746                         else if (errno == EPERM)
747                                 flags &= ~O_NOATIME;
748                 }
749 #endif
750                 if (t->entry_fd < 0) {
751                         archive_set_error(&a->archive, errno,
752                             "Couldn't open %s", tree_current_path(t));
753                         r = ARCHIVE_FAILED;
754                         tree_enter_initial_dir(t);
755                         goto abort_read_data;
756                 }
757                 tree_enter_initial_dir(t);
758         }
759
760         /*
761          * Allocate read buffer if not allocated.
762          */
763         if (t->current_filesystem->allocation_ptr == NULL) {
764                 r = setup_suitable_read_buffer(a);
765                 if (r != ARCHIVE_OK) {
766                         a->archive.state = ARCHIVE_STATE_FATAL;
767                         goto abort_read_data;
768                 }
769         }
770         t->entry_buff = t->current_filesystem->buff;
771         t->entry_buff_size = t->current_filesystem->buff_size;
772
773         buffbytes = t->entry_buff_size;
774         if ((int64_t)buffbytes > t->current_sparse->length)
775                 buffbytes = t->current_sparse->length;
776
777         if (t->current_sparse->length == 0)
778                 empty_sparse_region = 1;
779
780         /*
781          * Skip hole.
782          * TODO: Should we consider t->current_filesystem->xfer_align?
783          */
784         if (t->current_sparse->offset > t->entry_total) {
785                 if (lseek(t->entry_fd,
786                     (off_t)t->current_sparse->offset, SEEK_SET) < 0) {
787                         archive_set_error(&a->archive, errno, "Seek error");
788                         r = ARCHIVE_FATAL;
789                         a->archive.state = ARCHIVE_STATE_FATAL;
790                         goto abort_read_data;
791                 }
792                 sparse_bytes = t->current_sparse->offset - t->entry_total;
793                 t->entry_remaining_bytes -= sparse_bytes;
794                 t->entry_total += sparse_bytes;
795         }
796
797         /*
798          * Read file contents.
799          */
800         if (buffbytes > 0) {
801                 bytes = read(t->entry_fd, t->entry_buff, buffbytes);
802                 if (bytes < 0) {
803                         archive_set_error(&a->archive, errno, "Read error");
804                         r = ARCHIVE_FATAL;
805                         a->archive.state = ARCHIVE_STATE_FATAL;
806                         goto abort_read_data;
807                 }
808         } else
809                 bytes = 0;
810         /*
811          * Return an EOF unless we've read a leading empty sparse region, which
812          * is used to represent fully-sparse files.
813         */
814         if (bytes == 0 && !empty_sparse_region) {
815                 /* Get EOF */
816                 t->entry_eof = 1;
817                 r = ARCHIVE_EOF;
818                 goto abort_read_data;
819         }
820         *buff = t->entry_buff;
821         *size = bytes;
822         *offset = t->entry_total;
823         t->entry_total += bytes;
824         t->entry_remaining_bytes -= bytes;
825         if (t->entry_remaining_bytes == 0) {
826                 /* Close the current file descriptor */
827                 close_and_restore_time(t->entry_fd, t, &t->restore_time);
828                 t->entry_fd = -1;
829                 t->entry_eof = 1;
830         }
831         t->current_sparse->offset += bytes;
832         t->current_sparse->length -= bytes;
833         if (t->current_sparse->length == 0 && !t->entry_eof)
834                 t->current_sparse++;
835         return (ARCHIVE_OK);
836
837 abort_read_data:
838         *buff = NULL;
839         *size = 0;
840         *offset = t->entry_total;
841         if (t->entry_fd >= 0) {
842                 /* Close the current file descriptor */
843                 close_and_restore_time(t->entry_fd, t, &t->restore_time);
844                 t->entry_fd = -1;
845         }
846         return (r);
847 }
848
849 static int
850 next_entry(struct archive_read_disk *a, struct tree *t,
851     struct archive_entry *entry)
852 {
853         const struct stat *st; /* info to use for this entry */
854         const struct stat *lst;/* lstat() information */
855         const char *name;
856         int delayed, delayed_errno, descend, r;
857         struct archive_string delayed_str;
858
859         delayed = ARCHIVE_OK;
860         delayed_errno = 0;
861         archive_string_init(&delayed_str);
862
863         st = NULL;
864         lst = NULL;
865         t->descend = 0;
866         do {
867                 switch (tree_next(t)) {
868                 case TREE_ERROR_FATAL:
869                         archive_set_error(&a->archive, t->tree_errno,
870                             "%s: Unable to continue traversing directory tree",
871                             tree_current_path(t));
872                         a->archive.state = ARCHIVE_STATE_FATAL;
873                         tree_enter_initial_dir(t);
874                         return (ARCHIVE_FATAL);
875                 case TREE_ERROR_DIR:
876                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
877                             "%s: Couldn't visit directory",
878                             tree_current_path(t));
879                         tree_enter_initial_dir(t);
880                         return (ARCHIVE_FAILED);
881                 case 0:
882                         tree_enter_initial_dir(t);
883                         return (ARCHIVE_EOF);
884                 case TREE_POSTDESCENT:
885                 case TREE_POSTASCENT:
886                         break;
887                 case TREE_REGULAR:
888                         lst = tree_current_lstat(t);
889                         if (lst == NULL) {
890                             if (errno == ENOENT && t->depth > 0) {
891                                 delayed = ARCHIVE_WARN;
892                                 delayed_errno = errno;
893                                 if (delayed_str.length == 0) {
894                                         archive_string_sprintf(&delayed_str,
895                                             "%s", tree_current_path(t));
896                                 } else {
897                                         archive_string_sprintf(&delayed_str,
898                                             " %s", tree_current_path(t));
899                                 }
900                             } else {
901                                 archive_set_error(&a->archive, errno,
902                                     "%s: Cannot stat",
903                                     tree_current_path(t));
904                                 tree_enter_initial_dir(t);
905                                 return (ARCHIVE_FAILED);
906                             }
907                         }
908                         break;
909                 }
910         } while (lst == NULL);
911
912 #ifdef __APPLE__
913         if (a->flags & ARCHIVE_READDISK_MAC_COPYFILE) {
914                 /* If we're using copyfile(), ignore "._XXX" files. */
915                 const char *bname = strrchr(tree_current_path(t), '/');
916                 if (bname == NULL)
917                         bname = tree_current_path(t);
918                 else
919                         ++bname;
920                 if (bname[0] == '.' && bname[1] == '_')
921                         return (ARCHIVE_RETRY);
922         }
923 #endif
924
925         archive_entry_copy_pathname(entry, tree_current_path(t));
926         /*
927          * Perform path matching.
928          */
929         if (a->matching) {
930                 r = archive_match_path_excluded(a->matching, entry);
931                 if (r < 0) {
932                         archive_set_error(&(a->archive), errno,
933                             "Failed : %s", archive_error_string(a->matching));
934                         return (r);
935                 }
936                 if (r) {
937                         if (a->excluded_cb_func)
938                                 a->excluded_cb_func(&(a->archive),
939                                     a->excluded_cb_data, entry);
940                         return (ARCHIVE_RETRY);
941                 }
942         }
943
944         /*
945          * Distinguish 'L'/'P'/'H' symlink following.
946          */
947         switch(t->symlink_mode) {
948         case 'H':
949                 /* 'H': After the first item, rest like 'P'. */
950                 t->symlink_mode = 'P';
951                 /* 'H': First item (from command line) like 'L'. */
952                 /* FALLTHROUGH */
953         case 'L':
954                 /* 'L': Do descend through a symlink to dir. */
955                 descend = tree_current_is_dir(t);
956                 /* 'L': Follow symlinks to files. */
957                 a->symlink_mode = 'L';
958                 a->follow_symlinks = 1;
959                 /* 'L': Archive symlinks as targets, if we can. */
960                 st = tree_current_stat(t);
961                 if (st != NULL && !tree_target_is_same_as_parent(t, st))
962                         break;
963                 /* If stat fails, we have a broken symlink;
964                  * in that case, don't follow the link. */
965                 /* FALLTHROUGH */
966         default:
967                 /* 'P': Don't descend through a symlink to dir. */
968                 descend = tree_current_is_physical_dir(t);
969                 /* 'P': Don't follow symlinks to files. */
970                 a->symlink_mode = 'P';
971                 a->follow_symlinks = 0;
972                 /* 'P': Archive symlinks as symlinks. */
973                 st = lst;
974                 break;
975         }
976
977         if (update_current_filesystem(a, st->st_dev) != ARCHIVE_OK) {
978                 a->archive.state = ARCHIVE_STATE_FATAL;
979                 tree_enter_initial_dir(t);
980                 return (ARCHIVE_FATAL);
981         }
982         if (t->initial_filesystem_id == -1)
983                 t->initial_filesystem_id = t->current_filesystem_id;
984         if (a->flags & ARCHIVE_READDISK_NO_TRAVERSE_MOUNTS) {
985                 if (t->initial_filesystem_id != t->current_filesystem_id)
986                         descend = 0;
987         }
988         t->descend = descend;
989
990         /*
991          * Honor nodump flag.
992          * If the file is marked with nodump flag, do not return this entry.
993          */
994         if (a->flags & ARCHIVE_READDISK_HONOR_NODUMP) {
995 #if defined(HAVE_STRUCT_STAT_ST_FLAGS) && defined(UF_NODUMP)
996                 if (st->st_flags & UF_NODUMP)
997                         return (ARCHIVE_RETRY);
998 #elif (defined(FS_IOC_GETFLAGS) && defined(FS_NODUMP_FL) && \
999        defined(HAVE_WORKING_FS_IOC_GETFLAGS)) || \
1000       (defined(EXT2_IOC_GETFLAGS) && defined(EXT2_NODUMP_FL) && \
1001        defined(HAVE_WORKING_EXT2_IOC_GETFLAGS))
1002                 if (S_ISREG(st->st_mode) || S_ISDIR(st->st_mode)) {
1003                         int stflags;
1004
1005                         t->entry_fd = open_on_current_dir(t,
1006                             tree_current_access_path(t),
1007                             O_RDONLY | O_NONBLOCK | O_CLOEXEC);
1008                         __archive_ensure_cloexec_flag(t->entry_fd);
1009                         if (t->entry_fd >= 0) {
1010                                 r = ioctl(t->entry_fd,
1011 #ifdef FS_IOC_GETFLAGS
1012                                 FS_IOC_GETFLAGS,
1013 #else
1014                                 EXT2_IOC_GETFLAGS,
1015 #endif
1016                                         &stflags);
1017 #ifdef FS_NODUMP_FL
1018                                 if (r == 0 && (stflags & FS_NODUMP_FL) != 0)
1019 #else
1020                                 if (r == 0 && (stflags & EXT2_NODUMP_FL) != 0)
1021 #endif
1022                                         return (ARCHIVE_RETRY);
1023                         }
1024                 }
1025 #endif
1026         }
1027
1028         archive_entry_copy_stat(entry, st);
1029
1030         /* Save the times to be restored. This must be in before
1031          * calling archive_read_disk_descend() or any chance of it,
1032          * especially, invoking a callback. */
1033         t->restore_time.mtime = archive_entry_mtime(entry);
1034         t->restore_time.mtime_nsec = archive_entry_mtime_nsec(entry);
1035         t->restore_time.atime = archive_entry_atime(entry);
1036         t->restore_time.atime_nsec = archive_entry_atime_nsec(entry);
1037         t->restore_time.filetype = archive_entry_filetype(entry);
1038         t->restore_time.noatime = t->current_filesystem->noatime;
1039
1040         /*
1041          * Perform time matching.
1042          */
1043         if (a->matching) {
1044                 r = archive_match_time_excluded(a->matching, entry);
1045                 if (r < 0) {
1046                         archive_set_error(&(a->archive), errno,
1047                             "Failed : %s", archive_error_string(a->matching));
1048                         return (r);
1049                 }
1050                 if (r) {
1051                         if (a->excluded_cb_func)
1052                                 a->excluded_cb_func(&(a->archive),
1053                                     a->excluded_cb_data, entry);
1054                         return (ARCHIVE_RETRY);
1055                 }
1056         }
1057
1058         /* Lookup uname/gname */
1059         name = archive_read_disk_uname(&(a->archive), archive_entry_uid(entry));
1060         if (name != NULL)
1061                 archive_entry_copy_uname(entry, name);
1062         name = archive_read_disk_gname(&(a->archive), archive_entry_gid(entry));
1063         if (name != NULL)
1064                 archive_entry_copy_gname(entry, name);
1065
1066         /*
1067          * Perform owner matching.
1068          */
1069         if (a->matching) {
1070                 r = archive_match_owner_excluded(a->matching, entry);
1071                 if (r < 0) {
1072                         archive_set_error(&(a->archive), errno,
1073                             "Failed : %s", archive_error_string(a->matching));
1074                         return (r);
1075                 }
1076                 if (r) {
1077                         if (a->excluded_cb_func)
1078                                 a->excluded_cb_func(&(a->archive),
1079                                     a->excluded_cb_data, entry);
1080                         return (ARCHIVE_RETRY);
1081                 }
1082         }
1083
1084         /*
1085          * Invoke a meta data filter callback.
1086          */
1087         if (a->metadata_filter_func) {
1088                 if (!a->metadata_filter_func(&(a->archive),
1089                     a->metadata_filter_data, entry))
1090                         return (ARCHIVE_RETRY);
1091         }
1092
1093         /*
1094          * Populate the archive_entry with metadata from the disk.
1095          */
1096         archive_entry_copy_sourcepath(entry, tree_current_access_path(t));
1097         r = archive_read_disk_entry_from_file(&(a->archive), entry,
1098                 t->entry_fd, st);
1099
1100         if (r == ARCHIVE_OK) {
1101                 r = delayed;
1102                 if (r != ARCHIVE_OK) {
1103                         archive_string_sprintf(&delayed_str, ": %s",
1104                             "File removed before we read it");
1105                         archive_set_error(&(a->archive), delayed_errno,
1106                             "%s", delayed_str.s);
1107                 }
1108         }
1109         archive_string_free(&delayed_str);
1110
1111         return (r);
1112 }
1113
1114 static int
1115 _archive_read_next_header(struct archive *_a, struct archive_entry **entryp)
1116 {
1117         int ret;
1118         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1119         *entryp = NULL;
1120         ret = _archive_read_next_header2(_a, a->entry);
1121         *entryp = a->entry;
1122         return ret;
1123 }
1124
1125 static int
1126 _archive_read_next_header2(struct archive *_a, struct archive_entry *entry)
1127 {
1128         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1129         struct tree *t;
1130         int r;
1131
1132         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
1133             ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1134             "archive_read_next_header2");
1135
1136         t = a->tree;
1137         if (t->entry_fd >= 0) {
1138                 close_and_restore_time(t->entry_fd, t, &t->restore_time);
1139                 t->entry_fd = -1;
1140         }
1141
1142         archive_entry_clear(entry);
1143
1144         for (;;) {
1145                 r = next_entry(a, t, entry);
1146                 if (t->entry_fd >= 0) {
1147                         close(t->entry_fd);
1148                         t->entry_fd = -1;
1149                 }
1150
1151                 if (r == ARCHIVE_RETRY) {
1152                         archive_entry_clear(entry);
1153                         continue;
1154                 }
1155                 break;
1156         }
1157
1158         /* Return to the initial directory. */
1159         tree_enter_initial_dir(t);
1160
1161         /*
1162          * EOF and FATAL are persistent at this layer.  By
1163          * modifying the state, we guarantee that future calls to
1164          * read a header or read data will fail.
1165          */
1166         switch (r) {
1167         case ARCHIVE_EOF:
1168                 a->archive.state = ARCHIVE_STATE_EOF;
1169                 break;
1170         case ARCHIVE_OK:
1171         case ARCHIVE_WARN:
1172                 /* Overwrite the sourcepath based on the initial directory. */
1173                 archive_entry_copy_sourcepath(entry, tree_current_path(t));
1174                 t->entry_total = 0;
1175                 if (archive_entry_filetype(entry) == AE_IFREG) {
1176                         t->nlink = archive_entry_nlink(entry);
1177                         t->entry_remaining_bytes = archive_entry_size(entry);
1178                         t->entry_eof = (t->entry_remaining_bytes == 0)? 1: 0;
1179                         if (!t->entry_eof &&
1180                             setup_sparse(a, entry) != ARCHIVE_OK)
1181                                 return (ARCHIVE_FATAL);
1182                 } else {
1183                         t->entry_remaining_bytes = 0;
1184                         t->entry_eof = 1;
1185                 }
1186                 a->archive.state = ARCHIVE_STATE_DATA;
1187                 break;
1188         case ARCHIVE_RETRY:
1189                 break;
1190         case ARCHIVE_FATAL:
1191                 a->archive.state = ARCHIVE_STATE_FATAL;
1192                 break;
1193         }
1194
1195         __archive_reset_read_data(&a->archive);
1196         return (r);
1197 }
1198
1199 static int
1200 setup_sparse(struct archive_read_disk *a, struct archive_entry *entry)
1201 {
1202         struct tree *t = a->tree;
1203         int64_t length, offset;
1204         int i;
1205
1206         t->sparse_count = archive_entry_sparse_reset(entry);
1207         if (t->sparse_count+1 > t->sparse_list_size) {
1208                 free(t->sparse_list);
1209                 t->sparse_list_size = t->sparse_count + 1;
1210                 t->sparse_list = malloc(sizeof(t->sparse_list[0]) *
1211                     t->sparse_list_size);
1212                 if (t->sparse_list == NULL) {
1213                         t->sparse_list_size = 0;
1214                         archive_set_error(&a->archive, ENOMEM,
1215                             "Can't allocate data");
1216                         a->archive.state = ARCHIVE_STATE_FATAL;
1217                         return (ARCHIVE_FATAL);
1218                 }
1219         }
1220         for (i = 0; i < t->sparse_count; i++) {
1221                 archive_entry_sparse_next(entry, &offset, &length);
1222                 t->sparse_list[i].offset = offset;
1223                 t->sparse_list[i].length = length;
1224         }
1225         if (i == 0) {
1226                 t->sparse_list[i].offset = 0;
1227                 t->sparse_list[i].length = archive_entry_size(entry);
1228         } else {
1229                 t->sparse_list[i].offset = archive_entry_size(entry);
1230                 t->sparse_list[i].length = 0;
1231         }
1232         t->current_sparse = t->sparse_list;
1233
1234         return (ARCHIVE_OK);
1235 }
1236
1237 int
1238 archive_read_disk_set_matching(struct archive *_a, struct archive *_ma,
1239     void (*_excluded_func)(struct archive *, void *, struct archive_entry *),
1240     void *_client_data)
1241 {
1242         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1243         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
1244             ARCHIVE_STATE_ANY, "archive_read_disk_set_matching");
1245         a->matching = _ma;
1246         a->excluded_cb_func = _excluded_func;
1247         a->excluded_cb_data = _client_data;
1248         return (ARCHIVE_OK);
1249 }
1250
1251 int
1252 archive_read_disk_set_metadata_filter_callback(struct archive *_a,
1253     int (*_metadata_filter_func)(struct archive *, void *,
1254     struct archive_entry *), void *_client_data)
1255 {
1256         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1257
1258         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_ANY,
1259             "archive_read_disk_set_metadata_filter_callback");
1260
1261         a->metadata_filter_func = _metadata_filter_func;
1262         a->metadata_filter_data = _client_data;
1263         return (ARCHIVE_OK);
1264 }
1265
1266 int
1267 archive_read_disk_can_descend(struct archive *_a)
1268 {
1269         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1270         struct tree *t = a->tree;
1271
1272         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
1273             ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1274             "archive_read_disk_can_descend");
1275
1276         return (t->visit_type == TREE_REGULAR && t->descend);
1277 }
1278
1279 /*
1280  * Called by the client to mark the directory just returned from
1281  * tree_next() as needing to be visited.
1282  */
1283 int
1284 archive_read_disk_descend(struct archive *_a)
1285 {
1286         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1287         struct tree *t = a->tree;
1288
1289         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
1290             ARCHIVE_STATE_HEADER | ARCHIVE_STATE_DATA,
1291             "archive_read_disk_descend");
1292
1293         if (t->visit_type != TREE_REGULAR || !t->descend)
1294                 return (ARCHIVE_OK);
1295
1296         /*
1297          * We must not treat the initial specified path as a physical dir,
1298          * because if we do then we will try and ascend out of it by opening
1299          * ".." which is (a) wrong and (b) causes spurious permissions errors
1300          * if ".." is not readable by us. Instead, treat it as if it were a
1301          * symlink. (This uses an extra fd, but it can only happen once at the
1302          * top level of a traverse.) But we can't necessarily assume t->st is
1303          * valid here (though t->lst is), which complicates the logic a
1304          * little.
1305          */
1306         if (tree_current_is_physical_dir(t)) {
1307                 tree_push(t, t->basename, t->current_filesystem_id,
1308                     t->lst.st_dev, t->lst.st_ino, &t->restore_time);
1309                 if (t->stack->parent->parent != NULL)
1310                         t->stack->flags |= isDir;
1311                 else
1312                         t->stack->flags |= isDirLink;
1313         } else if (tree_current_is_dir(t)) {
1314                 tree_push(t, t->basename, t->current_filesystem_id,
1315                     t->st.st_dev, t->st.st_ino, &t->restore_time);
1316                 t->stack->flags |= isDirLink;
1317         }
1318         t->descend = 0;
1319         return (ARCHIVE_OK);
1320 }
1321
1322 int
1323 archive_read_disk_open(struct archive *_a, const char *pathname)
1324 {
1325         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1326
1327         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
1328             ARCHIVE_STATE_NEW | ARCHIVE_STATE_CLOSED,
1329             "archive_read_disk_open");
1330         archive_clear_error(&a->archive);
1331
1332         return (_archive_read_disk_open(_a, pathname));
1333 }
1334
1335 int
1336 archive_read_disk_open_w(struct archive *_a, const wchar_t *pathname)
1337 {
1338         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1339         struct archive_string path;
1340         int ret;
1341
1342         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC,
1343             ARCHIVE_STATE_NEW | ARCHIVE_STATE_CLOSED,
1344             "archive_read_disk_open_w");
1345         archive_clear_error(&a->archive);
1346
1347         /* Make a char string from a wchar_t string. */
1348         archive_string_init(&path);
1349         if (archive_string_append_from_wcs(&path, pathname,
1350             wcslen(pathname)) != 0) {
1351                 if (errno == ENOMEM)
1352                         archive_set_error(&a->archive, ENOMEM,
1353                             "Can't allocate memory");
1354                 else
1355                         archive_set_error(&a->archive, ARCHIVE_ERRNO_MISC,
1356                             "Can't convert a path to a char string");
1357                 a->archive.state = ARCHIVE_STATE_FATAL;
1358                 ret = ARCHIVE_FATAL;
1359         } else
1360                 ret = _archive_read_disk_open(_a, path.s);
1361
1362         archive_string_free(&path);
1363         return (ret);
1364 }
1365
1366 static int
1367 _archive_read_disk_open(struct archive *_a, const char *pathname)
1368 {
1369         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1370
1371         if (a->tree != NULL)
1372                 a->tree = tree_reopen(a->tree, pathname,
1373                     a->flags & ARCHIVE_READDISK_RESTORE_ATIME);
1374         else
1375                 a->tree = tree_open(pathname, a->symlink_mode,
1376                     a->flags & ARCHIVE_READDISK_RESTORE_ATIME);
1377         if (a->tree == NULL) {
1378                 archive_set_error(&a->archive, ENOMEM,
1379                     "Can't allocate tar data");
1380                 a->archive.state = ARCHIVE_STATE_FATAL;
1381                 return (ARCHIVE_FATAL);
1382         }
1383         a->archive.state = ARCHIVE_STATE_HEADER;
1384
1385         return (ARCHIVE_OK);
1386 }
1387
1388 /*
1389  * Return a current filesystem ID which is index of the filesystem entry
1390  * you've visited through archive_read_disk.
1391  */
1392 int
1393 archive_read_disk_current_filesystem(struct archive *_a)
1394 {
1395         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1396
1397         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA,
1398             "archive_read_disk_current_filesystem");
1399
1400         return (a->tree->current_filesystem_id);
1401 }
1402
1403 static int
1404 update_current_filesystem(struct archive_read_disk *a, int64_t dev)
1405 {
1406         struct tree *t = a->tree;
1407         int i, fid;
1408
1409         if (t->current_filesystem != NULL &&
1410             t->current_filesystem->dev == dev)
1411                 return (ARCHIVE_OK);
1412
1413         for (i = 0; i < t->max_filesystem_id; i++) {
1414                 if (t->filesystem_table[i].dev == dev) {
1415                         /* There is the filesystem ID we've already generated. */
1416                         t->current_filesystem_id = i;
1417                         t->current_filesystem = &(t->filesystem_table[i]);
1418                         return (ARCHIVE_OK);
1419                 }
1420         }
1421
1422         /*
1423          * This is the new filesystem which we have to generate a new ID for.
1424          */
1425         fid = t->max_filesystem_id++;
1426         if (t->max_filesystem_id > t->allocated_filesystem) {
1427                 size_t s;
1428                 void *p;
1429
1430                 s = t->max_filesystem_id * 2;
1431                 p = realloc(t->filesystem_table,
1432                         s * sizeof(*t->filesystem_table));
1433                 if (p == NULL) {
1434                         archive_set_error(&a->archive, ENOMEM,
1435                             "Can't allocate tar data");
1436                         return (ARCHIVE_FATAL);
1437                 }
1438                 t->filesystem_table = (struct filesystem *)p;
1439                 t->allocated_filesystem = s;
1440         }
1441         t->current_filesystem_id = fid;
1442         t->current_filesystem = &(t->filesystem_table[fid]);
1443         t->current_filesystem->dev = dev;
1444         t->current_filesystem->allocation_ptr = NULL;
1445         t->current_filesystem->buff = NULL;
1446
1447         /* Setup the current filesystem properties which depend on
1448          * platform specific. */
1449         return (setup_current_filesystem(a));
1450 }
1451
1452 /*
1453  * Returns 1 if current filesystem is generated filesystem, 0 if it is not
1454  * or -1 if it is unknown.
1455  */
1456 int
1457 archive_read_disk_current_filesystem_is_synthetic(struct archive *_a)
1458 {
1459         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1460
1461         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA,
1462             "archive_read_disk_current_filesystem");
1463
1464         return (a->tree->current_filesystem->synthetic);
1465 }
1466
1467 /*
1468  * Returns 1 if current filesystem is remote filesystem, 0 if it is not
1469  * or -1 if it is unknown.
1470  */
1471 int
1472 archive_read_disk_current_filesystem_is_remote(struct archive *_a)
1473 {
1474         struct archive_read_disk *a = (struct archive_read_disk *)_a;
1475
1476         archive_check_magic(_a, ARCHIVE_READ_DISK_MAGIC, ARCHIVE_STATE_DATA,
1477             "archive_read_disk_current_filesystem");
1478
1479         return (a->tree->current_filesystem->remote);
1480 }
1481
1482 #if defined(_PC_REC_INCR_XFER_SIZE) && defined(_PC_REC_MAX_XFER_SIZE) &&\
1483         defined(_PC_REC_MIN_XFER_SIZE) && defined(_PC_REC_XFER_ALIGN)
1484 static int
1485 get_xfer_size(struct tree *t, int fd, const char *path)
1486 {
1487         t->current_filesystem->xfer_align = -1;
1488         errno = 0;
1489         if (fd >= 0) {
1490                 t->current_filesystem->incr_xfer_size =
1491                     fpathconf(fd, _PC_REC_INCR_XFER_SIZE);
1492                 t->current_filesystem->max_xfer_size =
1493                     fpathconf(fd, _PC_REC_MAX_XFER_SIZE);
1494                 t->current_filesystem->min_xfer_size =
1495                     fpathconf(fd, _PC_REC_MIN_XFER_SIZE);
1496                 t->current_filesystem->xfer_align =
1497                     fpathconf(fd, _PC_REC_XFER_ALIGN);
1498         } else if (path != NULL) {
1499                 t->current_filesystem->incr_xfer_size =
1500                     pathconf(path, _PC_REC_INCR_XFER_SIZE);
1501                 t->current_filesystem->max_xfer_size =
1502                     pathconf(path, _PC_REC_MAX_XFER_SIZE);
1503                 t->current_filesystem->min_xfer_size =
1504                     pathconf(path, _PC_REC_MIN_XFER_SIZE);
1505                 t->current_filesystem->xfer_align =
1506                     pathconf(path, _PC_REC_XFER_ALIGN);
1507         }
1508         /* At least we need an alignment size. */
1509         if (t->current_filesystem->xfer_align == -1)
1510                 return ((errno == EINVAL)?1:-1);
1511         else
1512                 return (0);
1513 }
1514 #else
1515 static int
1516 get_xfer_size(struct tree *t, int fd, const char *path)
1517 {
1518         (void)t; /* UNUSED */
1519         (void)fd; /* UNUSED */
1520         (void)path; /* UNUSED */
1521         return (1);/* Not supported */
1522 }
1523 #endif
1524
1525 #if defined(HAVE_STATFS) && defined(HAVE_FSTATFS) && defined(MNT_LOCAL) \
1526         && !defined(ST_LOCAL)
1527
1528 /*
1529  * Gather current filesystem properties on FreeBSD, OpenBSD and Mac OS X.
1530  */
1531 static int
1532 setup_current_filesystem(struct archive_read_disk *a)
1533 {
1534         struct tree *t = a->tree;
1535         struct statfs sfs;
1536 #if defined(HAVE_GETVFSBYNAME) && defined(VFCF_SYNTHETIC)
1537 /* TODO: configure should set GETVFSBYNAME_ARG_TYPE to make
1538  * this accurate; some platforms have both and we need the one that's
1539  * used by getvfsbyname()
1540  *
1541  * Then the following would become:
1542  *  #if defined(GETVFSBYNAME_ARG_TYPE)
1543  *   GETVFSBYNAME_ARG_TYPE vfc;
1544  *  #endif
1545  */
1546 #  if defined(HAVE_STRUCT_XVFSCONF)
1547         struct xvfsconf vfc;
1548 #  else
1549         struct vfsconf vfc;
1550 #  endif
1551 #endif
1552         int r, xr = 0;
1553 #if !defined(HAVE_STRUCT_STATFS_F_NAMEMAX)
1554         long nm;
1555 #endif
1556
1557         t->current_filesystem->synthetic = -1;
1558         t->current_filesystem->remote = -1;
1559         if (tree_current_is_symblic_link_target(t)) {
1560 #if defined(HAVE_OPENAT)
1561                 /*
1562                  * Get file system statistics on any directory
1563                  * where current is.
1564                  */
1565                 int fd = openat(tree_current_dir_fd(t),
1566                     tree_current_access_path(t), O_RDONLY | O_CLOEXEC);
1567                 __archive_ensure_cloexec_flag(fd);
1568                 if (fd < 0) {
1569                         archive_set_error(&a->archive, errno,
1570                             "openat failed");
1571                         return (ARCHIVE_FAILED);
1572                 }
1573                 r = fstatfs(fd, &sfs);
1574                 if (r == 0)
1575                         xr = get_xfer_size(t, fd, NULL);
1576                 close(fd);
1577 #else
1578                 if (tree_enter_working_dir(t) != 0) {
1579                         archive_set_error(&a->archive, errno, "fchdir failed");
1580                         return (ARCHIVE_FAILED);
1581                 }
1582                 r = statfs(tree_current_access_path(t), &sfs);
1583                 if (r == 0)
1584                         xr = get_xfer_size(t, -1, tree_current_access_path(t));
1585 #endif
1586         } else {
1587                 r = fstatfs(tree_current_dir_fd(t), &sfs);
1588                 if (r == 0)
1589                         xr = get_xfer_size(t, tree_current_dir_fd(t), NULL);
1590         }
1591         if (r == -1 || xr == -1) {
1592                 archive_set_error(&a->archive, errno, "statfs failed");
1593                 return (ARCHIVE_FAILED);
1594         } else if (xr == 1) {
1595                 /* pathconf(_PC_REX_*) operations are not supported. */
1596                 t->current_filesystem->xfer_align = sfs.f_bsize;
1597                 t->current_filesystem->max_xfer_size = -1;
1598                 t->current_filesystem->min_xfer_size = sfs.f_iosize;
1599                 t->current_filesystem->incr_xfer_size = sfs.f_iosize;
1600         }
1601         if (sfs.f_flags & MNT_LOCAL)
1602                 t->current_filesystem->remote = 0;
1603         else
1604                 t->current_filesystem->remote = 1;
1605
1606 #if defined(HAVE_GETVFSBYNAME) && defined(VFCF_SYNTHETIC)
1607         r = getvfsbyname(sfs.f_fstypename, &vfc);
1608         if (r == -1) {
1609                 archive_set_error(&a->archive, errno, "getvfsbyname failed");
1610                 return (ARCHIVE_FAILED);
1611         }
1612         if (vfc.vfc_flags & VFCF_SYNTHETIC)
1613                 t->current_filesystem->synthetic = 1;
1614         else
1615                 t->current_filesystem->synthetic = 0;
1616 #endif
1617
1618 #if defined(MNT_NOATIME)
1619         if (sfs.f_flags & MNT_NOATIME)
1620                 t->current_filesystem->noatime = 1;
1621         else
1622 #endif
1623                 t->current_filesystem->noatime = 0;
1624
1625 #if defined(USE_READDIR_R)
1626         /* Set maximum filename length. */
1627 #if defined(HAVE_STRUCT_STATFS_F_NAMEMAX)
1628         t->current_filesystem->name_max = sfs.f_namemax;
1629 #else
1630 # if defined(_PC_NAME_MAX)
1631         /* Mac OS X does not have f_namemax in struct statfs. */
1632         if (tree_current_is_symblic_link_target(t)) {
1633                 if (tree_enter_working_dir(t) != 0) {
1634                         archive_set_error(&a->archive, errno, "fchdir failed");
1635                         return (ARCHIVE_FAILED);
1636                 }
1637                 nm = pathconf(tree_current_access_path(t), _PC_NAME_MAX);
1638         } else
1639                 nm = fpathconf(tree_current_dir_fd(t), _PC_NAME_MAX);
1640 # else
1641         nm = -1;
1642 # endif
1643         if (nm == -1)
1644                 t->current_filesystem->name_max = NAME_MAX;
1645         else
1646                 t->current_filesystem->name_max = nm;
1647 #endif
1648 #endif /* USE_READDIR_R */
1649         return (ARCHIVE_OK);
1650 }
1651
1652 #elif (defined(HAVE_STATVFS) || defined(HAVE_FSTATVFS)) && defined(ST_LOCAL)
1653
1654 /*
1655  * Gather current filesystem properties on NetBSD
1656  */
1657 static int
1658 setup_current_filesystem(struct archive_read_disk *a)
1659 {
1660         struct tree *t = a->tree;
1661         struct statvfs svfs;
1662         int r, xr = 0;
1663
1664         t->current_filesystem->synthetic = -1;
1665         if (tree_enter_working_dir(t) != 0) {
1666                 archive_set_error(&a->archive, errno, "fchdir failed");
1667                 return (ARCHIVE_FAILED);
1668         }
1669         if (tree_current_is_symblic_link_target(t)) {
1670                 r = statvfs(tree_current_access_path(t), &svfs);
1671                 if (r == 0)
1672                         xr = get_xfer_size(t, -1, tree_current_access_path(t));
1673         } else {
1674 #ifdef HAVE_FSTATVFS
1675                 r = fstatvfs(tree_current_dir_fd(t), &svfs);
1676                 if (r == 0)
1677                         xr = get_xfer_size(t, tree_current_dir_fd(t), NULL);
1678 #else
1679                 r = statvfs(".", &svfs);
1680                 if (r == 0)
1681                         xr = get_xfer_size(t, -1, ".");
1682 #endif
1683         }
1684         if (r == -1 || xr == -1) {
1685                 t->current_filesystem->remote = -1;
1686                 archive_set_error(&a->archive, errno, "statvfs failed");
1687                 return (ARCHIVE_FAILED);
1688         } else if (xr == 1) {
1689                 /* Usually come here unless NetBSD supports _PC_REC_XFER_ALIGN
1690                  * for pathconf() function. */
1691                 t->current_filesystem->xfer_align = svfs.f_frsize;
1692                 t->current_filesystem->max_xfer_size = -1;
1693 #if defined(HAVE_STRUCT_STATVFS_F_IOSIZE)
1694                 t->current_filesystem->min_xfer_size = svfs.f_iosize;
1695                 t->current_filesystem->incr_xfer_size = svfs.f_iosize;
1696 #else
1697                 t->current_filesystem->min_xfer_size = svfs.f_bsize;
1698                 t->current_filesystem->incr_xfer_size = svfs.f_bsize;
1699 #endif
1700         }
1701         if (svfs.f_flag & ST_LOCAL)
1702                 t->current_filesystem->remote = 0;
1703         else
1704                 t->current_filesystem->remote = 1;
1705
1706 #if defined(ST_NOATIME)
1707         if (svfs.f_flag & ST_NOATIME)
1708                 t->current_filesystem->noatime = 1;
1709         else
1710 #endif
1711                 t->current_filesystem->noatime = 0;
1712
1713         /* Set maximum filename length. */
1714         t->current_filesystem->name_max = svfs.f_namemax;
1715         return (ARCHIVE_OK);
1716 }
1717
1718 #elif defined(HAVE_SYS_STATFS_H) && defined(HAVE_LINUX_MAGIC_H) &&\
1719         defined(HAVE_STATFS) && defined(HAVE_FSTATFS)
1720 /*
1721  * Note: statfs is deprecated since LSB 3.2
1722  */
1723
1724 #ifndef CIFS_SUPER_MAGIC
1725 #define CIFS_SUPER_MAGIC 0xFF534D42
1726 #endif
1727 #ifndef DEVFS_SUPER_MAGIC
1728 #define DEVFS_SUPER_MAGIC 0x1373
1729 #endif
1730
1731 /*
1732  * Gather current filesystem properties on Linux
1733  */
1734 static int
1735 setup_current_filesystem(struct archive_read_disk *a)
1736 {
1737         struct tree *t = a->tree;
1738         struct statfs sfs;
1739 #if defined(HAVE_STATVFS)
1740         struct statvfs svfs;
1741 #endif
1742         int r, vr = 0, xr = 0;
1743
1744         if (tree_current_is_symblic_link_target(t)) {
1745 #if defined(HAVE_OPENAT)
1746                 /*
1747                  * Get file system statistics on any directory
1748                  * where current is.
1749                  */
1750                 int fd = openat(tree_current_dir_fd(t),
1751                     tree_current_access_path(t), O_RDONLY | O_CLOEXEC);
1752                 __archive_ensure_cloexec_flag(fd);
1753                 if (fd < 0) {
1754                         archive_set_error(&a->archive, errno,
1755                             "openat failed");
1756                         return (ARCHIVE_FAILED);
1757                 }
1758 #if defined(HAVE_FSTATVFS)
1759                 vr = fstatvfs(fd, &svfs);/* for f_flag, mount flags */
1760 #endif
1761                 r = fstatfs(fd, &sfs);
1762                 if (r == 0)
1763                         xr = get_xfer_size(t, fd, NULL);
1764                 close(fd);
1765 #else
1766                 if (tree_enter_working_dir(t) != 0) {
1767                         archive_set_error(&a->archive, errno, "fchdir failed");
1768                         return (ARCHIVE_FAILED);
1769                 }
1770 #if defined(HAVE_STATVFS)
1771                 vr = statvfs(tree_current_access_path(t), &svfs);
1772 #endif
1773                 r = statfs(tree_current_access_path(t), &sfs);
1774                 if (r == 0)
1775                         xr = get_xfer_size(t, -1, tree_current_access_path(t));
1776 #endif
1777         } else {
1778 #ifdef HAVE_FSTATFS
1779 #if defined(HAVE_FSTATVFS)
1780                 vr = fstatvfs(tree_current_dir_fd(t), &svfs);
1781 #endif
1782                 r = fstatfs(tree_current_dir_fd(t), &sfs);
1783                 if (r == 0)
1784                         xr = get_xfer_size(t, tree_current_dir_fd(t), NULL);
1785 #else
1786                 if (tree_enter_working_dir(t) != 0) {
1787                         archive_set_error(&a->archive, errno, "fchdir failed");
1788                         return (ARCHIVE_FAILED);
1789                 }
1790 #if defined(HAVE_STATVFS)
1791                 vr = statvfs(".", &svfs);
1792 #endif
1793                 r = statfs(".", &sfs);
1794                 if (r == 0)
1795                         xr = get_xfer_size(t, -1, ".");
1796 #endif
1797         }
1798         if (r == -1 || xr == -1 || vr == -1) {
1799                 t->current_filesystem->synthetic = -1;
1800                 t->current_filesystem->remote = -1;
1801                 archive_set_error(&a->archive, errno, "statfs failed");
1802                 return (ARCHIVE_FAILED);
1803         } else if (xr == 1) {
1804                 /* pathconf(_PC_REX_*) operations are not supported. */
1805 #if defined(HAVE_STATVFS)
1806                 t->current_filesystem->xfer_align = svfs.f_frsize;
1807                 t->current_filesystem->max_xfer_size = -1;
1808                 t->current_filesystem->min_xfer_size = svfs.f_bsize;
1809                 t->current_filesystem->incr_xfer_size = svfs.f_bsize;
1810 #else
1811                 t->current_filesystem->xfer_align = sfs.f_frsize;
1812                 t->current_filesystem->max_xfer_size = -1;
1813                 t->current_filesystem->min_xfer_size = sfs.f_bsize;
1814                 t->current_filesystem->incr_xfer_size = sfs.f_bsize;
1815 #endif
1816         }
1817         switch (sfs.f_type) {
1818         case AFS_SUPER_MAGIC:
1819         case CIFS_SUPER_MAGIC:
1820         case CODA_SUPER_MAGIC:
1821         case NCP_SUPER_MAGIC:/* NetWare */
1822         case NFS_SUPER_MAGIC:
1823         case SMB_SUPER_MAGIC:
1824                 t->current_filesystem->remote = 1;
1825                 t->current_filesystem->synthetic = 0;
1826                 break;
1827         case DEVFS_SUPER_MAGIC:
1828         case PROC_SUPER_MAGIC:
1829         case USBDEVICE_SUPER_MAGIC:
1830                 t->current_filesystem->remote = 0;
1831                 t->current_filesystem->synthetic = 1;
1832                 break;
1833         default:
1834                 t->current_filesystem->remote = 0;
1835                 t->current_filesystem->synthetic = 0;
1836                 break;
1837         }
1838
1839 #if defined(ST_NOATIME)
1840 #if defined(HAVE_STATVFS)
1841         if (svfs.f_flag & ST_NOATIME)
1842 #else
1843         if (sfs.f_flags & ST_NOATIME)
1844 #endif
1845                 t->current_filesystem->noatime = 1;
1846         else
1847 #endif
1848                 t->current_filesystem->noatime = 0;
1849
1850 #if defined(USE_READDIR_R)
1851         /* Set maximum filename length. */
1852         t->current_filesystem->name_max = sfs.f_namelen;
1853 #endif
1854         return (ARCHIVE_OK);
1855 }
1856
1857 #elif defined(HAVE_SYS_STATVFS_H) &&\
1858         (defined(HAVE_STATVFS) || defined(HAVE_FSTATVFS))
1859
1860 /*
1861  * Gather current filesystem properties on other posix platform.
1862  */
1863 static int
1864 setup_current_filesystem(struct archive_read_disk *a)
1865 {
1866         struct tree *t = a->tree;
1867         struct statvfs svfs;
1868         int r, xr = 0;
1869
1870         t->current_filesystem->synthetic = -1;/* Not supported */
1871         t->current_filesystem->remote = -1;/* Not supported */
1872         if (tree_current_is_symblic_link_target(t)) {
1873 #if defined(HAVE_OPENAT)
1874                 /*
1875                  * Get file system statistics on any directory
1876                  * where current is.
1877                  */
1878                 int fd = openat(tree_current_dir_fd(t),
1879                     tree_current_access_path(t), O_RDONLY | O_CLOEXEC);
1880                 __archive_ensure_cloexec_flag(fd);
1881                 if (fd < 0) {
1882                         archive_set_error(&a->archive, errno,
1883                             "openat failed");
1884                         return (ARCHIVE_FAILED);
1885                 }
1886                 r = fstatvfs(fd, &svfs);
1887                 if (r == 0)
1888                         xr = get_xfer_size(t, fd, NULL);
1889                 close(fd);
1890 #else
1891                 if (tree_enter_working_dir(t) != 0) {
1892                         archive_set_error(&a->archive, errno, "fchdir failed");
1893                         return (ARCHIVE_FAILED);
1894                 }
1895                 r = statvfs(tree_current_access_path(t), &svfs);
1896                 if (r == 0)
1897                         xr = get_xfer_size(t, -1, tree_current_access_path(t));
1898 #endif
1899         } else {
1900 #ifdef HAVE_FSTATVFS
1901                 r = fstatvfs(tree_current_dir_fd(t), &svfs);
1902                 if (r == 0)
1903                         xr = get_xfer_size(t, tree_current_dir_fd(t), NULL);
1904 #else
1905                 if (tree_enter_working_dir(t) != 0) {
1906                         archive_set_error(&a->archive, errno, "fchdir failed");
1907                         return (ARCHIVE_FAILED);
1908                 }
1909                 r = statvfs(".", &svfs);
1910                 if (r == 0)
1911                         xr = get_xfer_size(t, -1, ".");
1912 #endif
1913         }
1914         if (r == -1 || xr == -1) {
1915                 t->current_filesystem->synthetic = -1;
1916                 t->current_filesystem->remote = -1;
1917                 archive_set_error(&a->archive, errno, "statvfs failed");
1918                 return (ARCHIVE_FAILED);
1919         } else if (xr == 1) {
1920                 /* pathconf(_PC_REX_*) operations are not supported. */
1921                 t->current_filesystem->xfer_align = svfs.f_frsize;
1922                 t->current_filesystem->max_xfer_size = -1;
1923                 t->current_filesystem->min_xfer_size = svfs.f_bsize;
1924                 t->current_filesystem->incr_xfer_size = svfs.f_bsize;
1925         }
1926
1927 #if defined(ST_NOATIME)
1928         if (svfs.f_flag & ST_NOATIME)
1929                 t->current_filesystem->noatime = 1;
1930         else
1931 #endif
1932                 t->current_filesystem->noatime = 0;
1933
1934 #if defined(USE_READDIR_R)
1935         /* Set maximum filename length. */
1936         t->current_filesystem->name_max = svfs.f_namemax;
1937 #endif
1938         return (ARCHIVE_OK);
1939 }
1940
1941 #else
1942
1943 /*
1944  * Generic: Gather current filesystem properties.
1945  * TODO: Is this generic function really needed?
1946  */
1947 static int
1948 setup_current_filesystem(struct archive_read_disk *a)
1949 {
1950         struct tree *t = a->tree;
1951 #if defined(_PC_NAME_MAX) && defined(USE_READDIR_R)
1952         long nm;
1953 #endif
1954         t->current_filesystem->synthetic = -1;/* Not supported */
1955         t->current_filesystem->remote = -1;/* Not supported */
1956         t->current_filesystem->noatime = 0;
1957         (void)get_xfer_size(t, -1, ".");/* Dummy call to avoid build error. */
1958         t->current_filesystem->xfer_align = -1;/* Unknown */
1959         t->current_filesystem->max_xfer_size = -1;
1960         t->current_filesystem->min_xfer_size = -1;
1961         t->current_filesystem->incr_xfer_size = -1;
1962
1963 #if defined(USE_READDIR_R)
1964         /* Set maximum filename length. */
1965 #  if defined(_PC_NAME_MAX)
1966         if (tree_current_is_symblic_link_target(t)) {
1967                 if (tree_enter_working_dir(t) != 0) {
1968                         archive_set_error(&a->archive, errno, "fchdir failed");
1969                         return (ARCHIVE_FAILED);
1970                 }
1971                 nm = pathconf(tree_current_access_path(t), _PC_NAME_MAX);
1972         } else
1973                 nm = fpathconf(tree_current_dir_fd(t), _PC_NAME_MAX);
1974         if (nm == -1)
1975 #  endif /* _PC_NAME_MAX */
1976                 /*
1977                  * Some systems (HP-UX or others?) incorrectly defined
1978                  * NAME_MAX macro to be a smaller value.
1979                  */
1980 #  if defined(NAME_MAX) && NAME_MAX >= 255
1981                 t->current_filesystem->name_max = NAME_MAX;
1982 #  else
1983                 /* No way to get a trusted value of maximum filename
1984                  * length. */
1985                 t->current_filesystem->name_max = PATH_MAX;
1986 #  endif /* NAME_MAX */
1987 #  if defined(_PC_NAME_MAX)
1988         else
1989                 t->current_filesystem->name_max = nm;
1990 #  endif /* _PC_NAME_MAX */
1991 #endif /* USE_READDIR_R */
1992         return (ARCHIVE_OK);
1993 }
1994
1995 #endif
1996
1997 static int
1998 close_and_restore_time(int fd, struct tree *t, struct restore_time *rt)
1999 {
2000 #ifndef HAVE_UTIMES
2001         (void)t; /* UNUSED */
2002         (void)rt; /* UNUSED */
2003         return (close(fd));
2004 #else
2005 #if defined(HAVE_FUTIMENS) && !defined(__CYGWIN__)
2006         struct timespec timespecs[2];
2007 #endif
2008         struct timeval times[2];
2009
2010         if ((t->flags & needsRestoreTimes) == 0 || rt->noatime) {
2011                 if (fd >= 0)
2012                         return (close(fd));
2013                 else
2014                         return (0);
2015         }
2016
2017 #if defined(HAVE_FUTIMENS) && !defined(__CYGWIN__)
2018         if (rt->mtime == (time_t)-1) {
2019                 timespecs[1].tv_sec = 0;
2020                 timespecs[1].tv_nsec = UTIME_OMIT;
2021         } else {
2022                 timespecs[1].tv_sec = rt->mtime;
2023                 timespecs[1].tv_nsec = rt->mtime_nsec;
2024         }
2025
2026         if (rt->atime == (time_t)-1) {
2027                 timespecs[0].tv_sec = 0;
2028                 timespecs[0].tv_nsec = UTIME_OMIT;
2029         } else {
2030                 timespecs[0].tv_sec = rt->atime;
2031                 timespecs[0].tv_nsec = rt->atime_nsec;
2032         }
2033         /* futimens() is defined in POSIX.1-2008. */
2034         if (futimens(fd, timespecs) == 0)
2035                 return (close(fd));
2036 #endif
2037
2038         times[1].tv_sec = rt->mtime;
2039         times[1].tv_usec = rt->mtime_nsec / 1000;
2040
2041         times[0].tv_sec = rt->atime;
2042         times[0].tv_usec = rt->atime_nsec / 1000;
2043
2044 #if !defined(HAVE_FUTIMENS) && defined(HAVE_FUTIMES) && !defined(__CYGWIN__)
2045         if (futimes(fd, times) == 0)
2046                 return (close(fd));
2047 #endif
2048         close(fd);
2049 #if defined(HAVE_FUTIMESAT)
2050         if (futimesat(tree_current_dir_fd(t), rt->name, times) == 0)
2051                 return (0);
2052 #endif
2053 #ifdef HAVE_LUTIMES
2054         if (lutimes(rt->name, times) != 0)
2055 #else
2056         if (AE_IFLNK != rt->filetype && utimes(rt->name, times) != 0)
2057 #endif
2058                 return (-1);
2059 #endif
2060         return (0);
2061 }
2062
2063 static int
2064 open_on_current_dir(struct tree *t, const char *path, int flags)
2065 {
2066 #ifdef HAVE_OPENAT
2067         return (openat(tree_current_dir_fd(t), path, flags));
2068 #else
2069         if (tree_enter_working_dir(t) != 0)
2070                 return (-1);
2071         return (open(path, flags));
2072 #endif
2073 }
2074
2075 static int
2076 tree_dup(int fd)
2077 {
2078         int new_fd;
2079 #ifdef F_DUPFD_CLOEXEC
2080         static volatile int can_dupfd_cloexec = 1;
2081
2082         if (can_dupfd_cloexec) {
2083                 new_fd = fcntl(fd, F_DUPFD_CLOEXEC, 0);
2084                 if (new_fd != -1)
2085                         return (new_fd);
2086                 /* Linux 2.6.18 - 2.6.23 declare F_DUPFD_CLOEXEC,
2087                  * but it cannot be used. So we have to try dup(). */
2088                 /* We won't try F_DUPFD_CLOEXEC. */
2089                 can_dupfd_cloexec = 0;
2090         }
2091 #endif /* F_DUPFD_CLOEXEC */
2092         new_fd = dup(fd);
2093         __archive_ensure_cloexec_flag(new_fd);
2094         return (new_fd);
2095 }
2096
2097 /*
2098  * Add a directory path to the current stack.
2099  */
2100 static void
2101 tree_push(struct tree *t, const char *path, int filesystem_id,
2102     int64_t dev, int64_t ino, struct restore_time *rt)
2103 {
2104         struct tree_entry *te;
2105
2106         te = calloc(1, sizeof(*te));
2107         te->next = t->stack;
2108         te->parent = t->current;
2109         if (te->parent)
2110                 te->depth = te->parent->depth + 1;
2111         t->stack = te;
2112         archive_string_init(&te->name);
2113         te->symlink_parent_fd = -1;
2114         archive_strcpy(&te->name, path);
2115         te->flags = needsDescent | needsOpen | needsAscent;
2116         te->filesystem_id = filesystem_id;
2117         te->dev = dev;
2118         te->ino = ino;
2119         te->dirname_length = t->dirname_length;
2120         te->restore_time.name = te->name.s;
2121         if (rt != NULL) {
2122                 te->restore_time.mtime = rt->mtime;
2123                 te->restore_time.mtime_nsec = rt->mtime_nsec;
2124                 te->restore_time.atime = rt->atime;
2125                 te->restore_time.atime_nsec = rt->atime_nsec;
2126                 te->restore_time.filetype = rt->filetype;
2127                 te->restore_time.noatime = rt->noatime;
2128         }
2129 }
2130
2131 /*
2132  * Append a name to the current dir path.
2133  */
2134 static void
2135 tree_append(struct tree *t, const char *name, size_t name_length)
2136 {
2137         size_t size_needed;
2138
2139         t->path.s[t->dirname_length] = '\0';
2140         t->path.length = t->dirname_length;
2141         /* Strip trailing '/' from name, unless entire name is "/". */
2142         while (name_length > 1 && name[name_length - 1] == '/')
2143                 name_length--;
2144
2145         /* Resize pathname buffer as needed. */
2146         size_needed = name_length + t->dirname_length + 2;
2147         archive_string_ensure(&t->path, size_needed);
2148         /* Add a separating '/' if it's needed. */
2149         if (t->dirname_length > 0 && t->path.s[archive_strlen(&t->path)-1] != '/')
2150                 archive_strappend_char(&t->path, '/');
2151         t->basename = t->path.s + archive_strlen(&t->path);
2152         archive_strncat(&t->path, name, name_length);
2153         t->restore_time.name = t->basename;
2154 }
2155
2156 /*
2157  * Open a directory tree for traversal.
2158  */
2159 static struct tree *
2160 tree_open(const char *path, int symlink_mode, int restore_time)
2161 {
2162         struct tree *t;
2163
2164         if ((t = calloc(1, sizeof(*t))) == NULL)
2165                 return (NULL);
2166         archive_string_init(&t->path);
2167         archive_string_ensure(&t->path, 31);
2168         t->initial_symlink_mode = symlink_mode;
2169         return (tree_reopen(t, path, restore_time));
2170 }
2171
2172 static struct tree *
2173 tree_reopen(struct tree *t, const char *path, int restore_time)
2174 {
2175 #if defined(O_PATH)
2176         /* Linux */
2177         const int o_flag = O_PATH;
2178 #elif defined(O_SEARCH)
2179         /* SunOS */
2180         const int o_flag = O_SEARCH;
2181 #elif defined(__FreeBSD__) && defined(O_EXEC)
2182         /* FreeBSD */
2183         const int o_flag = O_EXEC;
2184 #endif
2185
2186         t->flags = (restore_time != 0)?needsRestoreTimes:0;
2187         t->flags |= onInitialDir;
2188         t->visit_type = 0;
2189         t->tree_errno = 0;
2190         t->dirname_length = 0;
2191         t->depth = 0;
2192         t->descend = 0;
2193         t->current = NULL;
2194         t->d = INVALID_DIR_HANDLE;
2195         t->symlink_mode = t->initial_symlink_mode;
2196         archive_string_empty(&t->path);
2197         t->entry_fd = -1;
2198         t->entry_eof = 0;
2199         t->entry_remaining_bytes = 0;
2200         t->initial_filesystem_id = -1;
2201
2202         /* First item is set up a lot like a symlink traversal. */
2203         tree_push(t, path, 0, 0, 0, NULL);
2204         t->stack->flags = needsFirstVisit;
2205         t->maxOpenCount = t->openCount = 1;
2206         t->initial_dir_fd = open(".", O_RDONLY | O_CLOEXEC);
2207 #if defined(O_PATH) || defined(O_SEARCH) || \
2208  (defined(__FreeBSD__) && defined(O_EXEC))
2209         /*
2210          * Most likely reason to fail opening "." is that it's not readable,
2211          * so try again for execute. The consequences of not opening this are
2212          * unhelpful and unnecessary errors later.
2213          */
2214         if (t->initial_dir_fd < 0)
2215                 t->initial_dir_fd = open(".", o_flag | O_CLOEXEC);
2216 #endif
2217         __archive_ensure_cloexec_flag(t->initial_dir_fd);
2218         t->working_dir_fd = tree_dup(t->initial_dir_fd);
2219         return (t);
2220 }
2221
2222 static int
2223 tree_descent(struct tree *t)
2224 {
2225         int flag, new_fd, r = 0;
2226
2227         t->dirname_length = archive_strlen(&t->path);
2228         flag = O_RDONLY | O_CLOEXEC;
2229 #if defined(O_DIRECTORY)
2230         flag |= O_DIRECTORY;
2231 #endif
2232         new_fd = open_on_current_dir(t, t->stack->name.s, flag);
2233         __archive_ensure_cloexec_flag(new_fd);
2234         if (new_fd < 0) {
2235                 t->tree_errno = errno;
2236                 r = TREE_ERROR_DIR;
2237         } else {
2238                 t->depth++;
2239                 /* If it is a link, set up fd for the ascent. */
2240                 if (t->stack->flags & isDirLink) {
2241                         t->stack->symlink_parent_fd = t->working_dir_fd;
2242                         t->openCount++;
2243                         if (t->openCount > t->maxOpenCount)
2244                                 t->maxOpenCount = t->openCount;
2245                 } else
2246                         close(t->working_dir_fd);
2247                 /* Renew the current working directory. */
2248                 t->working_dir_fd = new_fd;
2249                 t->flags &= ~onWorkingDir;
2250         }
2251         return (r);
2252 }
2253
2254 /*
2255  * We've finished a directory; ascend back to the parent.
2256  */
2257 static int
2258 tree_ascend(struct tree *t)
2259 {
2260         struct tree_entry *te;
2261         int new_fd, r = 0, prev_dir_fd;
2262
2263         te = t->stack;
2264         prev_dir_fd = t->working_dir_fd;
2265         if (te->flags & isDirLink)
2266                 new_fd = te->symlink_parent_fd;
2267         else {
2268                 new_fd = open_on_current_dir(t, "..", O_RDONLY | O_CLOEXEC);
2269                 __archive_ensure_cloexec_flag(new_fd);
2270         }
2271         if (new_fd < 0) {
2272                 t->tree_errno = errno;
2273                 r = TREE_ERROR_FATAL;
2274         } else {
2275                 /* Renew the current working directory. */
2276                 t->working_dir_fd = new_fd;
2277                 t->flags &= ~onWorkingDir;
2278                 /* Current directory has been changed, we should
2279                  * close an fd of previous working directory. */
2280                 close_and_restore_time(prev_dir_fd, t, &te->restore_time);
2281                 if (te->flags & isDirLink) {
2282                         t->openCount--;
2283                         te->symlink_parent_fd = -1;
2284                 }
2285                 t->depth--;
2286         }
2287         return (r);
2288 }
2289
2290 /*
2291  * Return to the initial directory where tree_open() was performed.
2292  */
2293 static int
2294 tree_enter_initial_dir(struct tree *t)
2295 {
2296         int r = 0;
2297
2298         if ((t->flags & onInitialDir) == 0) {
2299                 r = fchdir(t->initial_dir_fd);
2300                 if (r == 0) {
2301                         t->flags &= ~onWorkingDir;
2302                         t->flags |= onInitialDir;
2303                 }
2304         }
2305         return (r);
2306 }
2307
2308 /*
2309  * Restore working directory of directory traversals.
2310  */
2311 static int
2312 tree_enter_working_dir(struct tree *t)
2313 {
2314         int r = 0;
2315
2316         /*
2317          * Change the current directory if really needed.
2318          * Sometimes this is unneeded when we did not do
2319          * descent.
2320          */
2321         if (t->depth > 0 && (t->flags & onWorkingDir) == 0) {
2322                 r = fchdir(t->working_dir_fd);
2323                 if (r == 0) {
2324                         t->flags &= ~onInitialDir;
2325                         t->flags |= onWorkingDir;
2326                 }
2327         }
2328         return (r);
2329 }
2330
2331 static int
2332 tree_current_dir_fd(struct tree *t)
2333 {
2334         return (t->working_dir_fd);
2335 }
2336
2337 /*
2338  * Pop the working stack.
2339  */
2340 static void
2341 tree_pop(struct tree *t)
2342 {
2343         struct tree_entry *te;
2344
2345         t->path.s[t->dirname_length] = '\0';
2346         t->path.length = t->dirname_length;
2347         if (t->stack == t->current && t->current != NULL)
2348                 t->current = t->current->parent;
2349         te = t->stack;
2350         t->stack = te->next;
2351         t->dirname_length = te->dirname_length;
2352         t->basename = t->path.s + t->dirname_length;
2353         while (t->basename[0] == '/')
2354                 t->basename++;
2355         archive_string_free(&te->name);
2356         free(te);
2357 }
2358
2359 /*
2360  * Get the next item in the tree traversal.
2361  */
2362 static int
2363 tree_next(struct tree *t)
2364 {
2365         int r;
2366
2367         while (t->stack != NULL) {
2368                 /* If there's an open dir, get the next entry from there. */
2369                 if (t->d != INVALID_DIR_HANDLE) {
2370                         r = tree_dir_next_posix(t);
2371                         if (r == 0)
2372                                 continue;
2373                         return (r);
2374                 }
2375
2376                 if (t->stack->flags & needsFirstVisit) {
2377                         /* Top stack item needs a regular visit. */
2378                         t->current = t->stack;
2379                         tree_append(t, t->stack->name.s,
2380                             archive_strlen(&(t->stack->name)));
2381                         /* t->dirname_length = t->path_length; */
2382                         /* tree_pop(t); */
2383                         t->stack->flags &= ~needsFirstVisit;
2384                         return (t->visit_type = TREE_REGULAR);
2385                 } else if (t->stack->flags & needsDescent) {
2386                         /* Top stack item is dir to descend into. */
2387                         t->current = t->stack;
2388                         tree_append(t, t->stack->name.s,
2389                             archive_strlen(&(t->stack->name)));
2390                         t->stack->flags &= ~needsDescent;
2391                         r = tree_descent(t);
2392                         if (r != 0) {
2393                                 tree_pop(t);
2394                                 t->visit_type = r;
2395                         } else
2396                                 t->visit_type = TREE_POSTDESCENT;
2397                         return (t->visit_type);
2398                 } else if (t->stack->flags & needsOpen) {
2399                         t->stack->flags &= ~needsOpen;
2400                         r = tree_dir_next_posix(t);
2401                         if (r == 0)
2402                                 continue;
2403                         return (r);
2404                 } else if (t->stack->flags & needsAscent) {
2405                         /* Top stack item is dir and we're done with it. */
2406                         r = tree_ascend(t);
2407                         tree_pop(t);
2408                         t->visit_type = r != 0 ? r : TREE_POSTASCENT;
2409                         return (t->visit_type);
2410                 } else {
2411                         /* Top item on stack is dead. */
2412                         tree_pop(t);
2413                         t->flags &= ~hasLstat;
2414                         t->flags &= ~hasStat;
2415                 }
2416         }
2417         return (t->visit_type = 0);
2418 }
2419
2420 static int
2421 tree_dir_next_posix(struct tree *t)
2422 {
2423         int r;
2424         const char *name;
2425         size_t namelen;
2426
2427         if (t->d == NULL) {
2428 #if defined(USE_READDIR_R)
2429                 size_t dirent_size;
2430 #endif
2431
2432 #if defined(HAVE_FDOPENDIR)
2433                 t->d = fdopendir(tree_dup(t->working_dir_fd));
2434 #else /* HAVE_FDOPENDIR */
2435                 if (tree_enter_working_dir(t) == 0) {
2436                         t->d = opendir(".");
2437 #if HAVE_DIRFD || defined(dirfd)
2438                         __archive_ensure_cloexec_flag(dirfd(t->d));
2439 #endif
2440                 }
2441 #endif /* HAVE_FDOPENDIR */
2442                 if (t->d == NULL) {
2443                         r = tree_ascend(t); /* Undo "chdir" */
2444                         tree_pop(t);
2445                         t->tree_errno = errno;
2446                         t->visit_type = r != 0 ? r : TREE_ERROR_DIR;
2447                         return (t->visit_type);
2448                 }
2449 #if defined(USE_READDIR_R)
2450                 dirent_size = offsetof(struct dirent, d_name) +
2451                   t->filesystem_table[t->current->filesystem_id].name_max + 1;
2452                 if (t->dirent == NULL || t->dirent_allocated < dirent_size) {
2453                         free(t->dirent);
2454                         t->dirent = malloc(dirent_size);
2455                         if (t->dirent == NULL) {
2456                                 closedir(t->d);
2457                                 t->d = INVALID_DIR_HANDLE;
2458                                 (void)tree_ascend(t);
2459                                 tree_pop(t);
2460                                 t->tree_errno = ENOMEM;
2461                                 t->visit_type = TREE_ERROR_DIR;
2462                                 return (t->visit_type);
2463                         }
2464                         t->dirent_allocated = dirent_size;
2465                 }
2466 #endif /* USE_READDIR_R */
2467         }
2468         for (;;) {
2469                 errno = 0;
2470 #if defined(USE_READDIR_R)
2471                 r = readdir_r(t->d, t->dirent, &t->de);
2472 #ifdef _AIX
2473                 /* Note: According to the man page, return value 9 indicates
2474                  * that the readdir_r was not successful and the error code
2475                  * is set to the global errno variable. And then if the end
2476                  * of directory entries was reached, the return value is 9
2477                  * and the third parameter is set to NULL and errno is
2478                  * unchanged. */
2479                 if (r == 9)
2480                         r = errno;
2481 #endif /* _AIX */
2482                 if (r != 0 || t->de == NULL) {
2483 #else
2484                 t->de = readdir(t->d);
2485                 if (t->de == NULL) {
2486                         r = errno;
2487 #endif
2488                         closedir(t->d);
2489                         t->d = INVALID_DIR_HANDLE;
2490                         if (r != 0) {
2491                                 t->tree_errno = r;
2492                                 t->visit_type = TREE_ERROR_DIR;
2493                                 return (t->visit_type);
2494                         } else
2495                                 return (0);
2496                 }
2497                 name = t->de->d_name;
2498                 namelen = D_NAMELEN(t->de);
2499                 t->flags &= ~hasLstat;
2500                 t->flags &= ~hasStat;
2501                 if (name[0] == '.' && name[1] == '\0')
2502                         continue;
2503                 if (name[0] == '.' && name[1] == '.' && name[2] == '\0')
2504                         continue;
2505                 tree_append(t, name, namelen);
2506                 return (t->visit_type = TREE_REGULAR);
2507         }
2508 }
2509
2510
2511 /*
2512  * Get the stat() data for the entry just returned from tree_next().
2513  */
2514 static const struct stat *
2515 tree_current_stat(struct tree *t)
2516 {
2517         if (!(t->flags & hasStat)) {
2518 #ifdef HAVE_FSTATAT
2519                 if (fstatat(tree_current_dir_fd(t),
2520                     tree_current_access_path(t), &t->st, 0) != 0)
2521 #else
2522                 if (tree_enter_working_dir(t) != 0)
2523                         return NULL;
2524                 if (la_stat(tree_current_access_path(t), &t->st) != 0)
2525 #endif
2526                         return NULL;
2527                 t->flags |= hasStat;
2528         }
2529         return (&t->st);
2530 }
2531
2532 /*
2533  * Get the lstat() data for the entry just returned from tree_next().
2534  */
2535 static const struct stat *
2536 tree_current_lstat(struct tree *t)
2537 {
2538         if (!(t->flags & hasLstat)) {
2539 #ifdef HAVE_FSTATAT
2540                 if (fstatat(tree_current_dir_fd(t),
2541                     tree_current_access_path(t), &t->lst,
2542                     AT_SYMLINK_NOFOLLOW) != 0)
2543 #else
2544                 if (tree_enter_working_dir(t) != 0)
2545                         return NULL;
2546                 if (lstat(tree_current_access_path(t), &t->lst) != 0)
2547 #endif
2548                         return NULL;
2549                 t->flags |= hasLstat;
2550         }
2551         return (&t->lst);
2552 }
2553
2554 /*
2555  * Test whether current entry is a dir or link to a dir.
2556  */
2557 static int
2558 tree_current_is_dir(struct tree *t)
2559 {
2560         const struct stat *st;
2561         /*
2562          * If we already have lstat() info, then try some
2563          * cheap tests to determine if this is a dir.
2564          */
2565         if (t->flags & hasLstat) {
2566                 /* If lstat() says it's a dir, it must be a dir. */
2567                 st = tree_current_lstat(t);
2568                 if (st == NULL)
2569                         return 0;
2570                 if (S_ISDIR(st->st_mode))
2571                         return 1;
2572                 /* Not a dir; might be a link to a dir. */
2573                 /* If it's not a link, then it's not a link to a dir. */
2574                 if (!S_ISLNK(st->st_mode))
2575                         return 0;
2576                 /*
2577                  * It's a link, but we don't know what it's a link to,
2578                  * so we'll have to use stat().
2579                  */
2580         }
2581
2582         st = tree_current_stat(t);
2583         /* If we can't stat it, it's not a dir. */
2584         if (st == NULL)
2585                 return 0;
2586         /* Use the definitive test.  Hopefully this is cached. */
2587         return (S_ISDIR(st->st_mode));
2588 }
2589
2590 /*
2591  * Test whether current entry is a physical directory.  Usually, we
2592  * already have at least one of stat() or lstat() in memory, so we
2593  * use tricks to try to avoid an extra trip to the disk.
2594  */
2595 static int
2596 tree_current_is_physical_dir(struct tree *t)
2597 {
2598         const struct stat *st;
2599
2600         /*
2601          * If stat() says it isn't a dir, then it's not a dir.
2602          * If stat() data is cached, this check is free, so do it first.
2603          */
2604         if (t->flags & hasStat) {
2605                 st = tree_current_stat(t);
2606                 if (st == NULL)
2607                         return (0);
2608                 if (!S_ISDIR(st->st_mode))
2609                         return (0);
2610         }
2611
2612         /*
2613          * Either stat() said it was a dir (in which case, we have
2614          * to determine whether it's really a link to a dir) or
2615          * stat() info wasn't available.  So we use lstat(), which
2616          * hopefully is already cached.
2617          */
2618
2619         st = tree_current_lstat(t);
2620         /* If we can't stat it, it's not a dir. */
2621         if (st == NULL)
2622                 return 0;
2623         /* Use the definitive test.  Hopefully this is cached. */
2624         return (S_ISDIR(st->st_mode));
2625 }
2626
2627 /*
2628  * Test whether the same file has been in the tree as its parent.
2629  */
2630 static int
2631 tree_target_is_same_as_parent(struct tree *t, const struct stat *st)
2632 {
2633         struct tree_entry *te;
2634
2635         for (te = t->current->parent; te != NULL; te = te->parent) {
2636                 if (te->dev == (int64_t)st->st_dev &&
2637                     te->ino == (int64_t)st->st_ino)
2638                         return (1);
2639         }
2640         return (0);
2641 }
2642
2643 /*
2644  * Test whether the current file is symbolic link target and
2645  * on the other filesystem.
2646  */
2647 static int
2648 tree_current_is_symblic_link_target(struct tree *t)
2649 {
2650         static const struct stat *lst, *st;
2651
2652         lst = tree_current_lstat(t);
2653         st = tree_current_stat(t);
2654         return (st != NULL && lst != NULL &&
2655             (int64_t)st->st_dev == t->current_filesystem->dev &&
2656             st->st_dev != lst->st_dev);
2657 }
2658
2659 /*
2660  * Return the access path for the entry just returned from tree_next().
2661  */
2662 static const char *
2663 tree_current_access_path(struct tree *t)
2664 {
2665         return (t->basename);
2666 }
2667
2668 /*
2669  * Return the full path for the entry just returned from tree_next().
2670  */
2671 static const char *
2672 tree_current_path(struct tree *t)
2673 {
2674         return (t->path.s);
2675 }
2676
2677 /*
2678  * Terminate the traversal.
2679  */
2680 static void
2681 tree_close(struct tree *t)
2682 {
2683
2684         if (t == NULL)
2685                 return;
2686         if (t->entry_fd >= 0) {
2687                 close_and_restore_time(t->entry_fd, t, &t->restore_time);
2688                 t->entry_fd = -1;
2689         }
2690         /* Close the handle of readdir(). */
2691         if (t->d != INVALID_DIR_HANDLE) {
2692                 closedir(t->d);
2693                 t->d = INVALID_DIR_HANDLE;
2694         }
2695         /* Release anything remaining in the stack. */
2696         while (t->stack != NULL) {
2697                 if (t->stack->flags & isDirLink)
2698                         close(t->stack->symlink_parent_fd);
2699                 tree_pop(t);
2700         }
2701         if (t->working_dir_fd >= 0) {
2702                 close(t->working_dir_fd);
2703                 t->working_dir_fd = -1;
2704         }
2705         if (t->initial_dir_fd >= 0) {
2706                 close(t->initial_dir_fd);
2707                 t->initial_dir_fd = -1;
2708         }
2709 }
2710
2711 /*
2712  * Release any resources.
2713  */
2714 static void
2715 tree_free(struct tree *t)
2716 {
2717         int i;
2718
2719         if (t == NULL)
2720                 return;
2721         archive_string_free(&t->path);
2722 #if defined(USE_READDIR_R)
2723         free(t->dirent);
2724 #endif
2725         free(t->sparse_list);
2726         for (i = 0; i < t->max_filesystem_id; i++)
2727                 free(t->filesystem_table[i].allocation_ptr);
2728         free(t->filesystem_table);
2729         free(t);
2730 }
2731
2732 #endif