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