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