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