Import libarchive-3.0.3.
[dragonfly.git] / contrib / libarchive / tar / tree.c
1 /*-
2  * Copyright (c) 2003-2007 Tim Kientzle
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR(S) ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
16  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
17  * IN NO EVENT SHALL THE AUTHOR(S) BE LIABLE FOR ANY DIRECT, INDIRECT,
18  * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
19  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
20  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
21
22  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
23  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
24  * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25  */
26
27 /*-
28  * This is a new directory-walking system that addresses a number
29  * of problems I've had with fts(3).  In particular, it has no
30  * pathname-length limits (other than the size of 'int'), handles
31  * deep logical traversals, uses considerably less memory, and has
32  * an opaque interface (easier to modify in the future).
33  *
34  * Internally, it keeps a single list of "tree_entry" items that
35  * represent filesystem objects that require further attention.
36  * Non-directories are not kept in memory: they are pulled from
37  * readdir(), returned to the client, then freed as soon as possible.
38  * Any directory entry to be traversed gets pushed onto the stack.
39  *
40  * There is surprisingly little information that needs to be kept for
41  * each item on the stack.  Just the name, depth (represented here as the
42  * string length of the parent directory's pathname), and some markers
43  * indicating how to get back to the parent (via chdir("..") for a
44  * regular dir or via fchdir(2) for a symlink).
45  */
46 #include "bsdtar_platform.h"
47 __FBSDID("$FreeBSD: src/usr.bin/tar/tree.c,v 1.9 2008/11/27 05:49:52 kientzle Exp $");
48
49 #ifdef HAVE_SYS_STAT_H
50 #include <sys/stat.h>
51 #endif
52 #ifdef HAVE_DIRECT_H
53 #include <direct.h>
54 #endif
55 #ifdef HAVE_DIRENT_H
56 #include <dirent.h>
57 #endif
58 #ifdef HAVE_ERRNO_H
59 #include <errno.h>
60 #endif
61 #ifdef HAVE_FCNTL_H
62 #include <fcntl.h>
63 #endif
64 #ifdef HAVE_STDLIB_H
65 #include <stdlib.h>
66 #endif
67 #ifdef HAVE_STRING_H
68 #include <string.h>
69 #endif
70 #ifdef HAVE_UNISTD_H
71 #include <unistd.h>
72 #endif
73 #if defined(HAVE_WINDOWS_H) && !defined(__CYGWIN__)
74 #include <windows.h>
75 #endif
76
77 #include "tree.h"
78
79 /*
80  * TODO:
81  *    1) Loop checking.
82  *    3) Arbitrary logical traversals by closing/reopening intermediate fds.
83  */
84
85 struct tree_entry {
86         int depth;
87         struct tree_entry *next;
88         struct tree_entry *parent;
89         char *name;
90         size_t dirname_length;
91         dev_t dev;
92         ino_t ino;
93         int flags;
94         /* How to return back to the parent of a symlink. */
95 #ifdef HAVE_FCHDIR
96         int symlink_parent_fd;
97 #elif defined(_WIN32) && !defined(__CYGWIN__)
98         char *symlink_parent_path;
99 #else
100 #error fchdir function required.
101 #endif
102 };
103
104 /* Definitions for tree_entry.flags bitmap. */
105 #define isDir 1 /* This entry is a regular directory. */
106 #define isDirLink 2 /* This entry is a symbolic link to a directory. */
107 #define needsFirstVisit 4 /* This is an initial entry. */
108 #define needsDescent 8 /* This entry needs to be previsited. */
109 #define needsOpen 16 /* This is a directory that needs to be opened. */
110 #define needsAscent 32 /* This entry needs to be postvisited. */
111
112 /*
113  * On Windows, "first visit" is handled as a pattern to be handed to
114  * _findfirst().  This is consistent with Windows conventions that
115  * file patterns are handled within the application.  On Posix,
116  * "first visit" is just returned to the client.
117  */
118
119 /*
120  * Local data for this package.
121  */
122 struct tree {
123         struct tree_entry       *stack;
124         struct tree_entry       *current;
125 #if defined(_WIN32) && !defined(__CYGWIN__)
126         HANDLE d;
127         BY_HANDLE_FILE_INFORMATION fileInfo;
128 #define INVALID_DIR_HANDLE INVALID_HANDLE_VALUE
129         WIN32_FIND_DATA _findData;
130         WIN32_FIND_DATA *findData;
131 #else
132         DIR     *d;
133 #define INVALID_DIR_HANDLE NULL
134         struct dirent *de;
135 #endif
136         int      flags;
137         int      visit_type;
138         int      tree_errno; /* Error code from last failed operation. */
139
140         /* Dynamically-sized buffer for holding path */
141         char    *buff;
142         size_t   buff_length;
143
144         const char *basename; /* Last path element */
145         size_t   dirname_length; /* Leading dir length */
146         size_t   path_length; /* Total path length */
147
148         int      depth;
149         int      openCount;
150         int      maxOpenCount;
151
152         struct stat     lst;
153         struct stat     st;
154 };
155
156 /* Definitions for tree.flags bitmap. */
157 #define hasStat 16  /* The st entry is valid. */
158 #define hasLstat 32 /* The lst entry is valid. */
159 #define hasFileInfo 64 /* The Windows fileInfo entry is valid. */
160
161 #if defined(_WIN32) && !defined(__CYGWIN__)
162 static int
163 tree_dir_next_windows(struct tree *t, const char *pattern);
164 #else
165 static int
166 tree_dir_next_posix(struct tree *t);
167 #endif
168
169 #ifdef HAVE_DIRENT_D_NAMLEN
170 /* BSD extension; avoids need for a strlen() call. */
171 #define D_NAMELEN(dp)   (dp)->d_namlen
172 #else
173 #define D_NAMELEN(dp)   (strlen((dp)->d_name))
174 #endif
175
176 #include <stdio.h>
177 void
178 tree_dump(struct tree *t, FILE *out)
179 {
180         char buff[300];
181         struct tree_entry *te;
182
183         fprintf(out, "\tdepth: %d\n", t->depth);
184         fprintf(out, "\tbuff: %s\n", t->buff);
185         fprintf(out, "\tpwd: %s\n", getcwd(buff, sizeof(buff)));
186         fprintf(out, "\tbasename: %s\n", t->basename);
187         fprintf(out, "\tstack:\n");
188         for (te = t->stack; te != NULL; te = te->next) {
189                 fprintf(out, "\t\t%s%d:\"%s\" %s%s%s%s%s%s\n",
190                     t->current == te ? "*" : " ",
191                     te->depth,
192                     te->name,
193                     te->flags & needsFirstVisit ? "V" : "",
194                     te->flags & needsDescent ? "D" : "",
195                     te->flags & needsOpen ? "O" : "",
196                     te->flags & needsAscent ? "A" : "",
197                     te->flags & isDirLink ? "L" : "",
198                     (t->current == te && t->d) ? "+" : ""
199                 );
200         }
201 }
202
203 /*
204  * Add a directory path to the current stack.
205  */
206 static void
207 tree_push(struct tree *t, const char *path)
208 {
209         struct tree_entry *te;
210
211         te = malloc(sizeof(*te));
212         memset(te, 0, sizeof(*te));
213         te->next = t->stack;
214         te->parent = t->current;
215         if (te->parent)
216                 te->depth = te->parent->depth + 1;
217         t->stack = te;
218 #ifdef HAVE_FCHDIR
219         te->symlink_parent_fd = -1;
220         te->name = strdup(path);
221 #elif defined(_WIN32) && !defined(__CYGWIN__)
222         te->symlink_parent_path = NULL;
223         te->name = strdup(path);
224 #endif
225         te->flags = needsDescent | needsOpen | needsAscent;
226         te->dirname_length = t->dirname_length;
227 }
228
229 /*
230  * Append a name to the current dir path.
231  */
232 static void
233 tree_append(struct tree *t, const char *name, size_t name_length)
234 {
235         char *p;
236         size_t size_needed;
237
238         if (t->buff != NULL)
239                 t->buff[t->dirname_length] = '\0';
240         /* Strip trailing '/' from name, unless entire name is "/". */
241         while (name_length > 1 && name[name_length - 1] == '/')
242                 name_length--;
243
244         /* Resize pathname buffer as needed. */
245         size_needed = name_length + 1 + t->dirname_length;
246         if (t->buff_length < size_needed) {
247                 if (t->buff_length < 1024)
248                         t->buff_length = 1024;
249                 while (t->buff_length < size_needed)
250                         t->buff_length *= 2;
251                 t->buff = realloc(t->buff, t->buff_length);
252         }
253         if (t->buff == NULL)
254                 abort();
255         p = t->buff + t->dirname_length;
256         t->path_length = t->dirname_length + name_length;
257         /* Add a separating '/' if it's needed. */
258         if (t->dirname_length > 0 && p[-1] != '/') {
259                 *p++ = '/';
260                 t->path_length ++;
261         }
262 #if HAVE_STRNCPY_S
263         strncpy_s(p, t->buff_length - (p - t->buff), name, name_length);
264 #else
265         strncpy(p, name, name_length);
266 #endif
267         p[name_length] = '\0';
268         t->basename = p;
269 }
270
271 /*
272  * Open a directory tree for traversal.
273  */
274 struct tree *
275 tree_open(const char *path)
276 {
277 #ifdef HAVE_FCHDIR
278         struct tree *t;
279
280         t = malloc(sizeof(*t));
281         memset(t, 0, sizeof(*t));
282         /* First item is set up a lot like a symlink traversal. */
283         tree_push(t, path);
284         t->stack->flags = needsFirstVisit | isDirLink | needsAscent;
285         t->stack->symlink_parent_fd = open(".", O_RDONLY);
286         t->openCount++;
287         t->d = INVALID_DIR_HANDLE;
288         return (t);
289 #elif defined(_WIN32) && !defined(__CYGWIN__)
290         struct tree *t;
291         char *cwd = _getcwd(NULL, 0);
292         char *pathname, *p, *base;
293         wchar_t *wcs, *wp;
294         size_t l, wlen;
295
296         /* Take care of '\' character in multi-byte character-set.
297          * Some multi-byte character-set have been using '\' character
298          * for a part of its character code. */
299         l = MultiByteToWideChar(CP_OEMCP, 0, path, strlen(path), NULL, 0);
300         if (l == 0)
301                 abort();
302         wcs = malloc(sizeof(*wcs) * (l+1));
303         if (wcs == NULL)
304                 abort();
305         l = MultiByteToWideChar(CP_OEMCP, 0, path, strlen(path), wcs, l);
306         wcs[l] = L'\0';
307         wlen = l;
308         for (wp = wcs; *wp != L'\0'; ++wp) {
309                 if (*wp == L'\\')
310                         *wp = L'/';
311         }
312         l = WideCharToMultiByte(CP_OEMCP, 0, wcs, wlen, NULL, 0, NULL, NULL);
313         if (l == 0)
314                 abort();
315         pathname = malloc(l+1);
316         if (pathname == NULL)
317                 abort();
318         l = WideCharToMultiByte(CP_OEMCP, 0, wcs, wlen, pathname, l, NULL, NULL);
319         pathname[l] = '\0';
320         free(wcs);
321         base = pathname;
322 #if defined(_WIN32) && !defined(__CYGWIN__)
323         /* ASCII version APIs do not accept the path which begin with
324          * "//?/" prefix. */
325         if (strncmp(base, "//?/", 4) == 0)
326                 base += 4;
327 #endif
328
329         t = malloc(sizeof(*t));
330         memset(t, 0, sizeof(*t));
331         /* First item is set up a lot like a symlink traversal. */
332         /* printf("Looking for wildcard in %s\n", path); */
333         /* TODO: wildcard detection here screws up on \\?\c:\ UNC names */
334         if (strchr(base, '*') || strchr(base, '?')) {
335                 /* It has a wildcard in it... */
336                 /* Separate the last element. */
337                 p = strrchr(base, '/');
338                 if (p != NULL) {
339                         *p = '\0';
340                         chdir(base);
341                         tree_append(t, base, p - base);
342                         t->dirname_length = t->path_length;
343                         base = p + 1;
344                 }
345         }
346         tree_push(t, base);
347         free(pathname);
348         t->stack->flags = needsFirstVisit | isDirLink | needsAscent;
349         t->stack->symlink_parent_path = cwd;
350         t->d = INVALID_DIR_HANDLE;
351         return (t);
352 #endif
353 }
354
355 /*
356  * We've finished a directory; ascend back to the parent.
357  */
358 static int
359 tree_ascend(struct tree *t)
360 {
361         struct tree_entry *te;
362         int r = 0;
363
364         te = t->stack;
365         t->depth--;
366         if (te->flags & isDirLink) {
367 #ifdef HAVE_FCHDIR
368                 if (fchdir(te->symlink_parent_fd) != 0) {
369                         t->tree_errno = errno;
370                         r = TREE_ERROR_FATAL;
371                 }
372                 close(te->symlink_parent_fd);
373 #elif defined(_WIN32) && !defined(__CYGWIN__)
374                 if (SetCurrentDirectory(te->symlink_parent_path) == 0) {
375                         t->tree_errno = errno;
376                         r = TREE_ERROR_FATAL;
377                 }
378                 free(te->symlink_parent_path);
379                 te->symlink_parent_path = NULL;
380 #endif
381                 t->openCount--;
382         } else {
383 #if defined(_WIN32) && !defined(__CYGWIN__)
384                 if (SetCurrentDirectory("..") == 0) {
385 #else
386                 if (chdir("..") != 0) {
387 #endif
388                         t->tree_errno = errno;
389                         r = TREE_ERROR_FATAL;
390                 }
391         }
392         return (r);
393 }
394
395 /*
396  * Pop the working stack.
397  */
398 static void
399 tree_pop(struct tree *t)
400 {
401         struct tree_entry *te;
402
403         if (t->buff)
404                 t->buff[t->dirname_length] = '\0';
405         if (t->stack == t->current && t->current != NULL)
406                 t->current = t->current->parent;
407         te = t->stack;
408         t->stack = te->next;
409         t->dirname_length = te->dirname_length;
410         if (t->buff) {
411                 t->basename = t->buff + t->dirname_length;
412                 while (t->basename[0] == '/')
413                         t->basename++;
414         }
415         free(te->name);
416         free(te);
417 }
418
419 /*
420  * Get the next item in the tree traversal.
421  */
422 int
423 tree_next(struct tree *t)
424 {
425         int r;
426
427         /* If we're called again after a fatal error, that's an API
428          * violation.  Just crash now. */
429         if (t->visit_type == TREE_ERROR_FATAL) {
430                 fprintf(stderr, "Unable to continue traversing"
431                     " directory hierarchy after a fatal error.");
432                 abort();
433         }
434
435         while (t->stack != NULL) {
436                 /* If there's an open dir, get the next entry from there. */
437                 if (t->d != INVALID_DIR_HANDLE) {
438 #if defined(_WIN32) && !defined(__CYGWIN__)
439                         r = tree_dir_next_windows(t, NULL);
440 #else
441                         r = tree_dir_next_posix(t);
442 #endif
443                         if (r == 0)
444                                 continue;
445                         return (r);
446                 }
447
448                 if (t->stack->flags & needsFirstVisit) {
449 #if defined(_WIN32) && !defined(__CYGWIN__)
450                         char *d = t->stack->name;
451                         t->stack->flags &= ~needsFirstVisit;
452                         if (strchr(d, '*') || strchr(d, '?')) {
453                                 r = tree_dir_next_windows(t, d);
454                                 if (r == 0)
455                                         continue;
456                                 return (r);
457                         }
458                         /* Not a pattern, handle it as-is... */
459 #endif
460                         /* Top stack item needs a regular visit. */
461                         t->current = t->stack;
462                         tree_append(t, t->stack->name, strlen(t->stack->name));
463                         /* t->dirname_length = t->path_length; */
464                         /* tree_pop(t); */
465                         t->stack->flags &= ~needsFirstVisit;
466                         return (t->visit_type = TREE_REGULAR);
467                 } else if (t->stack->flags & needsDescent) {
468                         /* Top stack item is dir to descend into. */
469                         t->current = t->stack;
470                         tree_append(t, t->stack->name, strlen(t->stack->name));
471                         t->stack->flags &= ~needsDescent;
472                         /* If it is a link, set up fd for the ascent. */
473                         if (t->stack->flags & isDirLink) {
474 #ifdef HAVE_FCHDIR
475                                 t->stack->symlink_parent_fd = open(".", O_RDONLY);
476                                 t->openCount++;
477                                 if (t->openCount > t->maxOpenCount)
478                                         t->maxOpenCount = t->openCount;
479 #elif defined(_WIN32) && !defined(__CYGWIN__)
480                                 t->stack->symlink_parent_path = _getcwd(NULL, 0);
481 #endif
482                         }
483                         t->dirname_length = t->path_length;
484 #if defined(_WIN32) && !defined(__CYGWIN__)
485                         if (t->path_length == 259 || !SetCurrentDirectory(t->stack->name) != 0)
486 #else
487                         if (chdir(t->stack->name) != 0)
488 #endif
489                         {
490                                 /* chdir() failed; return error */
491                                 tree_pop(t);
492                                 t->tree_errno = errno;
493                                 return (t->visit_type = TREE_ERROR_DIR);
494                         }
495                         t->depth++;
496                         return (t->visit_type = TREE_POSTDESCENT);
497                 } else if (t->stack->flags & needsOpen) {
498                         t->stack->flags &= ~needsOpen;
499 #if defined(_WIN32) && !defined(__CYGWIN__)
500                         r = tree_dir_next_windows(t, "*");
501 #else
502                         r = tree_dir_next_posix(t);
503 #endif
504                         if (r == 0)
505                                 continue;
506                         return (r);
507                 } else if (t->stack->flags & needsAscent) {
508                         /* Top stack item is dir and we're done with it. */
509                         r = tree_ascend(t);
510                         tree_pop(t);
511                         t->visit_type = r != 0 ? r : TREE_POSTASCENT;
512                         return (t->visit_type);
513                 } else {
514                         /* Top item on stack is dead. */
515                         tree_pop(t);
516                         t->flags &= ~hasLstat;
517                         t->flags &= ~hasStat;
518                 }
519         }
520         return (t->visit_type = 0);
521 }
522
523 #if defined(_WIN32) && !defined(__CYGWIN__)
524 static int
525 tree_dir_next_windows(struct tree *t, const char *pattern)
526 {
527         const char *name;
528         size_t namelen;
529         int r;
530
531         for (;;) {
532                 if (pattern != NULL) {
533                         t->d = FindFirstFile(pattern, &t->_findData);
534                         if (t->d == INVALID_DIR_HANDLE) {
535                                 r = tree_ascend(t); /* Undo "chdir" */
536                                 tree_pop(t);
537                                 t->tree_errno = errno;
538                                 t->visit_type = r != 0 ? r : TREE_ERROR_DIR;
539                                 return (t->visit_type);
540                         }
541                         t->findData = &t->_findData;
542                         pattern = NULL;
543                 } else if (!FindNextFile(t->d, &t->_findData)) {
544                         FindClose(t->d);
545                         t->d = INVALID_DIR_HANDLE;
546                         t->findData = NULL;
547                         return (0);
548                 }
549                 name = t->findData->cFileName;
550                 namelen = strlen(name);
551                 t->flags &= ~hasLstat;
552                 t->flags &= ~hasStat;
553                 if (name[0] == '.' && name[1] == '\0')
554                         continue;
555                 if (name[0] == '.' && name[1] == '.' && name[2] == '\0')
556                         continue;
557                 tree_append(t, name, namelen);
558                 return (t->visit_type = TREE_REGULAR);
559         }
560 }
561 #else
562 static int
563 tree_dir_next_posix(struct tree *t)
564 {
565         int r;
566         const char *name;
567         size_t namelen;
568
569         if (t->d == NULL) {
570                 if ((t->d = opendir(".")) == NULL) {
571                         r = tree_ascend(t); /* Undo "chdir" */
572                         tree_pop(t);
573                         t->tree_errno = errno;
574                         t->visit_type = r != 0 ? r : TREE_ERROR_DIR;
575                         return (t->visit_type);
576                 }
577         }
578         for (;;) {
579                 t->de = readdir(t->d);
580                 if (t->de == NULL) {
581                         closedir(t->d);
582                         t->d = INVALID_DIR_HANDLE;
583                         return (0);
584                 }
585                 name = t->de->d_name;
586                 namelen = D_NAMELEN(t->de);
587                 t->flags &= ~hasLstat;
588                 t->flags &= ~hasStat;
589                 if (name[0] == '.' && name[1] == '\0')
590                         continue;
591                 if (name[0] == '.' && name[1] == '.' && name[2] == '\0')
592                         continue;
593                 tree_append(t, name, namelen);
594                 return (t->visit_type = TREE_REGULAR);
595         }
596 }
597 #endif
598
599 /*
600  * Return error code.
601  */
602 int
603 tree_errno(struct tree *t)
604 {
605         return (t->tree_errno);
606 }
607
608 /*
609  * Called by the client to mark the directory just returned from
610  * tree_next() as needing to be visited.
611  */
612 void
613 tree_descend(struct tree *t)
614 {
615         if (t->visit_type != TREE_REGULAR)
616                 return;
617
618         if (tree_current_is_physical_dir(t)) {
619                 tree_push(t, t->basename);
620                 t->stack->flags |= isDir;
621         } else if (tree_current_is_dir(t)) {
622                 tree_push(t, t->basename);
623                 t->stack->flags |= isDirLink;
624         }
625 }
626
627 /*
628  * Get the stat() data for the entry just returned from tree_next().
629  */
630 const struct stat *
631 tree_current_stat(struct tree *t)
632 {
633         if (!(t->flags & hasStat)) {
634                 if (stat(tree_current_access_path(t), &t->st) != 0)
635                         return NULL;
636                 t->flags |= hasStat;
637         }
638         return (&t->st);
639 }
640
641 #if defined(_WIN32) && !defined(__CYGWIN__)
642 const BY_HANDLE_FILE_INFORMATION *
643 tree_current_file_information(struct tree *t)
644 {
645         if (!(t->flags & hasFileInfo)) {
646                 HANDLE h = CreateFile(tree_current_access_path(t),
647                         0, 0, NULL,
648                         OPEN_EXISTING,
649                         FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
650                         NULL);
651                 if (h == INVALID_HANDLE_VALUE)
652                         return NULL;
653                 if (!GetFileInformationByHandle(h, &t->fileInfo)) {
654                         CloseHandle(h);
655                         return NULL;
656                 }
657                 CloseHandle(h);
658                 t->flags |= hasFileInfo;
659         }
660         return (&t->fileInfo);
661 }
662 #endif
663 /*
664  * Get the lstat() data for the entry just returned from tree_next().
665  */
666 const struct stat *
667 tree_current_lstat(struct tree *t)
668 {
669 #if defined(_WIN32) && !defined(__CYGWIN__)
670         return (tree_current_stat(t));
671 #else
672         if (!(t->flags & hasLstat)) {
673                 if (lstat(tree_current_access_path(t), &t->lst) != 0)
674                         return NULL;
675                 t->flags |= hasLstat;
676         }
677         return (&t->lst);
678 #endif
679 }
680
681 /*
682  * Test whether current entry is a dir or link to a dir.
683  */
684 int
685 tree_current_is_dir(struct tree *t)
686 {
687 #if defined(_WIN32) && !defined(__CYGWIN__)
688         if (t->findData)
689                 return (t->findData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
690         if (tree_current_file_information(t))
691                 return (t->fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
692         return (0);
693 #else
694         const struct stat *st;
695         /*
696          * If we already have lstat() info, then try some
697          * cheap tests to determine if this is a dir.
698          */
699         if (t->flags & hasLstat) {
700                 /* If lstat() says it's a dir, it must be a dir. */
701                 if (S_ISDIR(tree_current_lstat(t)->st_mode))
702                         return 1;
703                 /* Not a dir; might be a link to a dir. */
704                 /* If it's not a link, then it's not a link to a dir. */
705                 if (!S_ISLNK(tree_current_lstat(t)->st_mode))
706                         return 0;
707                 /*
708                  * It's a link, but we don't know what it's a link to,
709                  * so we'll have to use stat().
710                  */
711         }
712
713         st = tree_current_stat(t);
714         /* If we can't stat it, it's not a dir. */
715         if (st == NULL)
716                 return 0;
717         /* Use the definitive test.  Hopefully this is cached. */
718         return (S_ISDIR(st->st_mode));
719 #endif
720 }
721
722 /*
723  * Test whether current entry is a physical directory.  Usually, we
724  * already have at least one of stat() or lstat() in memory, so we
725  * use tricks to try to avoid an extra trip to the disk.
726  */
727 int
728 tree_current_is_physical_dir(struct tree *t)
729 {
730 #if defined(_WIN32) && !defined(__CYGWIN__)
731         if (tree_current_is_physical_link(t))
732                 return (0);
733         return (tree_current_is_dir(t));
734 #else
735         const struct stat *st;
736
737         /*
738          * If stat() says it isn't a dir, then it's not a dir.
739          * If stat() data is cached, this check is free, so do it first.
740          */
741         if ((t->flags & hasStat)
742             && (!S_ISDIR(tree_current_stat(t)->st_mode)))
743                 return 0;
744
745         /*
746          * Either stat() said it was a dir (in which case, we have
747          * to determine whether it's really a link to a dir) or
748          * stat() info wasn't available.  So we use lstat(), which
749          * hopefully is already cached.
750          */
751
752         st = tree_current_lstat(t);
753         /* If we can't stat it, it's not a dir. */
754         if (st == NULL)
755                 return 0;
756         /* Use the definitive test.  Hopefully this is cached. */
757         return (S_ISDIR(st->st_mode));
758 #endif
759 }
760
761 /*
762  * Test whether current entry is a symbolic link.
763  */
764 int
765 tree_current_is_physical_link(struct tree *t)
766 {
767 #if defined(_WIN32) && !defined(__CYGWIN__)
768 #ifndef IO_REPARSE_TAG_SYMLINK
769 /* Old SDKs do not provide IO_REPARSE_TAG_SYMLINK */
770 #define IO_REPARSE_TAG_SYMLINK 0xA000000CL
771 #endif
772         if (t->findData)
773                 return ((t->findData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
774                                 && (t->findData->dwReserved0 == IO_REPARSE_TAG_SYMLINK));
775         return (0);
776 #else
777         const struct stat *st = tree_current_lstat(t);
778         if (st == NULL)
779                 return 0;
780         return (S_ISLNK(st->st_mode));
781 #endif
782 }
783
784 /*
785  * Return the access path for the entry just returned from tree_next().
786  */
787 const char *
788 tree_current_access_path(struct tree *t)
789 {
790         return (t->basename);
791 }
792
793 /*
794  * Return the full path for the entry just returned from tree_next().
795  */
796 const char *
797 tree_current_path(struct tree *t)
798 {
799         return (t->buff);
800 }
801
802 /*
803  * Return the length of the path for the entry just returned from tree_next().
804  */
805 size_t
806 tree_current_pathlen(struct tree *t)
807 {
808         return (t->path_length);
809 }
810
811 /*
812  * Return the nesting depth of the entry just returned from tree_next().
813  */
814 int
815 tree_current_depth(struct tree *t)
816 {
817         return (t->depth);
818 }
819
820 /*
821  * Terminate the traversal and release any resources.
822  */
823 void
824 tree_close(struct tree *t)
825 {
826         /* Release anything remaining in the stack. */
827         while (t->stack != NULL)
828                 tree_pop(t);
829         free(t->buff);
830         /* TODO: Ensure that premature close() resets cwd */
831 #if 0
832 #ifdef HAVE_FCHDIR
833         if (t->initialDirFd >= 0) {
834                 int s = fchdir(t->initialDirFd);
835                 (void)s; /* UNUSED */
836                 close(t->initialDirFd);
837                 t->initialDirFd = -1;
838         }
839 #elif defined(_WIN32) && !defined(__CYGWIN__)
840         if (t->initialDir != NULL) {
841                 SetCurrentDir(t->initialDir);
842                 free(t->initialDir);
843                 t->initialDir = NULL;
844         }
845 #endif
846 #endif
847         free(t);
848 }