1 /* File tree walker functions.
2 Copyright (C) 1996-2004, 2006-2008, 2010 Free Software Foundation, Inc.
3 This file is part of the GNU C Library.
4 Contributed by Ulrich Drepper <drepper@cygnus.com>, 1996.
6 The GNU C Library is free software; you can redistribute it and/or
7 modify it under the terms of the GNU Lesser General Public
8 License as published by the Free Software Foundation; either
9 version 2.1 of the License, or (at your option) any later version.
11 The GNU C Library is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public
17 License along with the GNU C Library; if not, write to the Free
18 Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
26 # define alloca __builtin_alloca
32 #define NAMLEN(dirent) strlen ((dirent)->d_name)
43 # include <sys/param.h>
46 #include <atalk/ftw.h>
48 #define mempcpy(D, S, N) ((void *) ((char *) memcpy (D, S, N) + (N)))
55 # define __chdir chdir
57 # define __closedir closedir
59 # define __fchdir fchdir
61 # define __getcwd(P, N) xgetcwd ()
63 # define __mempcpy mempcpy
65 # define __opendir opendir
67 # define __readdir64 readdir
69 # define __tdestroy tdestroy
71 # define __tfind tfind
73 # define __tsearch tsearch
74 # undef internal_function
75 # define internal_function /* empty */
77 # define dirent64 dirent
79 # define MAX(a, b) ((a) > (b) ? (a) : (b))
83 # define __set_errno(Val) errno = (Val)
86 /* Support for the LFS API version. */
89 # define NFTW_NAME nftw
90 # define NFTW_OLD_NAME __old_nftw
91 # define NFTW_NEW_NAME __new_nftw
94 # define LXSTAT(V,f,sb) lstat (f,sb)
95 # define XSTAT(V,f,sb) stat (f,sb)
96 # define FXSTATAT(V,d,f,sb,m) fstatat (d, f, sb, m)
100 /* We define PATH_MAX if the system does not provide a definition.
101 This does not artificially limit any operation. PATH_MAX is simply
102 used as a guesstimate for the expected maximal path length.
103 Buffers will be enlarged if necessary. */
105 # define PATH_MAX 1024
123 /* Array with pointers to open directory streams. */
124 struct dir_data **dirstreams;
128 /* Buffer containing name of currently processed object. */
132 /* Passed as fourth argument to `nftw' callback. The `base' member
133 tracks the content of the `dirbuf'. */
136 /* Flags passed to `nftw' function. 0 for `ftw'. */
139 /* Conversion array for flag values. It is the identity mapping for
140 `nftw' calls, otherwise it maps the values to those known by
144 /* Callback function. We always use the `nftw' form. */
147 /* Device of starting point. Needed for FTW_MOUNT. */
150 /* Data structure for keeping fingerprints of already processed
151 object. This is needed when not using FTW_PHYS. */
156 /* Internally we use the FTW_* constants used for `nftw'. When invoked
157 as `ftw', map each flag to the subset of values used by `ftw'. */
158 static const int nftw_arr[] =
160 FTW_F, FTW_D, FTW_DNR, FTW_NS, FTW_SL, FTW_DP, FTW_SLN
163 static const int ftw_arr[] =
165 FTW_F, FTW_D, FTW_DNR, FTW_NS, FTW_F, FTW_D, FTW_NS
169 static dir_notification_func_t upfunc;
171 /* Forward declarations of local functions. */
172 static int ftw_dir (struct ftw_data *data, struct STAT *st,
173 struct dir_data *old_dir) internal_function;
175 typedef void (*__free_fn_t) (void *__nodep);
176 typedef struct node_t {
179 struct node_t *right;
183 static void tdestroy_recurse (node root, __free_fn_t freefct)
185 if (root->left != NULL)
186 tdestroy_recurse (root->left, freefct);
187 if (root->right != NULL)
188 tdestroy_recurse (root->right, freefct);
189 (*freefct) ((void *) root->key);
190 /* Free the node itself. */
194 static void mytdestroy (void *vroot, __free_fn_t freefct)
196 node root = (node) vroot;
199 tdestroy_recurse (root, freefct);
202 static char *mystpcpy(char *a, const char *b)
205 return (a + strlen(a));
208 static char *xgetcwd(void)
215 path_max = (unsigned) PATH_MAX;
216 path_max += 2; /* The getcwd docs say to do this. */
218 cwd = malloc (path_max);
220 while ((ret = getcwd (cwd, path_max)) == NULL && errno == ERANGE) {
222 cwd = realloc (cwd, path_max);
227 int save_errno = errno;
236 object_compare (const void *p1, const void *p2)
238 /* We don't need a sophisticated and useful comparison. We are only
239 interested in equality. However, we must be careful not to
240 accidentally compare `holes' in the structure. */
241 const struct known_object *kp1 = p1, *kp2 = p2;
243 cmp1 = (kp1->ino > kp2->ino) - (kp1->ino < kp2->ino);
246 return (kp1->dev > kp2->dev) - (kp1->dev < kp2->dev);
251 add_object (struct ftw_data *data, struct STAT *st)
253 struct known_object *newp = malloc (sizeof (struct known_object));
256 newp->dev = st->st_dev;
257 newp->ino = st->st_ino;
258 return __tsearch (newp, &data->known_objects, object_compare) ? 0 : -1;
263 find_object (struct ftw_data *data, struct STAT *st)
265 struct known_object obj;
266 obj.dev = st->st_dev;
267 obj.ino = st->st_ino;
268 return __tfind (&obj, &data->known_objects, object_compare) != NULL;
273 open_dir_stream (int *dfdp, struct ftw_data *data, struct dir_data *dirp)
277 if (data->dirstreams[data->actdir] != NULL)
279 /* Oh, oh. We must close this stream. Get all remaining
280 entries and store them as a list in the `content' member of
281 the `struct dir_data' variable. */
282 size_t bufsize = 1024;
283 char *buf = malloc (bufsize);
289 DIR *st = data->dirstreams[data->actdir]->stream;
293 while ((d = __readdir64 (st)) != NULL)
295 size_t this_len = NAMLEN (d);
296 if (actsize + this_len + 2 >= bufsize)
299 bufsize += MAX (1024, 2 * this_len);
300 newp = (char *) realloc (buf, bufsize);
303 /* No more memory. */
304 int save_err = errno;
306 __set_errno (save_err);
312 *((char *) __mempcpy (buf + actsize, d->d_name, this_len))
314 actsize += this_len + 1;
317 /* Terminate the list with an additional NUL byte. */
318 buf[actsize++] = '\0';
320 /* Shrink the buffer to what we actually need. */
321 data->dirstreams[data->actdir]->content = realloc (buf, actsize);
322 if (data->dirstreams[data->actdir]->content == NULL)
324 int save_err = errno;
326 __set_errno (save_err);
332 data->dirstreams[data->actdir]->stream = NULL;
333 data->dirstreams[data->actdir]->streamfd = -1;
334 data->dirstreams[data->actdir] = NULL;
339 /* Open the new stream. */
342 assert (data->dirstreams[data->actdir] == NULL);
344 if (dfdp != NULL && *dfdp != -1)
346 int fd = openat(*dfdp, data->dirbuf + data->ftw.base, O_RDONLY);
348 if (fd != -1 && (dirp->stream = fdopendir (fd)) == NULL)
355 if (data->flags & FTW_CHDIR)
357 name = data->dirbuf + data->ftw.base;
364 dirp->stream = __opendir (name);
367 if (dirp->stream == NULL)
371 dirp->streamfd = dirfd (dirp->stream);
372 dirp->content = NULL;
373 data->dirstreams[data->actdir] = dirp;
375 if (++data->actdir == data->maxdir)
385 process_entry (struct ftw_data *data, struct dir_data *dir, const char *name, size_t namlen)
392 if (name[0] == '.' && (name[1] == '\0'
393 || (name[1] == '.' && name[2] == '\0')))
394 /* Don't process the "." and ".." entries. */
397 new_buflen = data->ftw.base + namlen + 2;
398 if (data->dirbufsize < new_buflen)
400 /* Enlarge the buffer. */
403 data->dirbufsize = 2 * new_buflen;
404 newp = (char *) realloc (data->dirbuf, data->dirbufsize);
410 *((char *) __mempcpy (data->dirbuf + data->ftw.base, name, namlen)) = '\0';
413 if (dir->streamfd != -1)
414 statres = FXSTATAT (_STAT_VER, dir->streamfd, name, &st,
415 (data->flags & FTW_PHYS) ? AT_SYMLINK_NOFOLLOW : 0);
418 if ((data->flags & FTW_CHDIR) == 0)
421 statres = ((data->flags & FTW_PHYS)
422 ? LXSTAT (_STAT_VER, name, &st)
423 : XSTAT (_STAT_VER, name, &st));
428 if (errno != EACCES && errno != ENOENT)
430 else if (data->flags & FTW_PHYS)
434 if (dir->streamfd != -1)
435 statres = FXSTATAT (_STAT_VER, dir->streamfd, name, &st,
436 AT_SYMLINK_NOFOLLOW);
438 statres = LXSTAT (_STAT_VER, name, &st);
439 if (statres == 0 && S_ISLNK (st.st_mode))
447 if (S_ISDIR (st.st_mode))
449 else if (S_ISLNK (st.st_mode))
457 || !(data->flags & FTW_MOUNT) || st.st_dev == data->dev))
461 if ((data->flags & FTW_PHYS)
462 || (!find_object (data, &st)
463 /* Remember the object. */
464 && (result = add_object (data, &st)) == 0))
465 result = ftw_dir (data, &st, dir);
468 result = (*data->func) (data->dirbuf, &st, data->cvt_arr[flag],
472 if ((data->flags & FTW_ACTIONRETVAL) && result == FTW_SKIP_SUBTREE)
480 ftw_dir (struct ftw_data *data, struct STAT *st, struct dir_data *old_dir)
484 int previous_base = data->ftw.base;
488 /* Open the stream for this directory. This might require that
489 another stream has to be closed. */
490 result = open_dir_stream (old_dir == NULL ? NULL : &old_dir->streamfd,
495 /* We cannot read the directory. Signal this with a special flag. */
496 result = (*data->func) (data->dirbuf, st, FTW_DNR, &data->ftw);
501 /* First, report the directory (if not depth-first). */
502 if (!(data->flags & FTW_DEPTH))
504 result = (*data->func) (data->dirbuf, st, FTW_D, &data->ftw);
510 __closedir (dir.stream);
512 __set_errno (save_err);
514 if (data->actdir-- == 0)
515 data->actdir = data->maxdir - 1;
516 data->dirstreams[data->actdir] = NULL;
521 /* If necessary, change to this directory. */
522 if (data->flags & FTW_CHDIR)
524 if (__fchdir (dirfd (dir.stream)) < 0)
531 /* Next, update the `struct FTW' information. */
533 startp = data->dirbuf + strlen(data->dirbuf);
534 /* There always must be a directory name. */
535 assert (startp != data->dirbuf);
536 if (startp[-1] != '/')
538 data->ftw.base = startp - data->dirbuf;
540 while (dir.stream != NULL && (d = __readdir64 (dir.stream)) != NULL)
542 result = process_entry (data, &dir, d->d_name, NAMLEN (d));
547 if (dir.stream != NULL)
549 /* The stream is still open. I.e., we did not need more
550 descriptors. Simply close the stream now. */
551 int save_err = errno;
553 assert (dir.content == NULL);
555 __closedir (dir.stream);
557 __set_errno (save_err);
559 if (data->actdir-- == 0)
560 data->actdir = data->maxdir - 1;
561 data->dirstreams[data->actdir] = NULL;
566 char *runp = dir.content;
568 while (result == 0 && *runp != '\0')
570 char *endp = strchr (runp, '\0');
572 // XXX Should store the d_type values as well?!
573 result = process_entry (data, &dir, runp, endp - runp);
580 __set_errno (save_err);
583 if ((data->flags & FTW_ACTIONRETVAL) && result == FTW_SKIP_SIBLINGS)
586 /* Prepare the return, revert the `struct FTW' information. */
587 data->dirbuf[data->ftw.base - 1] = '\0';
591 data->ftw.base = previous_base;
593 /* Finally, if we process depth-first report the directory. */
594 if (result == 0 && (data->flags & FTW_DEPTH))
595 result = (*data->func) (data->dirbuf, st, FTW_DP, &data->ftw);
598 && (data->flags & FTW_CHDIR)
600 || ((data->flags & FTW_ACTIONRETVAL)
601 && (result != -1 && result != FTW_STOP))))
603 /* Change back to the parent directory. */
605 if (old_dir->stream != NULL)
606 if (__fchdir (dirfd (old_dir->stream)) == 0)
611 if (data->ftw.base == 1)
613 if (__chdir ("/") < 0)
617 if (__chdir ("..") < 0)
626 static int ftw_startup (const char *dir,
629 dir_notification_func_t up,
633 struct ftw_data data;
643 /* First make sure the parameters are reasonable. */
646 __set_errno (ENOENT);
650 data.maxdir = descriptors < 1 ? 1 : descriptors;
652 data.dirstreams = (struct dir_data **) alloca (data.maxdir
653 * sizeof (struct dir_data *));
654 memset (data.dirstreams, '\0', data.maxdir * sizeof (struct dir_data *));
656 /* PATH_MAX is always defined when we get here. */
657 data.dirbufsize = MAX (2 * strlen (dir), PATH_MAX);
658 data.dirbuf = (char *) malloc (data.dirbufsize);
659 if (data.dirbuf == NULL)
661 cp = mystpcpy (data.dirbuf, dir);
662 /* Strip trailing slashes. */
663 while (cp > data.dirbuf + 1 && cp[-1] == '/')
670 while (cp > data.dirbuf && cp[-1] != '/')
672 data.ftw.base = cp - data.dirbuf;
676 /* This assignment might seem to be strange but it is what we want.
677 The trick is that the first three arguments to the `ftw' and
678 `nftw' callback functions are equal. Therefore we can call in
679 every case the callback using the format of the `nftw' version
680 and get the correct result since the stack layout for a function
681 call in C allows this. */
682 data.func = (NFTW_FUNC_T) func;
684 /* Since we internally use the complete set of FTW_* values we need
685 to reduce the value range before calling a `ftw' callback. */
686 data.cvt_arr = is_nftw ? nftw_arr : ftw_arr;
688 /* No object known so far. */
689 data.known_objects = NULL;
691 /* Now go to the directory containing the initial file/directory. */
692 if (flags & FTW_CHDIR)
694 /* We have to be able to go back to the current working
695 directory. The best way to do this is to use a file
697 cwdfd = open (".", O_RDONLY);
700 /* Try getting the directory name. This can be needed if
701 the current directory is executable but not readable. */
703 /* GNU extension ahead. */
704 cwd = __getcwd(NULL, 0);
709 else if (data.maxdir > 1)
710 /* Account for the file descriptor we use here. */
713 if (data.ftw.base > 0)
715 /* Change to the directory the file is in. In data.dirbuf
716 we have a writable copy of the file name. Just NUL
717 terminate it for now and change the directory. */
718 if (data.ftw.base == 1)
719 /* I.e., the file is in the root directory. */
720 result = __chdir ("/");
723 char ch = data.dirbuf[data.ftw.base - 1];
724 data.dirbuf[data.ftw.base - 1] = '\0';
725 result = __chdir (data.dirbuf);
726 data.dirbuf[data.ftw.base - 1] = ch;
731 /* Get stat info for start directory. */
736 if (data.flags & FTW_CHDIR)
738 name = data.dirbuf + data.ftw.base;
745 if (((flags & FTW_PHYS)
746 ? LXSTAT (_STAT_VER, name, &st)
747 : XSTAT (_STAT_VER, name, &st)) < 0)
749 if (!(flags & FTW_PHYS)
751 && LXSTAT (_STAT_VER, name, &st) == 0
752 && S_ISLNK (st.st_mode))
753 result = (*data.func) (data.dirbuf, &st, data.cvt_arr[FTW_SLN],
756 /* No need to call the callback since we cannot say anything
762 if (S_ISDIR (st.st_mode))
764 /* Remember the device of the initial directory in case
765 FTW_MOUNT is given. */
766 data.dev = st.st_dev;
768 /* We know this directory now. */
769 if (!(flags & FTW_PHYS))
770 result = add_object (&data, &st);
773 result = ftw_dir (&data, &st, NULL);
777 int flag = S_ISLNK (st.st_mode) ? FTW_SL : FTW_F;
779 result = (*data.func) (data.dirbuf, &st, data.cvt_arr[flag],
784 if ((flags & FTW_ACTIONRETVAL)
785 && (result == FTW_SKIP_SUBTREE || result == FTW_SKIP_SIBLINGS))
789 /* Return to the start directory (if necessary). */
792 int save_err = errno;
795 __set_errno (save_err);
797 else if (cwd != NULL)
799 int save_err = errno;
802 __set_errno (save_err);
805 /* Free all memory. */
808 mytdestroy (data.known_objects, free);
810 __set_errno (save_err);
818 int NFTW_NAME(const char *path,
820 dir_notification_func_t up,
824 return ftw_startup (path, 1, func, up, descriptors, flags);