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