import less(1)
[unleashed/tickless.git] / usr / src / lib / libc / port / gen / fts.c
blob70a683e8f3a400895dd2dbec502d97393d370b92
1 /* $OpenBSD: fts.c,v 1.56 2016/09/21 04:38:56 guenther Exp $ */
3 /*-
4 * Copyright (c) 1990, 1993, 1994
5 * The Regents of the University of California. All rights reserved.
7 * Redistribution and use in source and binary forms, with or without
8 * modification, are permitted provided that the following conditions
9 * are met:
10 * 1. Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * 2. Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * 3. Neither the name of the University nor the names of its contributors
16 * may be used to endorse or promote products derived from this software
17 * without specific prior written permission.
19 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
20 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
21 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
22 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
23 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
24 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
25 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
26 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
27 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
28 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
29 * SUCH DAMAGE.
32 #include <sys/param.h> /* ALIGN */
33 #include <sys/stat.h>
35 #include <dirent.h>
36 #include <errno.h>
37 #include <fcntl.h>
38 #include <fts.h>
39 #include <limits.h>
40 #include <stdlib.h>
41 #include <string.h>
42 #include <unistd.h>
43 #include <stddef.h>
45 #define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
47 static FTSENT *fts_alloc(FTS *, char *, size_t);
48 static FTSENT *fts_build(FTS *, int);
49 static void fts_lfree(FTSENT *);
50 static void fts_load(FTS *, FTSENT *);
51 static size_t fts_maxarglen(char * const *);
52 static void fts_padjust(FTS *, FTSENT *);
53 static int fts_palloc(FTS *, size_t);
54 static FTSENT *fts_sort(FTS *, FTSENT *, int);
55 static u_short fts_stat(FTS *, FTSENT *, int, int);
56 static int fts_safe_changedir(FTS *, FTSENT *, int, char *);
58 #define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
60 #define CLR(opt) (sp->fts_options &= ~(opt))
61 #define ISSET(opt) (sp->fts_options & (opt))
62 #define SET(opt) (sp->fts_options |= (opt))
64 #define FCHDIR(sp, fd) (!ISSET(FTS_NOCHDIR) && fchdir(fd))
66 #define ALIGNBYTES (_MAX_ALIGNMENT - 1)
67 #define ALIGN(p) (((unsigned long)(p) + ALIGNBYTES) &~ALIGNBYTES)
69 /* fts_build flags */
70 #define BCHILD 1 /* fts_children */
71 #define BNAMES 2 /* fts_children, names only */
72 #define BREAD 3 /* fts_read */
74 FTS *
75 fts_open(char * const *argv, int options,
76 int (*compar)(const FTSENT **, const FTSENT **))
78 FTS *sp;
79 FTSENT *p, *root;
80 int nitems;
81 FTSENT *parent, *tmp;
83 /* Options check. */
84 if (options & ~FTS_OPTIONMASK) {
85 errno = EINVAL;
86 return (NULL);
89 /* At least one path must be specified. */
90 if (*argv == NULL) {
91 errno = EINVAL;
92 return (NULL);
95 /* Allocate/initialize the stream */
96 if ((sp = calloc(1, sizeof(FTS))) == NULL)
97 return (NULL);
98 sp->fts_compar = compar;
99 sp->fts_options = options;
101 /* Logical walks turn on NOCHDIR; symbolic links are too hard. */
102 if (ISSET(FTS_LOGICAL))
103 SET(FTS_NOCHDIR);
106 * Start out with 1K of path space, and enough, in any case,
107 * to hold the user's paths.
109 if (fts_palloc(sp, MAXIMUM(fts_maxarglen(argv), PATH_MAX)))
110 goto mem1;
112 /* Allocate/initialize root's parent. */
113 if ((parent = fts_alloc(sp, "", 0)) == NULL)
114 goto mem2;
115 parent->fts_level = FTS_ROOTPARENTLEVEL;
117 /* Allocate/initialize root(s). */
118 for (root = NULL, nitems = 0; *argv; ++argv, ++nitems) {
119 if ((p = fts_alloc(sp, *argv, strlen(*argv))) == NULL)
120 goto mem3;
121 p->fts_level = FTS_ROOTLEVEL;
122 p->fts_parent = parent;
123 p->fts_accpath = p->fts_name;
124 p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW), -1);
126 /* Command-line "." and ".." are real directories. */
127 if (p->fts_info == FTS_DOT)
128 p->fts_info = FTS_D;
131 * If comparison routine supplied, traverse in sorted
132 * order; otherwise traverse in the order specified.
134 if (compar) {
135 p->fts_link = root;
136 root = p;
137 } else {
138 p->fts_link = NULL;
139 if (root == NULL)
140 tmp = root = p;
141 else {
142 tmp->fts_link = p;
143 tmp = p;
147 if (compar && nitems > 1)
148 root = fts_sort(sp, root, nitems);
151 * Allocate a dummy pointer and make fts_read think that we've just
152 * finished the node before the root(s); set p->fts_info to FTS_INIT
153 * so that everything about the "current" node is ignored.
155 if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
156 goto mem3;
157 sp->fts_cur->fts_link = root;
158 sp->fts_cur->fts_info = FTS_INIT;
161 * If using chdir(2), grab a file descriptor pointing to dot to ensure
162 * that we can get back here; this could be avoided for some paths,
163 * but almost certainly not worth the effort. Slashes, symbolic links,
164 * and ".." are all fairly nasty problems. Note, if we can't get the
165 * descriptor we run anyway, just more slowly.
167 if (!ISSET(FTS_NOCHDIR) &&
168 (sp->fts_rfd = open(".", O_RDONLY | O_CLOEXEC)) < 0)
169 SET(FTS_NOCHDIR);
171 if (nitems == 0)
172 free(parent);
174 return (sp);
176 mem3: fts_lfree(root);
177 free(parent);
178 mem2: free(sp->fts_path);
179 mem1: free(sp);
180 return (NULL);
183 static void
184 fts_load(FTS *sp, FTSENT *p)
186 size_t len;
187 char *cp;
190 * Load the stream structure for the next traversal. Since we don't
191 * actually enter the directory until after the preorder visit, set
192 * the fts_accpath field specially so the chdir gets done to the right
193 * place and the user can access the first node. From fts_open it's
194 * known that the path will fit.
196 len = p->fts_pathlen = p->fts_namelen;
197 memmove(sp->fts_path, p->fts_name, len + 1);
198 if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
199 len = strlen(++cp);
200 memmove(p->fts_name, cp, len + 1);
201 p->fts_namelen = len;
203 p->fts_accpath = p->fts_path = sp->fts_path;
204 sp->fts_dev = p->fts_dev;
208 fts_close(FTS *sp)
210 FTSENT *freep, *p;
211 int rfd, error = 0;
214 * This still works if we haven't read anything -- the dummy structure
215 * points to the root list, so we step through to the end of the root
216 * list which has a valid parent pointer.
218 if (sp->fts_cur) {
219 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
220 freep = p;
221 p = p->fts_link ? p->fts_link : p->fts_parent;
222 free(freep);
224 free(p);
227 /* Stash the original directory fd if needed. */
228 rfd = ISSET(FTS_NOCHDIR) ? -1 : sp->fts_rfd;
230 /* Free up child linked list, sort array, path buffer, stream ptr.*/
231 if (sp->fts_child)
232 fts_lfree(sp->fts_child);
233 free(sp->fts_array);
234 free(sp->fts_path);
235 free(sp);
237 /* Return to original directory, checking for error. */
238 if (rfd != -1) {
239 int saved_errno;
240 error = fchdir(rfd);
241 saved_errno = errno;
242 (void)close(rfd);
243 errno = saved_errno;
246 return (error);
250 * Special case of "/" at the end of the path so that slashes aren't
251 * appended which would cause paths to be written as "....//foo".
253 #define NAPPEND(p) \
254 (p->fts_path[p->fts_pathlen - 1] == '/' \
255 ? p->fts_pathlen - 1 : p->fts_pathlen)
257 FTSENT *
258 fts_read(FTS *sp)
260 FTSENT *p, *tmp;
261 int instr;
262 char *t;
263 int saved_errno;
265 /* If finished or unrecoverable error, return NULL. */
266 if (sp->fts_cur == NULL || ISSET(FTS_STOP))
267 return (NULL);
269 /* Set current node pointer. */
270 p = sp->fts_cur;
272 /* Save and zero out user instructions. */
273 instr = p->fts_instr;
274 p->fts_instr = FTS_NOINSTR;
276 /* Any type of file may be re-visited; re-stat and re-turn. */
277 if (instr == FTS_AGAIN) {
278 p->fts_info = fts_stat(sp, p, 0, -1);
279 return (p);
283 * Following a symlink -- SLNONE test allows application to see
284 * SLNONE and recover. If indirecting through a symlink, have
285 * keep a pointer to current location. If unable to get that
286 * pointer, follow fails.
288 if (instr == FTS_FOLLOW &&
289 (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
290 p->fts_info = fts_stat(sp, p, 1, -1);
291 if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
292 if ((p->fts_symfd =
293 open(".", O_RDONLY | O_CLOEXEC)) < 0) {
294 p->fts_errno = errno;
295 p->fts_info = FTS_ERR;
296 } else
297 p->fts_flags |= FTS_SYMFOLLOW;
299 return (p);
302 /* Directory in pre-order. */
303 if (p->fts_info == FTS_D) {
304 /* If skipped or crossed mount point, do post-order visit. */
305 if (instr == FTS_SKIP ||
306 (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
307 if (p->fts_flags & FTS_SYMFOLLOW)
308 (void)close(p->fts_symfd);
309 if (sp->fts_child) {
310 fts_lfree(sp->fts_child);
311 sp->fts_child = NULL;
313 p->fts_info = FTS_DP;
314 return (p);
317 /* Rebuild if only read the names and now traversing. */
318 if (sp->fts_child && ISSET(FTS_NAMEONLY)) {
319 CLR(FTS_NAMEONLY);
320 fts_lfree(sp->fts_child);
321 sp->fts_child = NULL;
325 * Cd to the subdirectory.
327 * If have already read and now fail to chdir, whack the list
328 * to make the names come out right, and set the parent errno
329 * so the application will eventually get an error condition.
330 * Set the FTS_DONTCHDIR flag so that when we logically change
331 * directories back to the parent we don't do a chdir.
333 * If haven't read do so. If the read fails, fts_build sets
334 * FTS_STOP or the fts_info field of the node.
336 if (sp->fts_child) {
337 if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
338 p->fts_errno = errno;
339 p->fts_flags |= FTS_DONTCHDIR;
340 for (p = sp->fts_child; p; p = p->fts_link)
341 p->fts_accpath =
342 p->fts_parent->fts_accpath;
344 } else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
345 if (ISSET(FTS_STOP))
346 return (NULL);
347 return (p);
349 p = sp->fts_child;
350 sp->fts_child = NULL;
351 goto name;
354 /* Move to the next node on this level. */
355 next: tmp = p;
356 if ((p = p->fts_link)) {
357 free(tmp);
360 * If reached the top, return to the original directory (or
361 * the root of the tree), and load the paths for the next root.
363 if (p->fts_level == FTS_ROOTLEVEL) {
364 if (FCHDIR(sp, sp->fts_rfd)) {
365 SET(FTS_STOP);
366 return (NULL);
368 fts_load(sp, p);
369 return (sp->fts_cur = p);
373 * User may have called fts_set on the node. If skipped,
374 * ignore. If followed, get a file descriptor so we can
375 * get back if necessary.
377 if (p->fts_instr == FTS_SKIP)
378 goto next;
379 if (p->fts_instr == FTS_FOLLOW) {
380 p->fts_info = fts_stat(sp, p, 1, -1);
381 if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
382 if ((p->fts_symfd =
383 open(".", O_RDONLY | O_CLOEXEC)) < 0) {
384 p->fts_errno = errno;
385 p->fts_info = FTS_ERR;
386 } else
387 p->fts_flags |= FTS_SYMFOLLOW;
389 p->fts_instr = FTS_NOINSTR;
392 name: t = sp->fts_path + NAPPEND(p->fts_parent);
393 *t++ = '/';
394 memmove(t, p->fts_name, p->fts_namelen + 1);
395 return (sp->fts_cur = p);
398 /* Move up to the parent node. */
399 p = tmp->fts_parent;
400 free(tmp);
402 if (p->fts_level == FTS_ROOTPARENTLEVEL) {
404 * Done; free everything up and set errno to 0 so the user
405 * can distinguish between error and EOF.
407 free(p);
408 errno = 0;
409 return (sp->fts_cur = NULL);
412 /* NUL terminate the pathname. */
413 sp->fts_path[p->fts_pathlen] = '\0';
416 * Return to the parent directory. If at a root node or came through
417 * a symlink, go back through the file descriptor. Otherwise, cd up
418 * one directory.
420 if (p->fts_level == FTS_ROOTLEVEL) {
421 if (FCHDIR(sp, sp->fts_rfd)) {
422 SET(FTS_STOP);
423 sp->fts_cur = p;
424 return (NULL);
426 } else if (p->fts_flags & FTS_SYMFOLLOW) {
427 if (FCHDIR(sp, p->fts_symfd)) {
428 saved_errno = errno;
429 (void)close(p->fts_symfd);
430 errno = saved_errno;
431 SET(FTS_STOP);
432 sp->fts_cur = p;
433 return (NULL);
435 (void)close(p->fts_symfd);
436 } else if (!(p->fts_flags & FTS_DONTCHDIR) &&
437 fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
438 SET(FTS_STOP);
439 sp->fts_cur = p;
440 return (NULL);
442 p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
443 return (sp->fts_cur = p);
447 * Fts_set takes the stream as an argument although it's not used in this
448 * implementation; it would be necessary if anyone wanted to add global
449 * semantics to fts using fts_set. An error return is allowed for similar
450 * reasons.
453 fts_set(FTS *sp, FTSENT *p, int instr)
455 if (instr && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
456 instr != FTS_NOINSTR && instr != FTS_SKIP) {
457 errno = EINVAL;
458 return (1);
460 p->fts_instr = instr;
461 return (0);
464 FTSENT *
465 fts_children(FTS *sp, int instr)
467 FTSENT *p;
468 int fd;
470 if (instr && instr != FTS_NAMEONLY) {
471 errno = EINVAL;
472 return (NULL);
475 /* Set current node pointer. */
476 p = sp->fts_cur;
479 * Errno set to 0 so user can distinguish empty directory from
480 * an error.
482 errno = 0;
484 /* Fatal errors stop here. */
485 if (ISSET(FTS_STOP))
486 return (NULL);
488 /* Return logical hierarchy of user's arguments. */
489 if (p->fts_info == FTS_INIT)
490 return (p->fts_link);
493 * If not a directory being visited in pre-order, stop here. Could
494 * allow FTS_DNR, assuming the user has fixed the problem, but the
495 * same effect is available with FTS_AGAIN.
497 if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
498 return (NULL);
500 /* Free up any previous child list. */
501 if (sp->fts_child)
502 fts_lfree(sp->fts_child);
504 if (instr == FTS_NAMEONLY) {
505 SET(FTS_NAMEONLY);
506 instr = BNAMES;
507 } else
508 instr = BCHILD;
511 * If using chdir on a relative path and called BEFORE fts_read does
512 * its chdir to the root of a traversal, we can lose -- we need to
513 * chdir into the subdirectory, and we don't know where the current
514 * directory is, so we can't get back so that the upcoming chdir by
515 * fts_read will work.
517 if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
518 ISSET(FTS_NOCHDIR))
519 return (sp->fts_child = fts_build(sp, instr));
521 if ((fd = open(".", O_RDONLY | O_CLOEXEC)) < 0)
522 return (NULL);
523 sp->fts_child = fts_build(sp, instr);
524 if (fchdir(fd)) {
525 (void)close(fd);
526 return (NULL);
528 (void)close(fd);
529 return (sp->fts_child);
533 * This is the tricky part -- do not casually change *anything* in here. The
534 * idea is to build the linked list of entries that are used by fts_children
535 * and fts_read. There are lots of special cases.
537 * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is
538 * set and it's a physical walk (so that symbolic links can't be directories),
539 * we can do things quickly. First, if it's a 4.4BSD file system, the type
540 * of the file is in the directory entry. Otherwise, we assume that the number
541 * of subdirectories in a node is equal to the number of links to the parent.
542 * The former skips all stat calls. The latter skips stat calls in any leaf
543 * directories and for any files after the subdirectories in the directory have
544 * been found, cutting the stat calls by about 2/3.
546 static FTSENT *
547 fts_build(FTS *sp, int type)
549 struct dirent *dp;
550 FTSENT *p, *head;
551 FTSENT *cur, *tail;
552 DIR *dirp;
553 void *oldaddr;
554 size_t len, maxlen;
555 int nitems, cderrno, descend, level, nlinks, nostat, doadjust;
556 int saved_errno;
557 char *cp;
559 /* Set current node pointer. */
560 cur = sp->fts_cur;
563 * Open the directory for reading. If this fails, we're done.
564 * If being called from fts_read, set the fts_info field.
566 if ((dirp = opendir(cur->fts_accpath)) == NULL) {
567 if (type == BREAD) {
568 cur->fts_info = FTS_DNR;
569 cur->fts_errno = errno;
571 return (NULL);
575 * Nlinks is the number of possible entries of type directory in the
576 * directory if we're cheating on stat calls, 0 if we're not doing
577 * any stat calls at all, -1 if we're doing stats on everything.
579 if (type == BNAMES)
580 nlinks = 0;
581 else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
582 nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
583 nostat = 1;
584 } else {
585 nlinks = -1;
586 nostat = 0;
589 #ifdef notdef
590 (void)printf("nlinks == %d (cur: %u)\n", nlinks, cur->fts_nlink);
591 (void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
592 ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
593 #endif
595 * If we're going to need to stat anything or we want to descend
596 * and stay in the directory, chdir. If this fails we keep going,
597 * but set a flag so we don't chdir after the post-order visit.
598 * We won't be able to stat anything, but we can still return the
599 * names themselves. Note, that since fts_read won't be able to
600 * chdir into the directory, it will have to return different path
601 * names than before, i.e. "a/b" instead of "b". Since the node
602 * has already been visited in pre-order, have to wait until the
603 * post-order visit to return the error. There is a special case
604 * here, if there was nothing to stat then it's not an error to
605 * not be able to stat. This is all fairly nasty. If a program
606 * needed sorted entries or stat information, they had better be
607 * checking FTS_NS on the returned nodes.
609 cderrno = 0;
610 if (nlinks || type == BREAD) {
611 if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) {
612 if (nlinks && type == BREAD)
613 cur->fts_errno = errno;
614 cur->fts_flags |= FTS_DONTCHDIR;
615 descend = 0;
616 cderrno = errno;
617 (void)closedir(dirp);
618 dirp = NULL;
619 } else
620 descend = 1;
621 } else
622 descend = 0;
625 * Figure out the max file name length that can be stored in the
626 * current path -- the inner loop allocates more path as necessary.
627 * We really wouldn't have to do the maxlen calculations here, we
628 * could do them in fts_read before returning the path, but it's a
629 * lot easier here since the length is part of the dirent structure.
631 * If not changing directories set a pointer so that can just append
632 * each new name into the path.
634 len = NAPPEND(cur);
635 if (ISSET(FTS_NOCHDIR)) {
636 cp = sp->fts_path + len;
637 *cp++ = '/';
639 len++;
640 maxlen = sp->fts_pathlen - len;
643 * fts_level is signed so we must prevent it from wrapping
644 * around to FTS_ROOTLEVEL and FTS_ROOTPARENTLEVEL.
646 level = cur->fts_level;
647 if (level < FTS_MAXLEVEL)
648 level++;
650 /* Read the directory, attaching each entry to the `link' pointer. */
651 doadjust = 0;
652 for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) {
653 if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
654 continue;
656 size_t namlen = strlen(dp->d_name);
658 if (!(p = fts_alloc(sp, dp->d_name, namlen)))
659 goto mem1;
660 if (namlen >= maxlen) { /* include space for NUL */
661 oldaddr = sp->fts_path;
662 if (fts_palloc(sp, namlen + len + 1)) {
664 * No more memory for path or structures. Save
665 * errno, free up the current structure and the
666 * structures already allocated.
668 mem1: saved_errno = errno;
669 free(p);
670 fts_lfree(head);
671 (void)closedir(dirp);
672 cur->fts_info = FTS_ERR;
673 SET(FTS_STOP);
674 errno = saved_errno;
675 return (NULL);
677 /* Did realloc() change the pointer? */
678 if (oldaddr != sp->fts_path) {
679 doadjust = 1;
680 if (ISSET(FTS_NOCHDIR))
681 cp = sp->fts_path + len;
683 maxlen = sp->fts_pathlen - len;
686 p->fts_level = level;
687 p->fts_parent = sp->fts_cur;
688 p->fts_pathlen = len + namlen;
689 if (p->fts_pathlen < len) {
691 * If we wrap, free up the current structure and
692 * the structures already allocated, then error
693 * out with ENAMETOOLONG.
695 free(p);
696 fts_lfree(head);
697 (void)closedir(dirp);
698 cur->fts_info = FTS_ERR;
699 SET(FTS_STOP);
700 errno = ENAMETOOLONG;
701 return (NULL);
704 if (cderrno) {
705 if (nlinks) {
706 p->fts_info = FTS_NS;
707 p->fts_errno = cderrno;
708 } else
709 p->fts_info = FTS_NSOK;
710 p->fts_accpath = cur->fts_accpath;
711 } else if (nlinks == 0
712 #ifdef DT_DIR
713 || (nostat &&
714 dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN)
715 #endif
717 p->fts_accpath =
718 ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
719 p->fts_info = FTS_NSOK;
720 } else {
721 /* Build a file name for fts_stat to stat. */
722 if (ISSET(FTS_NOCHDIR)) {
723 p->fts_accpath = p->fts_path;
724 memmove(cp, p->fts_name, p->fts_namelen + 1);
725 p->fts_info = fts_stat(sp, p, 0, dirfd(dirp));
726 } else {
727 p->fts_accpath = p->fts_name;
728 p->fts_info = fts_stat(sp, p, 0, -1);
731 /* Decrement link count if applicable. */
732 if (nlinks > 0 && (p->fts_info == FTS_D ||
733 p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
734 --nlinks;
737 /* We walk in directory order so "ls -f" doesn't get upset. */
738 p->fts_link = NULL;
739 if (head == NULL)
740 head = tail = p;
741 else {
742 tail->fts_link = p;
743 tail = p;
745 ++nitems;
747 if (dirp)
748 (void)closedir(dirp);
751 * If realloc() changed the address of the path, adjust the
752 * addresses for the rest of the tree and the dir list.
754 if (doadjust)
755 fts_padjust(sp, head);
758 * If not changing directories, reset the path back to original
759 * state.
761 if (ISSET(FTS_NOCHDIR)) {
762 if (len == sp->fts_pathlen || nitems == 0)
763 --cp;
764 *cp = '\0';
768 * If descended after called from fts_children or after called from
769 * fts_read and nothing found, get back. At the root level we use
770 * the saved fd; if one of fts_open()'s arguments is a relative path
771 * to an empty directory, we wind up here with no other way back. If
772 * can't get back, we're done.
774 if (descend && (type == BCHILD || !nitems) &&
775 (cur->fts_level == FTS_ROOTLEVEL ? FCHDIR(sp, sp->fts_rfd) :
776 fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
777 cur->fts_info = FTS_ERR;
778 SET(FTS_STOP);
779 return (NULL);
782 /* If didn't find anything, return NULL. */
783 if (!nitems) {
784 if (type == BREAD)
785 cur->fts_info = FTS_DP;
786 return (NULL);
789 /* Sort the entries. */
790 if (sp->fts_compar && nitems > 1)
791 head = fts_sort(sp, head, nitems);
792 return (head);
795 static u_short
796 fts_stat(FTS *sp, FTSENT *p, int follow, int dfd)
798 FTSENT *t;
799 dev_t dev;
800 ino_t ino;
801 struct stat *sbp, sb;
802 int saved_errno;
803 const char *path;
805 if (dfd == -1) {
806 path = p->fts_accpath;
807 dfd = AT_FDCWD;
808 } else
809 path = p->fts_name;
811 /* If user needs stat info, stat buffer already allocated. */
812 sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
815 * If doing a logical walk, or application requested FTS_FOLLOW, do
816 * a stat(2). If that fails, check for a non-existent symlink. If
817 * fail, set the errno from the stat call.
819 if (ISSET(FTS_LOGICAL) || follow) {
820 if (fstatat(dfd, path, sbp, 0)) {
821 saved_errno = errno;
822 if (!fstatat(dfd, path, sbp, AT_SYMLINK_NOFOLLOW)) {
823 errno = 0;
824 return (FTS_SLNONE);
826 p->fts_errno = saved_errno;
827 goto err;
829 } else if (fstatat(dfd, path, sbp, AT_SYMLINK_NOFOLLOW)) {
830 p->fts_errno = errno;
831 err: memset(sbp, 0, sizeof(struct stat));
832 return (FTS_NS);
835 if (S_ISDIR(sbp->st_mode)) {
837 * Set the device/inode. Used to find cycles and check for
838 * crossing mount points. Also remember the link count, used
839 * in fts_build to limit the number of stat calls. It is
840 * understood that these fields are only referenced if fts_info
841 * is set to FTS_D.
843 dev = p->fts_dev = sbp->st_dev;
844 ino = p->fts_ino = sbp->st_ino;
845 p->fts_nlink = sbp->st_nlink;
847 if (ISDOT(p->fts_name))
848 return (FTS_DOT);
851 * Cycle detection is done by brute force when the directory
852 * is first encountered. If the tree gets deep enough or the
853 * number of symbolic links to directories is high enough,
854 * something faster might be worthwhile.
856 for (t = p->fts_parent;
857 t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
858 if (ino == t->fts_ino && dev == t->fts_dev) {
859 p->fts_cycle = t;
860 return (FTS_DC);
862 return (FTS_D);
864 if (S_ISLNK(sbp->st_mode))
865 return (FTS_SL);
866 if (S_ISREG(sbp->st_mode))
867 return (FTS_F);
868 return (FTS_DEFAULT);
871 static FTSENT *
872 fts_sort(FTS *sp, FTSENT *head, int nitems)
874 FTSENT **ap, *p;
877 * Construct an array of pointers to the structures and call qsort(3).
878 * Reassemble the array in the order returned by qsort. If unable to
879 * sort for memory reasons, return the directory entries in their
880 * current order. Allocate enough space for the current needs plus
881 * 40 so don't realloc one entry at a time.
883 if (nitems > sp->fts_nitems) {
884 struct _ftsent **a;
886 sp->fts_nitems = nitems + 40;
887 if ((a = reallocarray(sp->fts_array,
888 sp->fts_nitems, sizeof(FTSENT *))) == NULL) {
889 free(sp->fts_array);
890 sp->fts_array = NULL;
891 sp->fts_nitems = 0;
892 return (head);
894 sp->fts_array = a;
896 for (ap = sp->fts_array, p = head; p; p = p->fts_link)
897 *ap++ = p;
898 qsort(sp->fts_array, nitems, sizeof(FTSENT *), sp->fts_compar);
899 for (head = *(ap = sp->fts_array); --nitems; ++ap)
900 ap[0]->fts_link = ap[1];
901 ap[0]->fts_link = NULL;
902 return (head);
905 static FTSENT *
906 fts_alloc(FTS *sp, char *name, size_t namelen)
908 FTSENT *p;
909 size_t len;
912 * The file name is a variable length array and no stat structure is
913 * necessary if the user has set the nostat bit. Allocate the FTSENT
914 * structure, the file name and the stat structure in one chunk, but
915 * be careful that the stat structure is reasonably aligned. Since the
916 * fts_name field is declared to be of size 1, the fts_name pointer is
917 * namelen + 2 before the first possible address of the stat structure.
919 len = sizeof(FTSENT) + namelen;
920 if (!ISSET(FTS_NOSTAT))
921 len += sizeof(struct stat) + ALIGNBYTES;
922 if ((p = calloc(1, len)) == NULL)
923 return (NULL);
925 p->fts_path = sp->fts_path;
926 p->fts_namelen = namelen;
927 p->fts_instr = FTS_NOINSTR;
928 if (!ISSET(FTS_NOSTAT))
929 p->fts_statp = (struct stat *)ALIGN(p->fts_name + namelen + 2);
930 memcpy(p->fts_name, name, namelen);
932 return (p);
935 static void
936 fts_lfree(FTSENT *head)
938 FTSENT *p;
940 /* Free a linked list of structures. */
941 while ((p = head)) {
942 head = head->fts_link;
943 free(p);
948 * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
949 * Most systems will allow creation of paths much longer than PATH_MAX, even
950 * though the kernel won't resolve them. Add the size (not just what's needed)
951 * plus 256 bytes so don't realloc the path 2 bytes at a time.
953 static int
954 fts_palloc(FTS *sp, size_t more)
956 char *p;
959 * Check for possible wraparound.
961 more += 256;
962 if (sp->fts_pathlen + more < sp->fts_pathlen) {
963 free(sp->fts_path);
964 sp->fts_path = NULL;
965 errno = ENAMETOOLONG;
966 return (1);
968 sp->fts_pathlen += more;
969 p = realloc(sp->fts_path, sp->fts_pathlen);
970 if (p == NULL) {
971 free(sp->fts_path);
972 sp->fts_path = NULL;
973 return (1);
975 sp->fts_path = p;
976 return (0);
980 * When the path is realloc'd, have to fix all of the pointers in structures
981 * already returned.
983 static void
984 fts_padjust(FTS *sp, FTSENT *head)
986 FTSENT *p;
987 char *addr = sp->fts_path;
989 #define ADJUST(p) { \
990 if ((p)->fts_accpath != (p)->fts_name) { \
991 (p)->fts_accpath = \
992 (char *)addr + ((p)->fts_accpath - (p)->fts_path); \
994 (p)->fts_path = addr; \
996 /* Adjust the current set of children. */
997 for (p = sp->fts_child; p; p = p->fts_link)
998 ADJUST(p);
1000 /* Adjust the rest of the tree, including the current level. */
1001 for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
1002 ADJUST(p);
1003 p = p->fts_link ? p->fts_link : p->fts_parent;
1007 static size_t
1008 fts_maxarglen(char * const *argv)
1010 size_t len, max;
1012 for (max = 0; *argv; ++argv)
1013 if ((len = strlen(*argv)) > max)
1014 max = len;
1015 return (max + 1);
1019 * Change to dir specified by fd or p->fts_accpath without getting
1020 * tricked by someone changing the world out from underneath us.
1021 * Assumes p->fts_dev and p->fts_ino are filled in.
1023 static int
1024 fts_safe_changedir(FTS *sp, FTSENT *p, int fd, char *path)
1026 int ret, oerrno, newfd;
1027 struct stat sb;
1029 newfd = fd;
1030 if (ISSET(FTS_NOCHDIR))
1031 return (0);
1032 if (fd < 0 && (newfd = open(path, O_RDONLY|O_DIRECTORY|O_CLOEXEC)) < 0)
1033 return (-1);
1034 if (fstat(newfd, &sb)) {
1035 ret = -1;
1036 goto bail;
1038 if (p->fts_dev != sb.st_dev || p->fts_ino != sb.st_ino) {
1039 errno = ENOENT; /* disinformation */
1040 ret = -1;
1041 goto bail;
1043 ret = fchdir(newfd);
1044 bail:
1045 oerrno = errno;
1046 if (fd < 0)
1047 (void)close(newfd);
1048 errno = oerrno;
1049 return (ret);