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