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