1 /* File tree walker functions.
2    Copyright (C) 1996-2021 Free Software Foundation, Inc.
3    This file is part of the GNU C Library.
4 
5    The GNU C Library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9 
10    The GNU C Library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14 
15    You should have received a copy of the GNU Lesser General Public
16    License along with the GNU C Library; if not, see
17    <https://www.gnu.org/licenses/>.  */
18 
19 #ifdef HAVE_CONFIG_H
20 # include <config.h>
21 #endif
22 
23 #if __GNUC__
24 # define alloca __builtin_alloca
25 #else
26 # if HAVE_ALLOCA_H
27 #  include <alloca.h>
28 # else
29 #  ifdef _AIX
30  #  pragma alloca
31 #  else
32 char *alloca ();
33 #  endif
34 # endif
35 #endif
36 
37 #ifdef _LIBC
38 # include <dirent.h>
39 # define NAMLEN(dirent) _D_EXACT_NAMLEN (dirent)
40 #else
41 # if HAVE_DIRENT_H
42 #  include <dirent.h>
43 #  define NAMLEN(dirent) strlen ((dirent)->d_name)
44 # else
45 #  define dirent direct
46 #  define NAMLEN(dirent) (dirent)->d_namlen
47 #  if HAVE_SYS_NDIR_H
48 #   include <sys/ndir.h>
49 #  endif
50 #  if HAVE_SYS_DIR_H
51 #   include <sys/dir.h>
52 #  endif
53 #  if HAVE_NDIR_H
54 #   include <ndir.h>
55 #  endif
56 # endif
57 #endif
58 
59 #include <errno.h>
60 #include <fcntl.h>
61 #include <ftw.h>
62 #include <limits.h>
63 #include <search.h>
64 #include <stdlib.h>
65 #include <string.h>
66 #include <unistd.h>
67 #include <not-cancel.h>
68 #include <sys/param.h>
69 #ifdef _LIBC
70 # include <include/sys/stat.h>
71 #else
72 # include <sys/stat.h>
73 #endif
74 
75 #if ! _LIBC && !HAVE_DECL_STPCPY && !defined stpcpy
76 char *stpcpy ();
77 #endif
78 
79 #if ! _LIBC && ! defined HAVE_MEMPCPY && ! defined mempcpy
80 /* Be CAREFUL that there are no side effects in N.  */
81 # define mempcpy(D, S, N) ((void *) ((char *) memcpy (D, S, N) + (N)))
82 #endif
83 
84 /* #define NDEBUG 1 */
85 #include <assert.h>
86 
87 #ifndef _LIBC
88 # undef __chdir
89 # define __chdir chdir
90 # undef __closedir
91 # define __closedir closedir
92 # undef __fchdir
93 # define __fchdir fchdir
94 # undef __getcwd
95 # define __getcwd(P, N) xgetcwd ()
96 extern char *xgetcwd (void);
97 # undef __mempcpy
98 # define __mempcpy mempcpy
99 # undef __opendir
100 # define __opendir opendir
101 # undef __readdir64
102 # define __readdir64 readdir
103 # undef __stpcpy
104 # define __stpcpy stpcpy
105 # undef __tdestroy
106 # define __tdestroy tdestroy
107 # undef __tfind
108 # define __tfind tfind
109 # undef __tsearch
110 # define __tsearch tsearch
111 # undef dirent64
112 # define dirent64 dirent
113 # undef MAX
114 # define MAX(a, b) ((a) > (b) ? (a) : (b))
115 #endif
116 
117 /* Arrange to make lstat calls go through the wrapper function
118    on systems with an lstat function that does not dereference symlinks
119    that are specified with a trailing slash.  */
120 #if ! _LIBC && ! LSTAT_FOLLOWS_SLASHED_SYMLINK
121 int rpl_lstat (const char *, struct stat *);
122 # undef lstat
123 # define lstat(Name, Stat_buf) rpl_lstat(Name, Stat_buf)
124 #endif
125 
126 #ifndef __set_errno
127 # define __set_errno(Val) errno = (Val)
128 #endif
129 
130 /* Support for the LFS API version.  */
131 #ifndef FTW_NAME
132 # define FTW_NAME ftw
133 # define NFTW_NAME nftw
134 # define NFTW_OLD_NAME __old_nftw
135 # define NFTW_NEW_NAME __new_nftw
136 # define INO_T ino_t
137 # define STRUCT_STAT stat
138 # ifdef _LIBC
139 #  define LSTAT __lstat
140 #  define STAT __stat
141 #  define FSTATAT __fstatat
142 # else
143 #  define LSTAT lstat
144 #  define XTAT stat
145 #  define FSTATAT fstatat
146 # endif
147 # define FTW_FUNC_T __ftw_func_t
148 # define NFTW_FUNC_T __nftw_func_t
149 #endif
150 
151 /* We define PATH_MAX if the system does not provide a definition.
152    This does not artificially limit any operation.  PATH_MAX is simply
153    used as a guesstimate for the expected maximal path length.
154    Buffers will be enlarged if necessary.  */
155 #ifndef PATH_MAX
156 # define PATH_MAX 1024
157 #endif
158 
159 struct dir_data
160 {
161   DIR *stream;
162   int streamfd;
163   char *content;
164 };
165 
166 struct known_object
167 {
168   dev_t dev;
169   INO_T ino;
170 };
171 
172 struct ftw_data
173 {
174   /* Array with pointers to open directory streams.  */
175   struct dir_data **dirstreams;
176   size_t actdir;
177   size_t maxdir;
178 
179   /* Buffer containing name of currently processed object.  */
180   char *dirbuf;
181   size_t dirbufsize;
182 
183   /* Passed as fourth argument to `nftw' callback.  The `base' member
184      tracks the content of the `dirbuf'.  */
185   struct FTW ftw;
186 
187   /* Flags passed to `nftw' function.  0 for `ftw'.  */
188   int flags;
189 
190   /* Conversion array for flag values.  It is the identity mapping for
191      `nftw' calls, otherwise it maps the values to those known by
192      `ftw'.  */
193   const int *cvt_arr;
194 
195   /* Callback function.  We always use the `nftw' form.  */
196   NFTW_FUNC_T func;
197 
198   /* Device of starting point.  Needed for FTW_MOUNT.  */
199   dev_t dev;
200 
201   /* Data structure for keeping fingerprints of already processed
202      object.  This is needed when not using FTW_PHYS.  */
203   void *known_objects;
204 };
205 
206 static bool
ftw_allocate(struct ftw_data * data,size_t newsize)207 ftw_allocate (struct ftw_data *data, size_t newsize)
208 {
209   void *newp = realloc (data->dirstreams, data->maxdir
210 					  * sizeof (struct dir_data *)
211 					  + newsize);
212   if (newp == NULL)
213     return false;
214   data->dirstreams = newp;
215   data->dirbufsize = newsize;
216   data->dirbuf = (char *) data->dirstreams
217 		 + data->maxdir * sizeof (struct dir_data *);
218   return true;
219 }
220 
221 /* Internally we use the FTW_* constants used for `nftw'.  When invoked
222    as `ftw', map each flag to the subset of values used by `ftw'.  */
223 static const int nftw_arr[] =
224 {
225   FTW_F, FTW_D, FTW_DNR, FTW_NS, FTW_SL, FTW_DP, FTW_SLN
226 };
227 
228 static const int ftw_arr[] =
229 {
230   FTW_F, FTW_D, FTW_DNR, FTW_NS, FTW_F, FTW_D, FTW_NS
231 };
232 
233 
234 /* Forward declarations of local functions.  */
235 static int ftw_dir (struct ftw_data *data, struct STRUCT_STAT *st,
236 		    struct dir_data *old_dir);
237 
238 
239 static int
object_compare(const void * p1,const void * p2)240 object_compare (const void *p1, const void *p2)
241 {
242   /* We don't need a sophisticated and useful comparison.  We are only
243      interested in equality.  However, we must be careful not to
244      accidentally compare `holes' in the structure.  */
245   const struct known_object *kp1 = p1, *kp2 = p2;
246   int cmp1;
247   cmp1 = (kp1->ino > kp2->ino) - (kp1->ino < kp2->ino);
248   if (cmp1 != 0)
249     return cmp1;
250   return (kp1->dev > kp2->dev) - (kp1->dev < kp2->dev);
251 }
252 
253 
254 static int
add_object(struct ftw_data * data,struct STRUCT_STAT * st)255 add_object (struct ftw_data *data, struct STRUCT_STAT *st)
256 {
257   struct known_object *newp = malloc (sizeof (struct known_object));
258   if (newp == NULL)
259     return -1;
260   newp->dev = st->st_dev;
261   newp->ino = st->st_ino;
262   return __tsearch (newp, &data->known_objects, object_compare) ? 0 : -1;
263 }
264 
265 
266 static inline int
find_object(struct ftw_data * data,struct STRUCT_STAT * st)267 find_object (struct ftw_data *data, struct STRUCT_STAT *st)
268 {
269   struct known_object obj;
270   obj.dev = st->st_dev;
271   obj.ino = st->st_ino;
272   return __tfind (&obj, &data->known_objects, object_compare) != NULL;
273 }
274 
275 
276 static inline int
277 __attribute ((always_inline))
open_dir_stream(int * dfdp,struct ftw_data * data,struct dir_data * dirp)278 open_dir_stream (int *dfdp, struct ftw_data *data, struct dir_data *dirp)
279 {
280   int result = 0;
281 
282   if (data->dirstreams[data->actdir] != NULL)
283     {
284       /* Oh, oh.  We must close this stream.  Get all remaining
285 	 entries and store them as a list in the `content' member of
286 	 the `struct dir_data' variable.  */
287       size_t bufsize = 1024;
288       char *buf = malloc (bufsize);
289 
290       if (buf == NULL)
291 	result = -1;
292       else
293 	{
294 	  DIR *st = data->dirstreams[data->actdir]->stream;
295 	  struct dirent64 *d;
296 	  size_t actsize = 0;
297 
298 	  while ((d = __readdir64 (st)) != NULL)
299 	    {
300 	      size_t this_len = NAMLEN (d);
301 	      if (actsize + this_len + 2 >= bufsize)
302 		{
303 		  char *newp;
304 		  bufsize += MAX (1024, 2 * this_len);
305 		  newp = (char *) realloc (buf, bufsize);
306 		  if (newp == NULL)
307 		    {
308 		      /* No more memory.  */
309 		      int save_err = errno;
310 		      free (buf);
311 		      __set_errno (save_err);
312 		      return -1;
313 		    }
314 		  buf = newp;
315 		}
316 
317 	      *((char *) __mempcpy (buf + actsize, d->d_name, this_len))
318 		= '\0';
319 	      actsize += this_len + 1;
320 	    }
321 
322 	  /* Terminate the list with an additional NUL byte.  */
323 	  buf[actsize++] = '\0';
324 
325 	  /* Shrink the buffer to what we actually need.  */
326 	  data->dirstreams[data->actdir]->content = realloc (buf, actsize);
327 	  if (data->dirstreams[data->actdir]->content == NULL)
328 	    {
329 	      int save_err = errno;
330 	      free (buf);
331 	      __set_errno (save_err);
332 	      result = -1;
333 	    }
334 	  else
335 	    {
336 	      __closedir (st);
337 	      data->dirstreams[data->actdir]->stream = NULL;
338 	      data->dirstreams[data->actdir]->streamfd = -1;
339 	      data->dirstreams[data->actdir] = NULL;
340 	    }
341 	}
342     }
343 
344   /* Open the new stream.  */
345   if (result == 0)
346     {
347       assert (data->dirstreams[data->actdir] == NULL);
348 
349       if (dfdp != NULL && *dfdp != -1)
350 	{
351 	  int fd = __openat64_nocancel (*dfdp, data->dirbuf + data->ftw.base,
352 					O_RDONLY | O_DIRECTORY | O_NDELAY);
353 	  dirp->stream = NULL;
354 	  if (fd != -1 && (dirp->stream = __fdopendir (fd)) == NULL)
355 	    __close_nocancel_nostatus (fd);
356 	}
357       else
358 	{
359 	  const char *name;
360 
361 	  if (data->flags & FTW_CHDIR)
362 	    {
363 	      name = data->dirbuf + data->ftw.base;
364 	      if (name[0] == '\0')
365 		name = ".";
366 	    }
367 	  else
368 	    name = data->dirbuf;
369 
370 	  dirp->stream = __opendir (name);
371 	}
372 
373       if (dirp->stream == NULL)
374 	result = -1;
375       else
376 	{
377 	  dirp->streamfd = __dirfd (dirp->stream);
378 	  dirp->content = NULL;
379 	  data->dirstreams[data->actdir] = dirp;
380 
381 	  if (++data->actdir == data->maxdir)
382 	    data->actdir = 0;
383 	}
384     }
385 
386   return result;
387 }
388 
389 
390 static int
process_entry(struct ftw_data * data,struct dir_data * dir,const char * name,size_t namlen,int d_type)391 process_entry (struct ftw_data *data, struct dir_data *dir, const char *name,
392 	       size_t namlen, int d_type)
393 {
394   struct STRUCT_STAT st;
395   int result = 0;
396   int flag = 0;
397   size_t new_buflen;
398 
399   if (name[0] == '.' && (name[1] == '\0'
400 			 || (name[1] == '.' && name[2] == '\0')))
401     /* Don't process the "." and ".." entries.  */
402     return 0;
403 
404   new_buflen = data->ftw.base + namlen + 2;
405   if (data->dirbufsize < new_buflen
406       && !ftw_allocate (data, 2 * new_buflen))
407     return -1;
408 
409   *((char *) __mempcpy (data->dirbuf + data->ftw.base, name, namlen)) = '\0';
410 
411   int statres;
412   if (dir->streamfd != -1)
413     statres = FSTATAT (dir->streamfd, name, &st,
414 		       (data->flags & FTW_PHYS) ? AT_SYMLINK_NOFOLLOW : 0);
415   else
416     {
417       if ((data->flags & FTW_CHDIR) == 0)
418 	name = data->dirbuf;
419 
420       statres = ((data->flags & FTW_PHYS)
421 		 ? LSTAT (name, &st)
422 		 : STAT (name, &st));
423     }
424 
425   if (statres < 0)
426     {
427       if (errno != EACCES && errno != ENOENT)
428 	result = -1;
429       else if (data->flags & FTW_PHYS)
430 	flag = FTW_NS;
431       else
432 	{
433 	  /* Old code left ST undefined for dangling DT_LNK without
434 	     FTW_PHYS set; a clarification at the POSIX level suggests
435 	     it should contain information about the link (ala lstat).
436 	     We do our best to fill in what data we can.  */
437 	  if (dir->streamfd != -1)
438 	    statres = FSTATAT (dir->streamfd, name, &st,
439 			       AT_SYMLINK_NOFOLLOW);
440 	  else
441 	    statres = LSTAT (name, &st);
442 	  if (statres == 0 && S_ISLNK (st.st_mode))
443 	    flag = FTW_SLN;
444 	  else
445 	    flag = FTW_NS;
446 	}
447     }
448   else
449     {
450       if (S_ISDIR (st.st_mode))
451 	flag = FTW_D;
452       else if (S_ISLNK (st.st_mode))
453 	flag = FTW_SL;
454       else
455 	flag = FTW_F;
456     }
457 
458   if (result == 0
459       && (flag == FTW_NS
460 	  || !(data->flags & FTW_MOUNT) || st.st_dev == data->dev))
461     {
462       if (flag == FTW_D)
463 	{
464 	  if ((data->flags & FTW_PHYS)
465 	      || (!find_object (data, &st)
466 		  /* Remember the object.  */
467 		  && (result = add_object (data, &st)) == 0))
468 	    result = ftw_dir (data, &st, dir);
469 	}
470       else
471 	result = (*data->func) (data->dirbuf, &st, data->cvt_arr[flag],
472 				&data->ftw);
473     }
474 
475   if ((data->flags & FTW_ACTIONRETVAL) && result == FTW_SKIP_SUBTREE)
476     result = 0;
477 
478   return result;
479 }
480 
481 
482 static int
483 __attribute ((noinline))
ftw_dir(struct ftw_data * data,struct STRUCT_STAT * st,struct dir_data * old_dir)484 ftw_dir (struct ftw_data *data, struct STRUCT_STAT *st, struct dir_data *old_dir)
485 {
486   struct dir_data dir;
487   struct dirent64 *d;
488   int previous_base = data->ftw.base;
489   int result;
490   char *startp;
491 
492   /* Open the stream for this directory.  This might require that
493      another stream has to be closed.  */
494   result = open_dir_stream (old_dir == NULL ? NULL : &old_dir->streamfd,
495 			    data, &dir);
496   if (result != 0)
497     {
498       if (errno == EACCES)
499 	/* We cannot read the directory.  Signal this with a special flag.  */
500 	result = (*data->func) (data->dirbuf, st, FTW_DNR, &data->ftw);
501 
502       return result;
503     }
504 
505   /* First, report the directory (if not depth-first).  */
506   if (!(data->flags & FTW_DEPTH))
507     {
508       result = (*data->func) (data->dirbuf, st, FTW_D, &data->ftw);
509       if (result != 0)
510 	{
511 	  int save_err;
512 fail:
513 	  save_err = errno;
514 	  __closedir (dir.stream);
515 	  dir.streamfd = -1;
516 	  __set_errno (save_err);
517 
518 	  if (data->actdir-- == 0)
519 	    data->actdir = data->maxdir - 1;
520 	  data->dirstreams[data->actdir] = NULL;
521 	  return result;
522 	}
523     }
524 
525   /* If necessary, change to this directory.  */
526   if (data->flags & FTW_CHDIR)
527     {
528       if (__fchdir (__dirfd (dir.stream)) < 0)
529 	{
530 	  result = -1;
531 	  goto fail;
532 	}
533     }
534 
535   /* Next, update the `struct FTW' information.  */
536   ++data->ftw.level;
537   startp = __rawmemchr (data->dirbuf, '\0');
538   /* There always must be a directory name.  */
539   assert (startp != data->dirbuf);
540   if (startp[-1] != '/')
541     *startp++ = '/';
542   data->ftw.base = startp - data->dirbuf;
543 
544   while (dir.stream != NULL && (d = __readdir64 (dir.stream)) != NULL)
545     {
546       int d_type = DT_UNKNOWN;
547 #ifdef _DIRENT_HAVE_D_TYPE
548       d_type = d->d_type;
549 #endif
550       result = process_entry (data, &dir, d->d_name, NAMLEN (d), d_type);
551       if (result != 0)
552 	break;
553     }
554 
555   if (dir.stream != NULL)
556     {
557       /* The stream is still open.  I.e., we did not need more
558 	 descriptors.  Simply close the stream now.  */
559       int save_err = errno;
560 
561       assert (dir.content == NULL);
562 
563       __closedir (dir.stream);
564       dir.streamfd = -1;
565       __set_errno (save_err);
566 
567       if (data->actdir-- == 0)
568 	data->actdir = data->maxdir - 1;
569       data->dirstreams[data->actdir] = NULL;
570     }
571   else
572     {
573       int save_err;
574       char *runp = dir.content;
575 
576       while (result == 0 && *runp != '\0')
577 	{
578 	  char *endp = strchr (runp, '\0');
579 
580 	  // XXX Should store the d_type values as well?!
581 	  result = process_entry (data, &dir, runp, endp - runp, DT_UNKNOWN);
582 
583 	  runp = endp + 1;
584 	}
585 
586       save_err = errno;
587       free (dir.content);
588       __set_errno (save_err);
589     }
590 
591   if ((data->flags & FTW_ACTIONRETVAL) && result == FTW_SKIP_SIBLINGS)
592     result = 0;
593 
594   /* Prepare the return, revert the `struct FTW' information.  */
595   data->dirbuf[data->ftw.base - 1] = '\0';
596   --data->ftw.level;
597   data->ftw.base = previous_base;
598 
599   /* Finally, if we process depth-first report the directory.  */
600   if (result == 0 && (data->flags & FTW_DEPTH))
601     result = (*data->func) (data->dirbuf, st, FTW_DP, &data->ftw);
602 
603   if (old_dir
604       && (data->flags & FTW_CHDIR)
605       && (result == 0
606 	  || ((data->flags & FTW_ACTIONRETVAL)
607 	      && (result != -1 && result != FTW_STOP))))
608     {
609       /* Change back to the parent directory.  */
610       int done = 0;
611       if (old_dir->stream != NULL)
612 	if (__fchdir (__dirfd (old_dir->stream)) == 0)
613 	  done = 1;
614 
615       if (!done)
616 	{
617 	  if (data->ftw.base == 1)
618 	    {
619 	      if (__chdir ("/") < 0)
620 		result = -1;
621 	    }
622 	  else
623 	    if (__chdir ("..") < 0)
624 	      result = -1;
625 	}
626     }
627 
628   return result;
629 }
630 
631 
632 static int
633 __attribute ((noinline))
ftw_startup(const char * dir,int is_nftw,void * func,int descriptors,int flags)634 ftw_startup (const char *dir, int is_nftw, void *func, int descriptors,
635 	     int flags)
636 {
637   struct ftw_data data = { .dirstreams = NULL };
638   struct STRUCT_STAT st;
639   int result = 0;
640   int save_err;
641   int cwdfd = -1;
642   char *cwd = NULL;
643   char *cp;
644 
645   /* First make sure the parameters are reasonable.  */
646   if (dir[0] == '\0')
647     {
648       __set_errno (ENOENT);
649       return -1;
650     }
651 
652   data.maxdir = descriptors < 1 ? 1 : descriptors;
653   data.actdir = 0;
654   /* PATH_MAX is always defined when we get here.  */
655   if (!ftw_allocate (&data, MAX (2 * strlen (dir), PATH_MAX)))
656     return -1;
657   memset (data.dirstreams, '\0', data.maxdir * sizeof (struct dir_data *));
658   cp = __stpcpy (data.dirbuf, dir);
659   /* Strip trailing slashes.  */
660   while (cp > data.dirbuf + 1 && cp[-1] == '/')
661     --cp;
662   *cp = '\0';
663 
664   data.ftw.level = 0;
665 
666   /* Find basename.  */
667   while (cp > data.dirbuf && cp[-1] != '/')
668     --cp;
669   data.ftw.base = cp - data.dirbuf;
670 
671   data.flags = flags;
672 
673   /* This assignment might seem to be strange but it is what we want.
674      The trick is that the first three arguments to the `ftw' and
675      `nftw' callback functions are equal.  Therefore we can call in
676      every case the callback using the format of the `nftw' version
677      and get the correct result since the stack layout for a function
678      call in C allows this.  */
679   data.func = (NFTW_FUNC_T) func;
680 
681   /* Since we internally use the complete set of FTW_* values we need
682      to reduce the value range before calling a `ftw' callback.  */
683   data.cvt_arr = is_nftw ? nftw_arr : ftw_arr;
684 
685   /* No object known so far.  */
686   data.known_objects = NULL;
687 
688   /* Now go to the directory containing the initial file/directory.  */
689   if (flags & FTW_CHDIR)
690     {
691       /* We have to be able to go back to the current working
692 	 directory.  The best way to do this is to use a file
693 	 descriptor.  */
694       cwdfd = __open (".", O_RDONLY | O_DIRECTORY);
695       if (cwdfd == -1)
696 	{
697 	  /* Try getting the directory name.  This can be needed if
698 	     the current directory is executable but not readable.  */
699 	  if (errno == EACCES)
700 	    /* GNU extension ahead.  */
701 	    cwd =  __getcwd (NULL, 0);
702 
703 	  if (cwd == NULL)
704 	    goto out_fail;
705 	}
706       else if (data.maxdir > 1)
707 	/* Account for the file descriptor we use here.  */
708 	--data.maxdir;
709 
710       if (data.ftw.base > 0)
711 	{
712 	  /* Change to the directory the file is in.  In data.dirbuf
713 	     we have a writable copy of the file name.  Just NUL
714 	     terminate it for now and change the directory.  */
715 	  if (data.ftw.base == 1)
716 	    /* I.e., the file is in the root directory.  */
717 	    result = __chdir ("/");
718 	  else
719 	    {
720 	      char ch = data.dirbuf[data.ftw.base - 1];
721 	      data.dirbuf[data.ftw.base - 1] = '\0';
722 	      result = __chdir (data.dirbuf);
723 	      data.dirbuf[data.ftw.base - 1] = ch;
724 	    }
725 	}
726     }
727 
728   /* Get stat info for start directory.  */
729   if (result == 0)
730     {
731       const char *name;
732 
733       if (data.flags & FTW_CHDIR)
734 	{
735 	  name = data.dirbuf + data.ftw.base;
736 	  if (name[0] == '\0')
737 	    name = ".";
738 	}
739       else
740 	name = data.dirbuf;
741 
742       if (((flags & FTW_PHYS)
743 	   ? LSTAT (name, &st)
744 	   : STAT (name, &st)) < 0)
745 	{
746 	  if (!(flags & FTW_PHYS)
747 	      && errno == ENOENT
748 	      && LSTAT (name, &st) == 0
749 	      && S_ISLNK (st.st_mode))
750 	    result = (*data.func) (data.dirbuf, &st, data.cvt_arr[FTW_SLN],
751 				   &data.ftw);
752 	  else
753 	    /* No need to call the callback since we cannot say anything
754 	       about the object.  */
755 	    result = -1;
756 	}
757       else
758 	{
759 	  if (S_ISDIR (st.st_mode))
760 	    {
761 	      /* Remember the device of the initial directory in case
762 		 FTW_MOUNT is given.  */
763 	      data.dev = st.st_dev;
764 
765 	      /* We know this directory now.  */
766 	      if (!(flags & FTW_PHYS))
767 		result = add_object (&data, &st);
768 
769 	      if (result == 0)
770 		result = ftw_dir (&data, &st, NULL);
771 	    }
772 	  else
773 	    {
774 	      int flag = S_ISLNK (st.st_mode) ? FTW_SL : FTW_F;
775 
776 	      result = (*data.func) (data.dirbuf, &st, data.cvt_arr[flag],
777 				     &data.ftw);
778 	    }
779 	}
780 
781       if ((flags & FTW_ACTIONRETVAL)
782 	  && (result == FTW_SKIP_SUBTREE || result == FTW_SKIP_SIBLINGS))
783 	result = 0;
784     }
785 
786   /* Return to the start directory (if necessary).  */
787   if (cwdfd != -1)
788     {
789       int save_err = errno;
790       __fchdir (cwdfd);
791       __close_nocancel_nostatus (cwdfd);
792       __set_errno (save_err);
793     }
794   else if (cwd != NULL)
795     {
796       int save_err = errno;
797       __chdir (cwd);
798       free (cwd);
799       __set_errno (save_err);
800     }
801 
802   /* Free all memory.  */
803  out_fail:
804   save_err = errno;
805   __tdestroy (data.known_objects, free);
806   free (data.dirstreams);
807   __set_errno (save_err);
808 
809   return result;
810 }
811 
812 
813 
814 /* Entry points.  */
815 
816 int
FTW_NAME(const char * path,FTW_FUNC_T func,int descriptors)817 FTW_NAME (const char *path, FTW_FUNC_T func, int descriptors)
818 {
819   return ftw_startup (path, 0, func, descriptors, 0);
820 }
821 
822 #ifndef NFTW_OLD_NAME
823 int
NFTW_NAME(const char * path,NFTW_FUNC_T func,int descriptors,int flags)824 NFTW_NAME (const char *path, NFTW_FUNC_T func, int descriptors, int flags)
825 {
826   return ftw_startup (path, 1, func, descriptors, flags);
827 }
828 #else
829 
830 # include <shlib-compat.h>
831 
832 int NFTW_NEW_NAME (const char *, NFTW_FUNC_T, int, int);
833 
834 int
NFTW_NEW_NAME(const char * path,NFTW_FUNC_T func,int descriptors,int flags)835 NFTW_NEW_NAME (const char *path, NFTW_FUNC_T func, int descriptors, int flags)
836 {
837   if (flags
838       & ~(FTW_PHYS | FTW_MOUNT | FTW_CHDIR | FTW_DEPTH | FTW_ACTIONRETVAL))
839     {
840       __set_errno (EINVAL);
841       return -1;
842     }
843   return ftw_startup (path, 1, func, descriptors, flags);
844 }
845 versioned_symbol (libc, NFTW_NEW_NAME, NFTW_NAME, GLIBC_2_3_3);
846 
847 # if SHLIB_COMPAT(libc, GLIBC_2_1, GLIBC_2_3_3)
848 
849 /* Older nftw* version just ignored all unknown flags.  */
850 
851 int NFTW_OLD_NAME (const char *, NFTW_FUNC_T, int, int);
852 
853 int
854 attribute_compat_text_section
NFTW_OLD_NAME(const char * path,NFTW_FUNC_T func,int descriptors,int flags)855 NFTW_OLD_NAME (const char *path, NFTW_FUNC_T func, int descriptors, int flags)
856 {
857   flags &= (FTW_PHYS | FTW_MOUNT | FTW_CHDIR | FTW_DEPTH);
858   return ftw_startup (path, 1, func, descriptors, flags);
859 }
860 
861 compat_symbol (libc, NFTW_OLD_NAME, NFTW_NAME, GLIBC_2_1);
862 # endif
863 #endif /* NFTW_OLD_NAME  */
864