rpm  4.5
fts.c
Go to the documentation of this file.
1 /*@-boundsread@*/
2 /*@-sysunrecog -noeffectuncon -nullpass -sizeoftype -unrecog -usereleased @*/
3 /*@-compdef -compmempass -dependenttrans -retalias @*/
4 /*-
5  * Copyright (c) 1990, 1993, 1994
6  * The Regents of the University of California. All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions
10  * are met:
11  * 1. Redistributions of source code must retain the above copyright
12  * notice, this list of conditions and the following disclaimer.
13  * 2. Redistributions in binary form must reproduce the above copyright
14  * notice, this list of conditions and the following disclaimer in the
15  * documentation and/or other materials provided with the distribution.
16  * 4. Neither the name of the University nor the names of its contributors
17  * may be used to endorse or promote products derived from this software
18  * without specific prior written permission.
19  *
20  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
21  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
22  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
23  * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
24  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
25  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
26  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
27  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
28  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
29  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
30  * SUCH DAMAGE.
31  */
32 
33 #if defined(LIBC_SCCS) && !defined(lint)
34 static char sccsid[] = "@(#)fts.c 8.6 (Berkeley) 8/14/94";
35 #endif /* LIBC_SCCS and not lint */
36 
37 #if defined(_LIBC)
38 #include <sys/param.h>
39 #include <include/sys/stat.h>
40 #include <fcntl.h>
41 #include <dirent.h>
42 #include <errno.h>
43 #include <fts.h>
44 #include <stdlib.h>
45 #include <string.h>
46 #include <unistd.h>
47 #else
48 #if defined(hpux) || defined(__hpux)
49 # define _INCLUDE_POSIX_SOURCE
50 # define __errno_location() (&errno)
51 # define dirfd(dirp) -1
52 # define stat64 stat
53 # define _STAT_VER 0
54 # define __fxstat64(_stat_ver, _fd, _sbp) fstat((_fd), (_sbp))
55 #endif
56 #if defined(sun)
57 # define __errno_location() (&errno)
58 # define dirfd(dirp) -1
59 # define _STAT_VER 0
60 # define __fxstat64(_stat_ver, _fd, _sbp) fstat((_fd), (_sbp))
61 #endif
62 #if defined(__APPLE__)
63 # define __errno_location() (__error())
64 # define stat64 stat
65 # define _STAT_VER 0
66 # define __fxstat64(_stat_ver, _fd, _sbp) fstat((_fd), (_sbp))
67 #endif
68 #if defined(__FreeBSD__)
69 # define __errno_location() (&errno)
70 # define stat64 stat
71 # define __fxstat64(_stat_ver, _fd, _sbp) fstat((_fd), (_sbp))
72 #endif
73 #include "system.h"
74 #include "fts.h"
75 #include "rpmio.h"
76 #include "rpmurl.h"
77 # define __set_errno(val) (*__errno_location ()) = (val)
78 # define __open open
79 # define __close close
80 # define __fchdir fchdir
81 #endif
82 
83 #if !defined(USHRT_MAX)
84 #define USHRT_MAX 65535
85 #endif
86 
87 /* Largest alignment size needed, minus one.
88  Usually long double is the worst case. */
89 #ifndef ALIGNBYTES
90 #if defined __GNUC__ && __GNUC__ >= 2
91 # define alignof(TYPE) __alignof__ (TYPE)
92 #else
93 # define alignof(TYPE) \
94  ((int) &((struct { char dummy1; TYPE dummy2; } *) 0)->dummy2)
95 #endif
96 #define ALIGNBYTES (alignof(long double) - 1)
97 #endif
98 /* Align P to that size. */
99 #ifndef ALIGN
100 #define ALIGN(p) (((unsigned long int) (p) + ALIGNBYTES) & ~ALIGNBYTES)
101 #endif
102 
103 /*@unchecked@*/
104 static int _fts_debug = 0;
105 
106 /*@only@*/ /*@null@*/
107 static FTSENT * fts_alloc(FTS * sp, const char * name, int namelen)
108  /*@*/;
109 /*@null@*/
110 static FTSENT * fts_build(FTS * sp, int type)
111  /*@globals fileSystem, internalState @*/
112  /*@modifies *sp, fileSystem, internalState @*/;
113 static void fts_lfree(/*@only@*/ FTSENT * head)
114  /*@modifies head @*/;
115 static void fts_load(FTS * sp, FTSENT * p)
116  /*@modifies *sp, *p @*/;
117 static size_t fts_maxarglen(char * const * argv)
118  /*@*/;
119 static void fts_padjust(FTS * sp, FTSENT * head)
120  /*@modifies *sp, *head @*/;
121 static int fts_palloc(FTS * sp, size_t more)
122  /*@modifies *sp @*/;
123 static FTSENT * fts_sort(FTS * sp, /*@returned@*/ FTSENT * head, int nitems)
124  /*@modifies *sp @*/;
125 static u_short fts_stat(FTS * sp, FTSENT * p, int follow)
126  /*@modifies *p @*/;
127 static int fts_safe_changedir(FTS * sp, FTSENT * p, int fd,
128  const char * path)
129  /*@globals fileSystem, internalState @*/
130  /*@modifies fileSystem, internalState @*/;
131 
132 #define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
133 
134 #define CLR(opt) (sp->fts_options &= ~(opt))
135 #define ISSET(opt) (sp->fts_options & (opt))
136 #define SET(opt) (sp->fts_options |= (opt))
137 
138 #define FCHDIR(sp, fd) (!ISSET(FTS_NOCHDIR) && __fchdir(fd))
139 
140 /* fts_build flags */
141 #define BCHILD 1 /* fts_children */
142 #define BNAMES 2 /* fts_children, names only */
143 #define BREAD 3 /* fts_read */
144 
145 FTS *
146 Fts_open(char * const * argv, int options,
147  int (*compar) (const FTSENT **, const FTSENT **))
148 {
149  register FTS *sp;
150  register FTSENT *p, *root;
151  register int nitems;
152  FTSENT *parent = NULL;
153  FTSENT *tmp = NULL;
154  size_t len;
155 
156 /*@-formattype -modfilesys@*/
157 if (_fts_debug)
158 fprintf(stderr, "*** Fts_open(%p, 0x%x, %p)\n", argv, options, compar);
159 /*@=formattype =modfilesys@*/
160 
161  /* Options check. */
162  if (options & ~FTS_OPTIONMASK) {
163 /*@-boundswrite@*/
164  __set_errno (EINVAL);
165 /*@=boundswrite@*/
166  return (NULL);
167  }
168 
169  /* Allocate/initialize the stream */
170  if ((sp = malloc((u_int)sizeof(*sp))) == NULL)
171  return (NULL);
172  memset(sp, 0, sizeof(*sp));
173  sp->fts_compar = (int (*) (const void *, const void *)) compar;
174  sp->fts_opendir = Opendir;
175  sp->fts_readdir = Readdir;
176  sp->fts_closedir = Closedir;
177  sp->fts_stat = Stat;
178  sp->fts_lstat = Lstat;
179  sp->fts_options = options;
180 
181  /* Logical walks turn on NOCHDIR; symbolic links are too hard. */
182  if (ISSET(FTS_LOGICAL))
183  SET(FTS_NOCHDIR);
184 
185  /*
186  * Start out with 1K of path space, and enough, in any case,
187  * to hold the user's paths.
188  */
189 #ifndef MAXPATHLEN
190 #define MAXPATHLEN 1024
191 #endif
192  len = fts_maxarglen(argv);
193  if (len < MAXPATHLEN)
194  len = MAXPATHLEN;
195  if (fts_palloc(sp, len))
196  goto mem1;
197 
198  /* Allocate/initialize root's parent. */
199 /*@-branchstate@*/
200  if (*argv != NULL) {
201  if ((parent = fts_alloc(sp, "", 0)) == NULL)
202  goto mem2;
203  parent->fts_level = FTS_ROOTPARENTLEVEL;
204  }
205 /*@=branchstate@*/
206 
207  /* Allocate/initialize root(s). */
208  for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) {
209  /* Don't allow zero-length paths. */
210  if ((len = strlen(*argv)) == 0) {
211 /*@-boundswrite@*/
212  __set_errno (ENOENT);
213 /*@=boundswrite@*/
214  goto mem3;
215  }
216 
217  /* Use fchdir(2) speedup only if local DASDI. */
218  switch (urlIsURL(*argv)) {
219  case URL_IS_DASH:
220  case URL_IS_HKP:
221 /*@-boundswrite@*/
222  __set_errno (ENOENT);
223 /*@=boundswrite@*/
224  goto mem3;
225  /*@notreached@*/ /*@switchbreak@*/ break;
226  case URL_IS_HTTPS:
227  case URL_IS_HTTP:
228  case URL_IS_FTP:
229  SET(FTS_NOCHDIR);
230  /*@switchbreak@*/ break;
231  case URL_IS_UNKNOWN:
232  case URL_IS_PATH:
233  /*@switchbreak@*/ break;
234  }
235 
236  p = fts_alloc(sp, *argv, len);
237  if (p == NULL)
238  goto mem3;
240  p->fts_parent = parent;
241  p->fts_accpath = p->fts_name;
242  p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW));
243 
244  /* Command-line "." and ".." are real directories. */
245  if (p->fts_info == FTS_DOT)
246  p->fts_info = FTS_D;
247 
248  /*
249  * If comparison routine supplied, traverse in sorted
250  * order; otherwise traverse in the order specified.
251  */
252  if (compar) {
253  p->fts_link = root;
254  root = p;
255  } else {
256  p->fts_link = NULL;
257  if (root == NULL)
258  tmp = root = p;
259  else {
260  if (tmp != NULL) /* XXX can't happen */
261  tmp->fts_link = p;
262  tmp = p;
263  }
264  }
265  }
266  /*@-branchstate@*/
267  if (compar && nitems > 1)
268  root = fts_sort(sp, root, nitems);
269  /*@=branchstate@*/
270 
271  /*
272  * Allocate a dummy pointer and make fts_read think that we've just
273  * finished the node before the root(s); set p->fts_info to FTS_INIT
274  * so that everything about the "current" node is ignored.
275  */
276  if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
277  goto mem3;
278  sp->fts_cur->fts_link = root;
279  sp->fts_cur->fts_info = FTS_INIT;
280 
281  /*
282  * If using chdir(2), grab a file descriptor pointing to dot to ensure
283  * that we can get back here; this could be avoided for some paths,
284  * but almost certainly not worth the effort. Slashes, symbolic links,
285  * and ".." are all fairly nasty problems. Note, if we can't get the
286  * descriptor we run anyway, just more slowly.
287  */
288  if (!ISSET(FTS_NOCHDIR)
289  && (sp->fts_rfd = __open(".", O_RDONLY, 0)) < 0)
290  SET(FTS_NOCHDIR);
291 
292  return (sp);
293 
294 mem3: fts_lfree(root);
295  free(parent);
296 mem2: free(sp->fts_path);
297 mem1: free(sp);
298  return (NULL);
299 }
300 
301 static void
302 fts_load(FTS * sp, FTSENT * p)
303 {
304  register int len;
305  register char *cp;
306 
307  /*
308  * Load the stream structure for the next traversal. Since we don't
309  * actually enter the directory until after the preorder visit, set
310  * the fts_accpath field specially so the chdir gets done to the right
311  * place and the user can access the first node. From fts_open it's
312  * known that the path will fit.
313  */
314  len = p->fts_pathlen = p->fts_namelen;
315 /*@-boundswrite@*/
316  memmove(sp->fts_path, p->fts_name, len + 1);
317  if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
318  len = strlen(++cp);
319  memmove(p->fts_name, cp, len + 1);
320  p->fts_namelen = len;
321  }
322  p->fts_accpath = p->fts_path = sp->fts_path;
323  sp->fts_dev = p->fts_dev;
324 /*@=boundswrite@*/
325 }
326 
327 int
329 {
330  register FTSENT *freep, *p;
331  int saved_errno;
332 
333  if (sp == NULL)
334  return 0;
335 
336  /*
337  * This still works if we haven't read anything -- the dummy structure
338  * points to the root list, so we step through to the end of the root
339  * list which has a valid parent pointer.
340  */
341  /*@-branchstate@*/
342  if (sp->fts_cur) {
343  for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
344  freep = p;
345  p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
346  free(freep);
347  }
348  free(p);
349  }
350  /*@=branchstate@*/
351 
352  /* Free up child linked list, sort array, path buffer. */
353  if (sp->fts_child)
354  fts_lfree(sp->fts_child);
355  if (sp->fts_array)
356  free(sp->fts_array);
357  free(sp->fts_path);
358 
359  /* Return to original directory, save errno if necessary. */
360  if (!ISSET(FTS_NOCHDIR)) {
361  saved_errno = __fchdir(sp->fts_rfd) ? errno : 0;
362  (void)__close(sp->fts_rfd);
363 
364  /* Set errno and return. */
365  if (saved_errno != 0) {
366  /* Free up the stream pointer. */
367  free(sp);
368 /*@-boundswrite@*/
369  __set_errno (saved_errno);
370 /*@=boundswrite@*/
371  return (-1);
372  }
373  }
374 
375  /* Free up the stream pointer. */
376  free(sp);
377  return (0);
378 }
379 
380 /*
381  * Special case of "/" at the end of the path so that slashes aren't
382  * appended which would cause paths to be written as "....//foo".
383  */
384 #define NAPPEND(p) \
385  (p->fts_path[p->fts_pathlen - 1] == '/' \
386  ? p->fts_pathlen - 1 : p->fts_pathlen)
387 
388 FTSENT *
390 {
391  register FTSENT *p;
392  register FTSENT *tmp;
393  register int instr;
394  register char *t;
395  int saved_errno;
396 
397  /* If finished or unrecoverable error, return NULL. */
398  if (sp == NULL || sp->fts_cur == NULL || ISSET(FTS_STOP))
399  return (NULL);
400 
401  /* Set current node pointer. */
402  p = sp->fts_cur;
403 
404  /* Save and zero out user instructions. */
405  instr = p->fts_instr;
406  p->fts_instr = FTS_NOINSTR;
407 
408  /* Any type of file may be re-visited; re-stat and re-turn. */
409  if (instr == FTS_AGAIN) {
410  p->fts_info = fts_stat(sp, p, 0);
411  return (p);
412  }
413 
414  /*
415  * Following a symlink -- SLNONE test allows application to see
416  * SLNONE and recover. If indirecting through a symlink, have
417  * keep a pointer to current location. If unable to get that
418  * pointer, follow fails.
419  */
420  if (instr == FTS_FOLLOW &&
421  (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
422  p->fts_info = fts_stat(sp, p, 1);
423  if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
424  if ((p->fts_symfd = __open(".", O_RDONLY, 0)) < 0) {
425  p->fts_errno = errno;
426  p->fts_info = FTS_ERR;
427  } else
428  p->fts_flags |= FTS_SYMFOLLOW;
429  }
430  return (p);
431  }
432 
433  /* Directory in pre-order. */
434  if (p->fts_info == FTS_D) {
435  /* If skipped or crossed mount point, do post-order visit. */
436  if (instr == FTS_SKIP ||
437  (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
438  if (p->fts_flags & FTS_SYMFOLLOW)
439  (void)__close(p->fts_symfd);
440  if (sp->fts_child) {
441  fts_lfree(sp->fts_child);
442  sp->fts_child = NULL;
443  }
444  p->fts_info = FTS_DP;
445  return (p);
446  }
447 
448  /* Rebuild if only read the names and now traversing. */
449  if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) {
450  CLR(FTS_NAMEONLY);
451  fts_lfree(sp->fts_child);
452  sp->fts_child = NULL;
453  }
454 
455  /*
456  * Cd to the subdirectory.
457  *
458  * If have already read and now fail to chdir, whack the list
459  * to make the names come out right, and set the parent errno
460  * so the application will eventually get an error condition.
461  * Set the FTS_DONTCHDIR flag so that when we logically change
462  * directories back to the parent we don't do a chdir.
463  *
464  * If haven't read do so. If the read fails, fts_build sets
465  * FTS_STOP or the fts_info field of the node.
466  */
467  if (sp->fts_child != NULL) {
468  if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
469  p->fts_errno = errno;
470  p->fts_flags |= FTS_DONTCHDIR;
471  for (p = sp->fts_child; p != NULL;
472  p = p->fts_link)
473  p->fts_accpath =
475  }
476  } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
477  if (ISSET(FTS_STOP))
478  return (NULL);
479  return (p);
480  }
481  p = sp->fts_child;
482  sp->fts_child = NULL;
483  sp->fts_cur = p;
484  goto name;
485  }
486 
487  /* Move to the next node on this level. */
488 /*@-boundswrite@*/
489 next: tmp = p;
490  if ((p = p->fts_link) != NULL) {
491  sp->fts_cur = p;
492  free(tmp);
493 
494  /*
495  * If reached the top, return to the original directory (or
496  * the root of the tree), and load the paths for the next root.
497  */
498  if (p->fts_level == FTS_ROOTLEVEL) {
499  if (FCHDIR(sp, sp->fts_rfd)) {
500  SET(FTS_STOP);
501  return (NULL);
502  }
503  fts_load(sp, p);
504  return (p);
505  }
506 
507  /*
508  * User may have called fts_set on the node. If skipped,
509  * ignore. If followed, get a file descriptor so we can
510  * get back if necessary.
511  */
512  if (p->fts_instr == FTS_SKIP)
513  goto next;
514  /*@-branchstate@*/
515  if (p->fts_instr == FTS_FOLLOW) {
516  p->fts_info = fts_stat(sp, p, 1);
517  if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
518  if ((p->fts_symfd =
519  __open(".", O_RDONLY, 0)) < 0) {
520  p->fts_errno = errno;
521  p->fts_info = FTS_ERR;
522  } else
523  p->fts_flags |= FTS_SYMFOLLOW;
524  }
525  p->fts_instr = FTS_NOINSTR;
526  }
527  /*@=branchstate@*/
528 
529 name: t = sp->fts_path + NAPPEND(p->fts_parent);
530  *t++ = '/';
531  memmove(t, p->fts_name, p->fts_namelen + 1);
532  return (p);
533  }
534 
535  /* Move up to the parent node. */
536  p = tmp->fts_parent;
537  sp->fts_cur = p;
538  free(tmp);
539 
540  if (p->fts_level == FTS_ROOTPARENTLEVEL) {
541  /*
542  * Done; free everything up and set errno to 0 so the user
543  * can distinguish between error and EOF.
544  */
545  free(p);
546  __set_errno (0);
547  return (sp->fts_cur = NULL);
548  }
549 
550  /* NUL terminate the pathname. */
551  sp->fts_path[p->fts_pathlen] = '\0';
552 /*@=boundswrite@*/
553 
554  /*
555  * Return to the parent directory. If at a root node or came through
556  * a symlink, go back through the file descriptor. Otherwise, cd up
557  * one directory.
558  */
559  if (p->fts_level == FTS_ROOTLEVEL) {
560  if (FCHDIR(sp, sp->fts_rfd)) {
561  SET(FTS_STOP);
562  return (NULL);
563  }
564  } else if (p->fts_flags & FTS_SYMFOLLOW) {
565  if (FCHDIR(sp, p->fts_symfd)) {
566  saved_errno = errno;
567  (void)__close(p->fts_symfd);
568 /*@-boundswrite@*/
569  __set_errno (saved_errno);
570 /*@=boundswrite@*/
571  SET(FTS_STOP);
572  return (NULL);
573  }
574  (void)__close(p->fts_symfd);
575  } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
576  fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
577  SET(FTS_STOP);
578  return (NULL);
579  }
580  p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
581  return (p);
582 }
583 
584 /*
585  * Fts_set takes the stream as an argument although it's not used in this
586  * implementation; it would be necessary if anyone wanted to add global
587  * semantics to fts using fts_set. An error return is allowed for similar
588  * reasons.
589  */
590 int
591 Fts_set(/*@unused@*/ FTS * sp, FTSENT * p, int instr)
592 {
593 /*@-modfilesys@*/
594 if (_fts_debug)
595 fprintf(stderr, "*** Fts_set(%p, %p, 0x%x)\n", sp, p, instr);
596 /*@=modfilesys@*/
597 
598  if (instr != 0 && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
599  instr != FTS_NOINSTR && instr != FTS_SKIP) {
600 /*@-boundswrite@*/
601  __set_errno (EINVAL);
602 /*@=boundswrite@*/
603  return (1);
604  }
605  p->fts_instr = instr;
606  return (0);
607 }
608 
609 FTSENT *
610 Fts_children(FTS * sp, int instr)
611 {
612  register FTSENT *p;
613  int fd;
614 
615 /*@-modfilesys@*/
616 if (_fts_debug)
617 fprintf(stderr, "*** Fts_children(%p, 0x%x)\n", sp, instr);
618 /*@=modfilesys@*/
619 
620  if (instr != 0 && instr != FTS_NAMEONLY) {
621 /*@-boundswrite@*/
622  __set_errno (EINVAL);
623 /*@=boundswrite@*/
624  return (NULL);
625  }
626 
627  /* Set current node pointer. */
628  p = sp->fts_cur;
629 
630  /*
631  * Errno set to 0 so user can distinguish empty directory from
632  * an error.
633  */
634 /*@-boundswrite@*/
635  __set_errno (0);
636 /*@=boundswrite@*/
637 
638  /* Fatal errors stop here. */
639  if (ISSET(FTS_STOP))
640  return (NULL);
641 
642  /* Return logical hierarchy of user's arguments. */
643  if (p->fts_info == FTS_INIT)
644  return (p->fts_link);
645 
646  /*
647  * If not a directory being visited in pre-order, stop here. Could
648  * allow FTS_DNR, assuming the user has fixed the problem, but the
649  * same effect is available with FTS_AGAIN.
650  */
651  if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
652  return (NULL);
653 
654  /* Free up any previous child list. */
655  if (sp->fts_child != NULL)
656  fts_lfree(sp->fts_child);
657 
658  if (instr == FTS_NAMEONLY) {
659  SET(FTS_NAMEONLY);
660  instr = BNAMES;
661  } else
662  instr = BCHILD;
663 
664  /*
665  * If using chdir on a relative path and called BEFORE fts_read does
666  * its chdir to the root of a traversal, we can lose -- we need to
667  * chdir into the subdirectory, and we don't know where the current
668  * directory is, so we can't get back so that the upcoming chdir by
669  * fts_read will work.
670  */
671  if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
673  return (sp->fts_child = fts_build(sp, instr));
674 
675  if ((fd = __open(".", O_RDONLY, 0)) < 0)
676  return (NULL);
677  sp->fts_child = fts_build(sp, instr);
678  if (__fchdir(fd))
679  return (NULL);
680  (void)__close(fd);
681  return (sp->fts_child);
682 }
683 
684 /*
685  * This is the tricky part -- do not casually change *anything* in here. The
686  * idea is to build the linked list of entries that are used by fts_children
687  * and fts_read. There are lots of special cases.
688  *
689  * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is
690  * set and it's a physical walk (so that symbolic links can't be directories),
691  * we can do things quickly. First, if it's a 4.4BSD file system, the type
692  * of the file is in the directory entry. Otherwise, we assume that the number
693  * of subdirectories in a node is equal to the number of links to the parent.
694  * The former skips all stat calls. The latter skips stat calls in any leaf
695  * directories and for any files after the subdirectories in the directory have
696  * been found, cutting the stat calls by about 2/3.
697  */
698 static FTSENT *
699 fts_build(FTS * sp, int type)
700 {
701  register struct dirent *dp;
702  register FTSENT *p, *head;
703  register int nitems;
704  FTSENT *cur, *tail;
705  DIR *dirp;
706  void *oldaddr;
707  int cderrno, descend, len, level, nlinks, saved_errno,
708  nostat, doadjust;
709  size_t maxlen;
710  char *cp;
711 
712  /* Set current node pointer. */
713  cur = sp->fts_cur;
714 
715  /*
716  * Open the directory for reading. If this fails, we're done.
717  * If being called from fts_read, set the fts_info field.
718  */
719 #if defined FTS_WHITEOUT && 0
720  if (ISSET(FTS_WHITEOUT))
721  oflag = DTF_NODUP|DTF_REWIND;
722  else
723  oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
724 #else
725 # define __opendir2(path, flag) (*sp->fts_opendir) (path)
726 #endif
727  if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
728  if (type == BREAD) {
729  cur->fts_info = FTS_DNR;
730  cur->fts_errno = errno;
731  }
732  return (NULL);
733  }
734 
735  /*
736  * Nlinks is the number of possible entries of type directory in the
737  * directory if we're cheating on stat calls, 0 if we're not doing
738  * any stat calls at all, -1 if we're doing stats on everything.
739  */
740  if (type == BNAMES) {
741  nlinks = 0;
742  /* Be quiet about nostat, GCC. */
743  nostat = 0;
744  } else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
745  nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
746  nostat = 1;
747  } else {
748  nlinks = -1;
749  nostat = 0;
750  }
751 
752 #ifdef notdef
753  (void)printf("nlinks == %d (cur: %d)\n", nlinks, cur->fts_nlink);
754  (void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
756 #endif
757  /*
758  * If we're going to need to stat anything or we want to descend
759  * and stay in the directory, chdir. If this fails we keep going,
760  * but set a flag so we don't chdir after the post-order visit.
761  * We won't be able to stat anything, but we can still return the
762  * names themselves. Note, that since fts_read won't be able to
763  * chdir into the directory, it will have to return different path
764  * names than before, i.e. "a/b" instead of "b". Since the node
765  * has already been visited in pre-order, have to wait until the
766  * post-order visit to return the error. There is a special case
767  * here, if there was nothing to stat then it's not an error to
768  * not be able to stat. This is all fairly nasty. If a program
769  * needed sorted entries or stat information, they had better be
770  * checking FTS_NS on the returned nodes.
771  */
772  cderrno = 0;
773  if (nlinks || type == BREAD) {
774  if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) {
775  if (nlinks && type == BREAD)
776  cur->fts_errno = errno;
777  cur->fts_flags |= FTS_DONTCHDIR;
778  descend = 0;
779  cderrno = errno;
780  (void) (*sp->fts_closedir) (dirp);
781  dirp = NULL;
782  } else
783  descend = 1;
784  } else
785  descend = 0;
786 
787  /*
788  * Figure out the max file name length that can be stored in the
789  * current path -- the inner loop allocates more path as necessary.
790  * We really wouldn't have to do the maxlen calculations here, we
791  * could do them in fts_read before returning the path, but it's a
792  * lot easier here since the length is part of the dirent structure.
793  *
794  * If not changing directories set a pointer so that can just append
795  * each new name into the path.
796  */
797  len = NAPPEND(cur);
798  if (ISSET(FTS_NOCHDIR)) {
799  cp = sp->fts_path + len;
800 /*@-boundswrite@*/
801  *cp++ = '/';
802 /*@=boundswrite@*/
803  } else {
804  /* GCC, you're too verbose. */
805  cp = NULL;
806  }
807  len++;
808  maxlen = sp->fts_pathlen - len;
809 
810  level = cur->fts_level + 1;
811 
812  /* Read the directory, attaching each entry to the `link' pointer. */
813  doadjust = 0;
814  for (head = tail = NULL, nitems = 0;
815  dirp && (dp = (*sp->fts_readdir) (dirp));)
816  {
817  if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
818  continue;
819 
820  if ((p = fts_alloc(sp, dp->d_name, (int)_D_EXACT_NAMLEN (dp))) == NULL)
821  goto mem1;
822  if (_D_EXACT_NAMLEN (dp) >= maxlen) {/* include space for NUL */
823  oldaddr = sp->fts_path;
824  if (fts_palloc(sp, _D_EXACT_NAMLEN (dp) + len + 1)) {
825  /*
826  * No more memory for path or structures. Save
827  * errno, free up the current structure and the
828  * structures already allocated.
829  */
830 mem1: saved_errno = errno;
831  if (p)
832  free(p);
833  fts_lfree(head);
834  (void) (*sp->fts_closedir) (dirp);
835  cur->fts_info = FTS_ERR;
836  SET(FTS_STOP);
837  __set_errno (saved_errno);
838  return (NULL);
839  }
840  /* Did realloc() change the pointer? */
841  if (oldaddr != sp->fts_path) {
842  doadjust = 1;
843  if (ISSET(FTS_NOCHDIR))
844  cp = sp->fts_path + len;
845  }
846  maxlen = sp->fts_pathlen - len;
847  }
848 
849  if (len + _D_EXACT_NAMLEN (dp) >= USHRT_MAX) {
850  /*
851  * In an FTSENT, fts_pathlen is a u_short so it is
852  * possible to wraparound here. If we do, free up
853  * the current structure and the structures already
854  * allocated, then error out with ENAMETOOLONG.
855  */
856  free(p);
857  fts_lfree(head);
858  (void) (*sp->fts_closedir) (dirp);
859  cur->fts_info = FTS_ERR;
860  SET(FTS_STOP);
861  __set_errno (ENAMETOOLONG);
862  return (NULL);
863  }
864  p->fts_level = level;
865  p->fts_parent = sp->fts_cur;
866  p->fts_pathlen = len + _D_EXACT_NAMLEN (dp);
867 
868 #if defined FTS_WHITEOUT && 0
869  if (dp->d_type == DT_WHT)
870  p->fts_flags |= FTS_ISW;
871 #endif
872 
873 #if 0
874  /*
875  * Unreachable code. cderrno is only ever set to a nonnull
876  * value if dirp is closed at the same time. But then we
877  * cannot enter this loop.
878  */
879  if (cderrno) {
880  if (nlinks) {
881  p->fts_info = FTS_NS;
882  p->fts_errno = cderrno;
883  } else
884  p->fts_info = FTS_NSOK;
885  p->fts_accpath = cur->fts_accpath;
886  } else
887 #endif
888  if (nlinks == 0
889 #if defined DT_DIR && defined _DIRENT_HAVE_D_TYPE
890  || (nostat &&
891  dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN)
892 #endif
893  ) {
894  p->fts_accpath =
895  ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
896  p->fts_info = FTS_NSOK;
897  } else {
898  /* Build a file name for fts_stat to stat. */
899  if (ISSET(FTS_NOCHDIR)) {
900  p->fts_accpath = p->fts_path;
901  memmove(cp, p->fts_name, p->fts_namelen + 1);
902  } else
903  p->fts_accpath = p->fts_name;
904  /* Stat it. */
905  p->fts_info = fts_stat(sp, p, 0);
906 
907  /* Decrement link count if applicable. */
908  if (nlinks > 0 && (p->fts_info == FTS_D ||
909  p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
910  --nlinks;
911  }
912 
913  /* We walk in directory order so "ls -f" doesn't get upset. */
914  p->fts_link = NULL;
915  if (head == NULL)
916  head = tail = p;
917  else {
918  tail->fts_link = p;
919  tail = p;
920  }
921  ++nitems;
922  }
923  if (dirp)
924  (void) (*sp->fts_closedir) (dirp);
925 
926  /*
927  * If realloc() changed the address of the path, adjust the
928  * addresses for the rest of the tree and the dir list.
929  */
930  if (doadjust)
931  fts_padjust(sp, head);
932 
933  /*
934  * If not changing directories, reset the path back to original
935  * state.
936  */
937  if (ISSET(FTS_NOCHDIR)) {
938  if (len == sp->fts_pathlen || nitems == 0)
939  --cp;
940 /*@-boundswrite@*/
941  if (cp != NULL) /* XXX can't happen */
942  *cp = '\0';
943 /*@=boundswrite@*/
944  }
945 
946  /*
947  * If descended after called from fts_children or after called from
948  * fts_read and nothing found, get back. At the root level we use
949  * the saved fd; if one of fts_open()'s arguments is a relative path
950  * to an empty directory, we wind up here with no other way back. If
951  * can't get back, we're done.
952  */
953  if (descend && (type == BCHILD || !nitems) &&
954  (cur->fts_level == FTS_ROOTLEVEL ?
955  FCHDIR(sp, sp->fts_rfd) :
956  fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
957  cur->fts_info = FTS_ERR;
958  SET(FTS_STOP);
959  fts_lfree(head);
960  return (NULL);
961  }
962 
963  /* If didn't find anything, return NULL. */
964  if (!nitems) {
965  if (type == BREAD)
966  cur->fts_info = FTS_DP;
967  fts_lfree(head);
968  return (NULL);
969  }
970 
971  /* Sort the entries. */
972  if (sp->fts_compar && nitems > 1)
973  head = fts_sort(sp, head, nitems);
974  return (head);
975 }
976 
977 static u_short
978 fts_stat(FTS * sp, FTSENT * p, int follow)
979 {
980  register FTSENT *t;
981  register dev_t dev;
982  register ino_t ino;
983  struct stat *sbp, sb;
984  int saved_errno;
985 
986  /* If user needs stat info, stat buffer already allocated. */
987  sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
988 
989 #if defined FTS_WHITEOUT && 0
990  /* check for whiteout */
991  if (p->fts_flags & FTS_ISW) {
992  if (sbp != &sb) {
993  memset(sbp, '\0', sizeof (*sbp));
994  sbp->st_mode = S_IFWHT;
995  }
996  return (FTS_W);
997  }
998 #endif
999 
1000  /*
1001  * If doing a logical walk, or application requested FTS_FOLLOW, do
1002  * a stat(2). If that fails, check for a non-existent symlink. If
1003  * fail, set the errno from the stat call.
1004  */
1005  if (ISSET(FTS_LOGICAL) || follow) {
1006  if ((*sp->fts_stat) (p->fts_accpath, sbp)) {
1007  saved_errno = errno;
1008  if (!(*sp->fts_lstat) (p->fts_accpath, sbp)) {
1009 /*@-boundswrite@*/
1010  __set_errno (0);
1011 /*@=boundswrite@*/
1012  return (FTS_SLNONE);
1013  }
1014  p->fts_errno = saved_errno;
1015  goto err;
1016  }
1017  } else if ((*sp->fts_lstat) (p->fts_accpath, sbp)) {
1018  p->fts_errno = errno;
1019 /*@-boundswrite@*/
1020 err: memset(sbp, 0, sizeof(*sbp));
1021 /*@=boundswrite@*/
1022  return (FTS_NS);
1023  }
1024 
1025  if (S_ISDIR(sbp->st_mode)) {
1026  /*
1027  * Set the device/inode. Used to find cycles and check for
1028  * crossing mount points. Also remember the link count, used
1029  * in fts_build to limit the number of stat calls. It is
1030  * understood that these fields are only referenced if fts_info
1031  * is set to FTS_D.
1032  */
1033  dev = p->fts_dev = sbp->st_dev;
1034  ino = p->fts_ino = sbp->st_ino;
1035  p->fts_nlink = sbp->st_nlink;
1036 
1037  if (ISDOT(p->fts_name))
1038  return (FTS_DOT);
1039 
1040  /*
1041  * Cycle detection is done by brute force when the directory
1042  * is first encountered. If the tree gets deep enough or the
1043  * number of symbolic links to directories is high enough,
1044  * something faster might be worthwhile.
1045  */
1046  for (t = p->fts_parent;
1047  t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
1048  if (ino == t->fts_ino && dev == t->fts_dev) {
1049  p->fts_cycle = t;
1050  return (FTS_DC);
1051  }
1052  return (FTS_D);
1053  }
1054  if (S_ISLNK(sbp->st_mode))
1055  return (FTS_SL);
1056  if (S_ISREG(sbp->st_mode))
1057  return (FTS_F);
1058  return (FTS_DEFAULT);
1059 }
1060 
1061 static FTSENT *
1062 fts_sort(FTS * sp, FTSENT * head, int nitems)
1063 {
1064  register FTSENT **ap, *p;
1065 
1066  /*
1067  * Construct an array of pointers to the structures and call qsort(3).
1068  * Reassemble the array in the order returned by qsort. If unable to
1069  * sort for memory reasons, return the directory entries in their
1070  * current order. Allocate enough space for the current needs plus
1071  * 40 so don't realloc one entry at a time.
1072  */
1073  if (nitems > sp->fts_nitems) {
1074  struct _ftsent **a;
1075 
1076  sp->fts_nitems = nitems + 40;
1077  if ((a = realloc(sp->fts_array,
1078  (size_t)(sp->fts_nitems * sizeof(*sp->fts_array)))) == NULL)
1079  {
1080  free(sp->fts_array);
1081  sp->fts_array = NULL;
1082  sp->fts_nitems = 0;
1083  return (head);
1084  }
1085  sp->fts_array = a;
1086  }
1087 /*@-boundswrite@*/
1088  for (ap = sp->fts_array, p = head; p != NULL; p = p->fts_link)
1089  *ap++ = p;
1090  qsort((void *)sp->fts_array, nitems, sizeof(*sp->fts_array),
1091  sp->fts_compar);
1092  for (head = *(ap = sp->fts_array); --nitems; ++ap)
1093  ap[0]->fts_link = ap[1];
1094  ap[0]->fts_link = NULL;
1095 /*@=boundswrite@*/
1096  return (head);
1097 }
1098 
1099 static FTSENT *
1100 fts_alloc(FTS * sp, const char * name, int namelen)
1101 {
1102  register FTSENT *p;
1103  size_t len;
1104 
1105  /*
1106  * The file name is a variable length array and no stat structure is
1107  * necessary if the user has set the nostat bit. Allocate the FTSENT
1108  * structure, the file name and the stat structure in one chunk, but
1109  * be careful that the stat structure is reasonably aligned. Since the
1110  * fts_name field is declared to be of size 1, the fts_name pointer is
1111  * namelen + 2 before the first possible address of the stat structure.
1112  */
1113  len = sizeof(*p) + namelen;
1114  if (!ISSET(FTS_NOSTAT))
1115  len += sizeof(*p->fts_statp) + ALIGNBYTES;
1116  if ((p = malloc(len)) == NULL)
1117  return (NULL);
1118 
1119  /* Copy the name and guarantee NUL termination. */
1120 /*@-boundswrite@*/
1121  memmove(p->fts_name, name, namelen);
1122  p->fts_name[namelen] = '\0';
1123 /*@=boundswrite@*/
1124 
1125  if (!ISSET(FTS_NOSTAT))
1126  p->fts_statp = (struct stat *)ALIGN(p->fts_name + namelen + 2);
1127  p->fts_namelen = namelen;
1128  p->fts_path = sp->fts_path;
1129  p->fts_errno = 0;
1130  p->fts_flags = 0;
1131  p->fts_instr = FTS_NOINSTR;
1132  p->fts_number = 0;
1133  p->fts_pointer = NULL;
1134  return (p);
1135 }
1136 
1137 static void
1139 {
1140  register FTSENT *p;
1141 
1142  /* Free a linked list of structures. */
1143  /*@-branchstate@*/
1144  while ((p = head)) {
1145  head = head->fts_link;
1146  free(p);
1147  }
1148  /*@=branchstate@*/
1149 }
1150 
1151 /*
1152  * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
1153  * Most systems will allow creation of paths much longer than MAXPATHLEN, even
1154  * though the kernel won't resolve them. Add the size (not just what's needed)
1155  * plus 256 bytes so don't realloc the path 2 bytes at a time.
1156  */
1157 static int
1158 fts_palloc(FTS * sp, size_t more)
1159 {
1160  char *p;
1161 
1162  sp->fts_pathlen += more + 256;
1163  /*
1164  * Check for possible wraparound. In an FTS, fts_pathlen is
1165  * a signed int but in an FTSENT it is an unsigned short.
1166  * We limit fts_pathlen to USHRT_MAX to be safe in both cases.
1167  */
1168  if (sp->fts_pathlen < 0 || sp->fts_pathlen >= USHRT_MAX) {
1169  if (sp->fts_path)
1170  free(sp->fts_path);
1171  sp->fts_path = NULL;
1172 /*@-boundswrite@*/
1173  __set_errno (ENAMETOOLONG);
1174 /*@=boundswrite@*/
1175  return (1);
1176  }
1177  p = realloc(sp->fts_path, sp->fts_pathlen);
1178  if (p == NULL) {
1179  free(sp->fts_path);
1180  sp->fts_path = NULL;
1181  return 1;
1182  }
1183  sp->fts_path = p;
1184  return 0;
1185 }
1186 
1187 /*
1188  * When the path is realloc'd, have to fix all of the pointers in structures
1189  * already returned.
1190  */
1191 static void
1192 fts_padjust(FTS * sp, FTSENT * head)
1193 {
1194  FTSENT *p;
1195  char *addr = sp->fts_path;
1196 
1197 #define ADJUST(p) do { \
1198  if ((p)->fts_accpath != (p)->fts_name) { \
1199  (p)->fts_accpath = \
1200  (char *)addr + ((p)->fts_accpath - (p)->fts_path); \
1201  } \
1202  (p)->fts_path = addr; \
1203 } while (0)
1204  /* Adjust the current set of children. */
1205  for (p = sp->fts_child; p != NULL; p = p->fts_link)
1206  ADJUST(p);
1207 
1208  /* Adjust the rest of the tree, including the current level. */
1209  for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
1210  ADJUST(p);
1211  p = p->fts_link ? p->fts_link : p->fts_parent;
1212  }
1213 }
1214 
1215 static size_t
1216 fts_maxarglen(char * const * argv)
1217 {
1218  size_t len, max;
1219 
1220  for (max = 0; *argv; ++argv)
1221  if ((len = strlen(*argv)) > max)
1222  max = len;
1223  return (max + 1);
1224 }
1225 
1226 /*
1227  * Change to dir specified by fd or p->fts_accpath without getting
1228  * tricked by someone changing the world out from underneath us.
1229  * Assumes p->fts_dev and p->fts_ino are filled in.
1230  */
1231 static int
1232 fts_safe_changedir(FTS * sp, FTSENT * p, int fd, const char * path)
1233 {
1234  int ret, oerrno, newfd;
1235  struct stat64 sb;
1236 
1237  newfd = fd;
1238  if (ISSET(FTS_NOCHDIR))
1239  return (0);
1240  if (fd < 0 && (newfd = __open(path, O_RDONLY, 0)) < 0)
1241  return (-1);
1242  if (__fxstat64(_STAT_VER, newfd, &sb)) {
1243  ret = -1;
1244  goto bail;
1245  }
1246  if (p->fts_dev != sb.st_dev || p->fts_ino != sb.st_ino) {
1247 /*@-boundswrite@*/
1248  __set_errno (ENOENT); /* disinformation */
1249 /*@=boundswrite@*/
1250  ret = -1;
1251  goto bail;
1252  }
1253  ret = __fchdir(newfd);
1254 bail:
1255  oerrno = errno;
1256  if (fd < 0)
1257  (void)__close(newfd);
1258 /*@-boundswrite@*/
1259  __set_errno (oerrno);
1260 /*@=boundswrite@*/
1261  return (ret);
1262 }
1263 /*@=compdef =compmempass =dependenttrans =retalias @*/
1264 /*@=sysunrecog =noeffectuncon =nullpass =sizeoftype =unrecog =usereleased @*/
1265 /*@=boundsread@*/