2 * Copyright (c) 2003-2007 Tim Kientzle
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
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.
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
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.
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).
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.
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).
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 $");
49 #ifdef HAVE_SYS_STAT_H
73 #if defined(HAVE_WINDOWS_H) && !defined(__CYGWIN__)
82 * 3) Arbitrary logical traversals by closing/reopening intermediate fds.
87 struct tree_entry *next;
88 struct tree_entry *parent;
90 size_t dirname_length;
94 /* How to return back to the parent of a symlink. */
96 int symlink_parent_fd;
97 #elif defined(_WIN32) && !defined(__CYGWIN__)
98 char *symlink_parent_path;
100 #error fchdir function required.
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. */
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.
120 * Local data for this package.
123 struct tree_entry *stack;
124 struct tree_entry *current;
125 #if defined(_WIN32) && !defined(__CYGWIN__)
127 BY_HANDLE_FILE_INFORMATION fileInfo;
128 #define INVALID_DIR_HANDLE INVALID_HANDLE_VALUE
129 WIN32_FIND_DATA _findData;
130 WIN32_FIND_DATA *findData;
133 #define INVALID_DIR_HANDLE NULL
138 int tree_errno; /* Error code from last failed operation. */
140 /* Dynamically-sized buffer for holding path */
144 const char *basename; /* Last path element */
145 size_t dirname_length; /* Leading dir length */
146 size_t path_length; /* Total path length */
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. */
161 #if defined(_WIN32) && !defined(__CYGWIN__)
163 tree_dir_next_windows(struct tree *t, const char *pattern);
166 tree_dir_next_posix(struct tree *t);
169 #ifdef HAVE_DIRENT_D_NAMLEN
170 /* BSD extension; avoids need for a strlen() call. */
171 #define D_NAMELEN(dp) (dp)->d_namlen
173 #define D_NAMELEN(dp) (strlen((dp)->d_name))
178 tree_dump(struct tree *t, FILE *out)
181 struct tree_entry *te;
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 ? "*" : " ",
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) ? "+" : ""
204 * Add a directory path to the current stack.
207 tree_push(struct tree *t, const char *path)
209 struct tree_entry *te;
211 te = malloc(sizeof(*te));
212 memset(te, 0, sizeof(*te));
214 te->parent = t->current;
216 te->depth = te->parent->depth + 1;
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);
225 te->flags = needsDescent | needsOpen | needsAscent;
226 te->dirname_length = t->dirname_length;
230 * Append a name to the current dir path.
233 tree_append(struct tree *t, const char *name, size_t name_length)
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] == '/')
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)
251 t->buff = realloc(t->buff, t->buff_length);
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] != '/') {
263 strncpy_s(p, t->buff_length - (p - t->buff), name, name_length);
265 strncpy(p, name, name_length);
267 p[name_length] = '\0';
272 * Open a directory tree for traversal.
275 tree_open(const char *path)
280 t = malloc(sizeof(*t));
281 memset(t, 0, sizeof(*t));
282 /* First item is set up a lot like a symlink traversal. */
284 t->stack->flags = needsFirstVisit | isDirLink | needsAscent;
285 t->stack->symlink_parent_fd = open(".", O_RDONLY);
287 t->d = INVALID_DIR_HANDLE;
289 #elif defined(_WIN32) && !defined(__CYGWIN__)
291 char *cwd = _getcwd(NULL, 0);
292 char *pathname, *p, *base;
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);
302 wcs = malloc(sizeof(*wcs) * (l+1));
305 l = MultiByteToWideChar(CP_OEMCP, 0, path, strlen(path), wcs, l);
308 for (wp = wcs; *wp != L'\0'; ++wp) {
312 l = WideCharToMultiByte(CP_OEMCP, 0, wcs, wlen, NULL, 0, NULL, NULL);
315 pathname = malloc(l+1);
316 if (pathname == NULL)
318 l = WideCharToMultiByte(CP_OEMCP, 0, wcs, wlen, pathname, l, NULL, NULL);
323 t = malloc(sizeof(*t));
324 memset(t, 0, sizeof(*t));
325 /* First item is set up a lot like a symlink traversal. */
326 /* printf("Looking for wildcard in %s\n", path); */
327 /* TODO: wildcard detection here screws up on \\?\c:\ UNC names */
328 if (strchr(base, '*') || strchr(base, '?')) {
329 /* It has a wildcard in it... */
330 /* Separate the last element. */
331 p = strrchr(base, '/');
335 tree_append(t, base, p - base);
336 t->dirname_length = t->path_length;
342 t->stack->flags = needsFirstVisit | isDirLink | needsAscent;
343 t->stack->symlink_parent_path = cwd;
344 t->d = INVALID_DIR_HANDLE;
350 * We've finished a directory; ascend back to the parent.
353 tree_ascend(struct tree *t)
355 struct tree_entry *te;
360 if (te->flags & isDirLink) {
362 if (fchdir(te->symlink_parent_fd) != 0) {
363 t->tree_errno = errno;
364 r = TREE_ERROR_FATAL;
366 close(te->symlink_parent_fd);
367 #elif defined(_WIN32) && !defined(__CYGWIN__)
368 if (SetCurrentDirectory(te->symlink_parent_path) == 0) {
369 t->tree_errno = errno;
370 r = TREE_ERROR_FATAL;
372 free(te->symlink_parent_path);
373 te->symlink_parent_path = NULL;
377 #if defined(_WIN32) && !defined(__CYGWIN__)
378 if (SetCurrentDirectory("..") == 0) {
380 if (chdir("..") != 0) {
382 t->tree_errno = errno;
383 r = TREE_ERROR_FATAL;
390 * Pop the working stack.
393 tree_pop(struct tree *t)
395 struct tree_entry *te;
398 t->buff[t->dirname_length] = '\0';
399 if (t->stack == t->current && t->current != NULL)
400 t->current = t->current->parent;
403 t->dirname_length = te->dirname_length;
405 t->basename = t->buff + t->dirname_length;
406 while (t->basename[0] == '/')
414 * Get the next item in the tree traversal.
417 tree_next(struct tree *t)
421 /* If we're called again after a fatal error, that's an API
422 * violation. Just crash now. */
423 if (t->visit_type == TREE_ERROR_FATAL) {
424 fprintf(stderr, "Unable to continue traversing"
425 " directory hierarchy after a fatal error.");
429 while (t->stack != NULL) {
430 /* If there's an open dir, get the next entry from there. */
431 if (t->d != INVALID_DIR_HANDLE) {
432 #if defined(_WIN32) && !defined(__CYGWIN__)
433 r = tree_dir_next_windows(t, NULL);
435 r = tree_dir_next_posix(t);
442 if (t->stack->flags & needsFirstVisit) {
443 #if defined(_WIN32) && !defined(__CYGWIN__)
444 char *d = t->stack->name;
445 t->stack->flags &= ~needsFirstVisit;
446 if (strchr(d, '*') || strchr(d, '?')) {
447 r = tree_dir_next_windows(t, d);
452 /* Not a pattern, handle it as-is... */
454 /* Top stack item needs a regular visit. */
455 t->current = t->stack;
456 tree_append(t, t->stack->name, strlen(t->stack->name));
457 /* t->dirname_length = t->path_length; */
459 t->stack->flags &= ~needsFirstVisit;
460 return (t->visit_type = TREE_REGULAR);
461 } else if (t->stack->flags & needsDescent) {
462 /* Top stack item is dir to descend into. */
463 t->current = t->stack;
464 tree_append(t, t->stack->name, strlen(t->stack->name));
465 t->stack->flags &= ~needsDescent;
466 /* If it is a link, set up fd for the ascent. */
467 if (t->stack->flags & isDirLink) {
469 t->stack->symlink_parent_fd = open(".", O_RDONLY);
471 if (t->openCount > t->maxOpenCount)
472 t->maxOpenCount = t->openCount;
473 #elif defined(_WIN32) && !defined(__CYGWIN__)
474 t->stack->symlink_parent_path = _getcwd(NULL, 0);
477 t->dirname_length = t->path_length;
478 #if defined(_WIN32) && !defined(__CYGWIN__)
479 if (t->path_length == 259 || !SetCurrentDirectory(t->stack->name) != 0)
481 if (chdir(t->stack->name) != 0)
484 /* chdir() failed; return error */
486 t->tree_errno = errno;
487 return (t->visit_type = TREE_ERROR_DIR);
490 return (t->visit_type = TREE_POSTDESCENT);
491 } else if (t->stack->flags & needsOpen) {
492 t->stack->flags &= ~needsOpen;
493 #if defined(_WIN32) && !defined(__CYGWIN__)
494 r = tree_dir_next_windows(t, "*");
496 r = tree_dir_next_posix(t);
501 } else if (t->stack->flags & needsAscent) {
502 /* Top stack item is dir and we're done with it. */
505 t->visit_type = r != 0 ? r : TREE_POSTASCENT;
506 return (t->visit_type);
508 /* Top item on stack is dead. */
510 t->flags &= ~hasLstat;
511 t->flags &= ~hasStat;
514 return (t->visit_type = 0);
517 #if defined(_WIN32) && !defined(__CYGWIN__)
519 tree_dir_next_windows(struct tree *t, const char *pattern)
526 if (pattern != NULL) {
527 t->d = FindFirstFile(pattern, &t->_findData);
528 if (t->d == INVALID_DIR_HANDLE) {
529 r = tree_ascend(t); /* Undo "chdir" */
531 t->tree_errno = errno;
532 t->visit_type = r != 0 ? r : TREE_ERROR_DIR;
533 return (t->visit_type);
535 t->findData = &t->_findData;
537 } else if (!FindNextFile(t->d, &t->_findData)) {
539 t->d = INVALID_DIR_HANDLE;
543 name = t->findData->cFileName;
544 namelen = strlen(name);
545 t->flags &= ~hasLstat;
546 t->flags &= ~hasStat;
547 if (name[0] == '.' && name[1] == '\0')
549 if (name[0] == '.' && name[1] == '.' && name[2] == '\0')
551 tree_append(t, name, namelen);
552 return (t->visit_type = TREE_REGULAR);
557 tree_dir_next_posix(struct tree *t)
564 if ((t->d = opendir(".")) == NULL) {
565 r = tree_ascend(t); /* Undo "chdir" */
567 t->tree_errno = errno;
568 t->visit_type = r != 0 ? r : TREE_ERROR_DIR;
569 return (t->visit_type);
573 t->de = readdir(t->d);
576 t->d = INVALID_DIR_HANDLE;
579 name = t->de->d_name;
580 namelen = D_NAMELEN(t->de);
581 t->flags &= ~hasLstat;
582 t->flags &= ~hasStat;
583 if (name[0] == '.' && name[1] == '\0')
585 if (name[0] == '.' && name[1] == '.' && name[2] == '\0')
587 tree_append(t, name, namelen);
588 return (t->visit_type = TREE_REGULAR);
597 tree_errno(struct tree *t)
599 return (t->tree_errno);
603 * Called by the client to mark the directory just returned from
604 * tree_next() as needing to be visited.
607 tree_descend(struct tree *t)
609 if (t->visit_type != TREE_REGULAR)
612 if (tree_current_is_physical_dir(t)) {
613 tree_push(t, t->basename);
614 t->stack->flags |= isDir;
615 } else if (tree_current_is_dir(t)) {
616 tree_push(t, t->basename);
617 t->stack->flags |= isDirLink;
622 * Get the stat() data for the entry just returned from tree_next().
625 tree_current_stat(struct tree *t)
627 if (!(t->flags & hasStat)) {
628 if (stat(tree_current_access_path(t), &t->st) != 0)
635 #if defined(_WIN32) && !defined(__CYGWIN__)
636 const BY_HANDLE_FILE_INFORMATION *
637 tree_current_file_information(struct tree *t)
639 if (!(t->flags & hasFileInfo)) {
640 HANDLE h = CreateFile(tree_current_access_path(t),
643 FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OPEN_REPARSE_POINT,
645 if (h == INVALID_HANDLE_VALUE)
647 if (!GetFileInformationByHandle(h, &t->fileInfo)) {
652 t->flags |= hasFileInfo;
654 return (&t->fileInfo);
658 * Get the lstat() data for the entry just returned from tree_next().
661 tree_current_lstat(struct tree *t)
663 #if defined(_WIN32) && !defined(__CYGWIN__)
664 return (tree_current_stat(t));
666 if (!(t->flags & hasLstat)) {
667 if (lstat(tree_current_access_path(t), &t->lst) != 0)
669 t->flags |= hasLstat;
676 * Test whether current entry is a dir or link to a dir.
679 tree_current_is_dir(struct tree *t)
681 #if defined(_WIN32) && !defined(__CYGWIN__)
683 return (t->findData->dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
684 if (tree_current_file_information(t))
685 return (t->fileInfo.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
688 const struct stat *st;
690 * If we already have lstat() info, then try some
691 * cheap tests to determine if this is a dir.
693 if (t->flags & hasLstat) {
694 /* If lstat() says it's a dir, it must be a dir. */
695 if (S_ISDIR(tree_current_lstat(t)->st_mode))
697 /* Not a dir; might be a link to a dir. */
698 /* If it's not a link, then it's not a link to a dir. */
699 if (!S_ISLNK(tree_current_lstat(t)->st_mode))
702 * It's a link, but we don't know what it's a link to,
703 * so we'll have to use stat().
707 st = tree_current_stat(t);
708 /* If we can't stat it, it's not a dir. */
711 /* Use the definitive test. Hopefully this is cached. */
712 return (S_ISDIR(st->st_mode));
717 * Test whether current entry is a physical directory. Usually, we
718 * already have at least one of stat() or lstat() in memory, so we
719 * use tricks to try to avoid an extra trip to the disk.
722 tree_current_is_physical_dir(struct tree *t)
724 #if defined(_WIN32) && !defined(__CYGWIN__)
725 if (tree_current_is_physical_link(t))
727 return (tree_current_is_dir(t));
729 const struct stat *st;
732 * If stat() says it isn't a dir, then it's not a dir.
733 * If stat() data is cached, this check is free, so do it first.
735 if ((t->flags & hasStat)
736 && (!S_ISDIR(tree_current_stat(t)->st_mode)))
740 * Either stat() said it was a dir (in which case, we have
741 * to determine whether it's really a link to a dir) or
742 * stat() info wasn't available. So we use lstat(), which
743 * hopefully is already cached.
746 st = tree_current_lstat(t);
747 /* If we can't stat it, it's not a dir. */
750 /* Use the definitive test. Hopefully this is cached. */
751 return (S_ISDIR(st->st_mode));
756 * Test whether current entry is a symbolic link.
759 tree_current_is_physical_link(struct tree *t)
761 #if defined(_WIN32) && !defined(__CYGWIN__)
762 #ifndef IO_REPARSE_TAG_SYMLINK
763 /* Old SDKs do not provide IO_REPARSE_TAG_SYMLINK */
764 #define IO_REPARSE_TAG_SYMLINK 0xA000000CL
767 return ((t->findData->dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT)
768 && (t->findData->dwReserved0 == IO_REPARSE_TAG_SYMLINK));
771 const struct stat *st = tree_current_lstat(t);
774 return (S_ISLNK(st->st_mode));
779 * Return the access path for the entry just returned from tree_next().
782 tree_current_access_path(struct tree *t)
784 return (t->basename);
788 * Return the full path for the entry just returned from tree_next().
791 tree_current_path(struct tree *t)
797 * Return the length of the path for the entry just returned from tree_next().
800 tree_current_pathlen(struct tree *t)
802 return (t->path_length);
806 * Return the nesting depth of the entry just returned from tree_next().
809 tree_current_depth(struct tree *t)
815 * Terminate the traversal and release any resources.
818 tree_close(struct tree *t)
820 /* Release anything remaining in the stack. */
821 while (t->stack != NULL)
824 /* TODO: Ensure that premature close() resets cwd */
827 if (t->initialDirFd >= 0) {
828 int s = fchdir(t->initialDirFd);
829 (void)s; /* UNUSED */
830 close(t->initialDirFd);
831 t->initialDirFd = -1;
833 #elif defined(_WIN32) && !defined(__CYGWIN__)
834 if (t->initialDir != NULL) {
835 SetCurrentDir(t->initialDir);
837 t->initialDir = NULL;