fts-compat.c revision 128946
11573Srgrimes/*-
21573Srgrimes * Copyright (c) 1990, 1993, 1994
31573Srgrimes *	The Regents of the University of California.  All rights reserved.
41573Srgrimes *
51573Srgrimes * Redistribution and use in source and binary forms, with or without
61573Srgrimes * modification, are permitted provided that the following conditions
71573Srgrimes * are met:
81573Srgrimes * 1. Redistributions of source code must retain the above copyright
91573Srgrimes *    notice, this list of conditions and the following disclaimer.
101573Srgrimes * 2. Redistributions in binary form must reproduce the above copyright
111573Srgrimes *    notice, this list of conditions and the following disclaimer in the
121573Srgrimes *    documentation and/or other materials provided with the distribution.
131573Srgrimes * 3. All advertising materials mentioning features or use of this software
141573Srgrimes *    must display the following acknowledgement:
151573Srgrimes *	This product includes software developed by the University of
161573Srgrimes *	California, Berkeley and its contributors.
171573Srgrimes * 4. Neither the name of the University nor the names of its contributors
181573Srgrimes *    may be used to endorse or promote products derived from this software
191573Srgrimes *    without specific prior written permission.
201573Srgrimes *
211573Srgrimes * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
221573Srgrimes * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
231573Srgrimes * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
241573Srgrimes * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
251573Srgrimes * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
261573Srgrimes * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
271573Srgrimes * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
281573Srgrimes * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
291573Srgrimes * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
301573Srgrimes * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
311573Srgrimes * SUCH DAMAGE.
3254770Sgreen *
3354770Sgreen * $OpenBSD: fts.c,v 1.22 1999/10/03 19:22:22 millert Exp $
341573Srgrimes */
351573Srgrimes
361573Srgrimes#if defined(LIBC_SCCS) && !defined(lint)
3723668Speterstatic char sccsid[] = "@(#)fts.c	8.6 (Berkeley) 8/14/94";
381573Srgrimes#endif /* LIBC_SCCS and not lint */
3990045Sobrien#include <sys/cdefs.h>
4090045Sobrien__FBSDID("$FreeBSD: head/lib/libc/gen/fts-compat.c 128946 2004-05-05 06:33:00Z kientzle $");
411573Srgrimes
4271579Sdeischen#include "namespace.h"
4377497Skris#include <sys/types.h>
441573Srgrimes#include <sys/param.h>
451573Srgrimes#include <sys/stat.h>
461573Srgrimes
471573Srgrimes#include <dirent.h>
481573Srgrimes#include <errno.h>
491573Srgrimes#include <fcntl.h>
501573Srgrimes#include <fts.h>
511573Srgrimes#include <stdlib.h>
521573Srgrimes#include <string.h>
531573Srgrimes#include <unistd.h>
5471579Sdeischen#include "un-namespace.h"
551573Srgrimes
5690045Sobrienstatic FTSENT	*fts_alloc(FTS *, char *, int);
5790045Sobrienstatic FTSENT	*fts_build(FTS *, int);
5890045Sobrienstatic void	 fts_lfree(FTSENT *);
5990045Sobrienstatic void	 fts_load(FTS *, FTSENT *);
6090045Sobrienstatic size_t	 fts_maxarglen(char * const *);
6190045Sobrienstatic void	 fts_padjust(FTS *, FTSENT *);
6290045Sobrienstatic int	 fts_palloc(FTS *, size_t);
6390045Sobrienstatic FTSENT	*fts_sort(FTS *, FTSENT *, int);
6490045Sobrienstatic u_short	 fts_stat(FTS *, FTSENT *, int);
6590045Sobrienstatic int	 fts_safe_changedir(FTS *, FTSENT *, int, char *);
661573Srgrimes
6728913Simp#define	ISDOT(a)	(a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
681573Srgrimes
6928913Simp#define	CLR(opt)	(sp->fts_options &= ~(opt))
7028913Simp#define	ISSET(opt)	(sp->fts_options & (opt))
7128913Simp#define	SET(opt)	(sp->fts_options |= (opt))
721573Srgrimes
731573Srgrimes#define	FCHDIR(sp, fd)	(!ISSET(FTS_NOCHDIR) && fchdir(fd))
741573Srgrimes
751573Srgrimes/* fts_build flags */
761573Srgrimes#define	BCHILD		1		/* fts_children */
771573Srgrimes#define	BNAMES		2		/* fts_children, names only */
781573Srgrimes#define	BREAD		3		/* fts_read */
791573Srgrimes
801573SrgrimesFTS *
811573Srgrimesfts_open(argv, options, compar)
821573Srgrimes	char * const *argv;
8390045Sobrien	int options;
84103726Swollman	int (*compar)(const FTSENT * const *, const FTSENT * const *);
851573Srgrimes{
8690045Sobrien	FTS *sp;
8790045Sobrien	FTSENT *p, *root;
8890045Sobrien	int nitems;
891573Srgrimes	FTSENT *parent, *tmp;
901573Srgrimes	int len;
911573Srgrimes
921573Srgrimes	/* Options check. */
931573Srgrimes	if (options & ~FTS_OPTIONMASK) {
941573Srgrimes		errno = EINVAL;
951573Srgrimes		return (NULL);
961573Srgrimes	}
971573Srgrimes
981573Srgrimes	/* Allocate/initialize the stream */
99103726Swollman	if ((sp = malloc(sizeof(FTS))) == NULL)
1001573Srgrimes		return (NULL);
1011573Srgrimes	memset(sp, 0, sizeof(FTS));
1021573Srgrimes	sp->fts_compar = compar;
1031573Srgrimes	sp->fts_options = options;
1041573Srgrimes
10554770Sgreen	/* Shush, GCC. */
10654770Sgreen	tmp = NULL;
10754770Sgreen
1081573Srgrimes	/* Logical walks turn on NOCHDIR; symbolic links are too hard. */
1091573Srgrimes	if (ISSET(FTS_LOGICAL))
1101573Srgrimes		SET(FTS_NOCHDIR);
1111573Srgrimes
1121573Srgrimes	/*
1131573Srgrimes	 * Start out with 1K of path space, and enough, in any case,
1141573Srgrimes	 * to hold the user's paths.
1151573Srgrimes	 */
1161573Srgrimes	if (fts_palloc(sp, MAX(fts_maxarglen(argv), MAXPATHLEN)))
1171573Srgrimes		goto mem1;
1181573Srgrimes
1191573Srgrimes	/* Allocate/initialize root's parent. */
1201573Srgrimes	if ((parent = fts_alloc(sp, "", 0)) == NULL)
1211573Srgrimes		goto mem2;
1221573Srgrimes	parent->fts_level = FTS_ROOTPARENTLEVEL;
1231573Srgrimes
1241573Srgrimes	/* Allocate/initialize root(s). */
12564740Sgreen	for (root = NULL, nitems = 0; *argv != NULL; ++argv, ++nitems) {
1261573Srgrimes		/* Don't allow zero-length paths. */
1271573Srgrimes		if ((len = strlen(*argv)) == 0) {
1281573Srgrimes			errno = ENOENT;
1291573Srgrimes			goto mem3;
1301573Srgrimes		}
1311573Srgrimes
1321573Srgrimes		p = fts_alloc(sp, *argv, len);
1331573Srgrimes		p->fts_level = FTS_ROOTLEVEL;
1341573Srgrimes		p->fts_parent = parent;
1351573Srgrimes		p->fts_accpath = p->fts_name;
1361573Srgrimes		p->fts_info = fts_stat(sp, p, ISSET(FTS_COMFOLLOW));
1371573Srgrimes
1381573Srgrimes		/* Command-line "." and ".." are real directories. */
1391573Srgrimes		if (p->fts_info == FTS_DOT)
1401573Srgrimes			p->fts_info = FTS_D;
1411573Srgrimes
1421573Srgrimes		/*
1431573Srgrimes		 * If comparison routine supplied, traverse in sorted
1441573Srgrimes		 * order; otherwise traverse in the order specified.
1451573Srgrimes		 */
1461573Srgrimes		if (compar) {
1471573Srgrimes			p->fts_link = root;
1481573Srgrimes			root = p;
1491573Srgrimes		} else {
1501573Srgrimes			p->fts_link = NULL;
1511573Srgrimes			if (root == NULL)
1521573Srgrimes				tmp = root = p;
1531573Srgrimes			else {
1541573Srgrimes				tmp->fts_link = p;
1551573Srgrimes				tmp = p;
1561573Srgrimes			}
1571573Srgrimes		}
1581573Srgrimes	}
1591573Srgrimes	if (compar && nitems > 1)
1601573Srgrimes		root = fts_sort(sp, root, nitems);
1611573Srgrimes
1621573Srgrimes	/*
1631573Srgrimes	 * Allocate a dummy pointer and make fts_read think that we've just
1641573Srgrimes	 * finished the node before the root(s); set p->fts_info to FTS_INIT
1651573Srgrimes	 * so that everything about the "current" node is ignored.
1661573Srgrimes	 */
1671573Srgrimes	if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
1681573Srgrimes		goto mem3;
1691573Srgrimes	sp->fts_cur->fts_link = root;
1701573Srgrimes	sp->fts_cur->fts_info = FTS_INIT;
1711573Srgrimes
1721573Srgrimes	/*
17354770Sgreen	 * If using chdir(2), grab a file descriptor pointing to dot to ensure
1741573Srgrimes	 * that we can get back here; this could be avoided for some paths,
1751573Srgrimes	 * but almost certainly not worth the effort.  Slashes, symbolic links,
1761573Srgrimes	 * and ".." are all fairly nasty problems.  Note, if we can't get the
1771573Srgrimes	 * descriptor we run anyway, just more slowly.
1781573Srgrimes	 */
17956698Sjasone	if (!ISSET(FTS_NOCHDIR) && (sp->fts_rfd = _open(".", O_RDONLY, 0)) < 0)
1801573Srgrimes		SET(FTS_NOCHDIR);
1811573Srgrimes
1821573Srgrimes	return (sp);
1831573Srgrimes
1841573Srgrimesmem3:	fts_lfree(root);
1851573Srgrimes	free(parent);
1861573Srgrimesmem2:	free(sp->fts_path);
1871573Srgrimesmem1:	free(sp);
1881573Srgrimes	return (NULL);
1891573Srgrimes}
1901573Srgrimes
1911573Srgrimesstatic void
1921573Srgrimesfts_load(sp, p)
1931573Srgrimes	FTS *sp;
19490045Sobrien	FTSENT *p;
1951573Srgrimes{
19690045Sobrien	int len;
19790045Sobrien	char *cp;
1981573Srgrimes
1991573Srgrimes	/*
2001573Srgrimes	 * Load the stream structure for the next traversal.  Since we don't
2011573Srgrimes	 * actually enter the directory until after the preorder visit, set
2021573Srgrimes	 * the fts_accpath field specially so the chdir gets done to the right
2031573Srgrimes	 * place and the user can access the first node.  From fts_open it's
2041573Srgrimes	 * known that the path will fit.
2051573Srgrimes	 */
2061573Srgrimes	len = p->fts_pathlen = p->fts_namelen;
2071573Srgrimes	memmove(sp->fts_path, p->fts_name, len + 1);
2081573Srgrimes	if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
2091573Srgrimes		len = strlen(++cp);
2101573Srgrimes		memmove(p->fts_name, cp, len + 1);
2111573Srgrimes		p->fts_namelen = len;
2121573Srgrimes	}
2131573Srgrimes	p->fts_accpath = p->fts_path = sp->fts_path;
2141573Srgrimes	sp->fts_dev = p->fts_dev;
2151573Srgrimes}
2161573Srgrimes
2171573Srgrimesint
2181573Srgrimesfts_close(sp)
2191573Srgrimes	FTS *sp;
2201573Srgrimes{
22190045Sobrien	FTSENT *freep, *p;
2221573Srgrimes	int saved_errno;
2231573Srgrimes
2241573Srgrimes	/*
2251573Srgrimes	 * This still works if we haven't read anything -- the dummy structure
2261573Srgrimes	 * points to the root list, so we step through to the end of the root
2271573Srgrimes	 * list which has a valid parent pointer.
2281573Srgrimes	 */
2291573Srgrimes	if (sp->fts_cur) {
2301573Srgrimes		for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
2311573Srgrimes			freep = p;
23264740Sgreen			p = p->fts_link != NULL ? p->fts_link : p->fts_parent;
2331573Srgrimes			free(freep);
2341573Srgrimes		}
2351573Srgrimes		free(p);
2361573Srgrimes	}
2371573Srgrimes
2381573Srgrimes	/* Free up child linked list, sort array, path buffer. */
2391573Srgrimes	if (sp->fts_child)
2401573Srgrimes		fts_lfree(sp->fts_child);
2411573Srgrimes	if (sp->fts_array)
2421573Srgrimes		free(sp->fts_array);
2431573Srgrimes	free(sp->fts_path);
2441573Srgrimes
2451573Srgrimes	/* Return to original directory, save errno if necessary. */
2461573Srgrimes	if (!ISSET(FTS_NOCHDIR)) {
2471573Srgrimes		saved_errno = fchdir(sp->fts_rfd) ? errno : 0;
24856698Sjasone		(void)_close(sp->fts_rfd);
24954770Sgreen
25054770Sgreen		/* Set errno and return. */
25154770Sgreen		if (saved_errno != 0) {
25254770Sgreen			/* Free up the stream pointer. */
25354770Sgreen			free(sp);
25454770Sgreen			errno = saved_errno;
25554770Sgreen			return (-1);
25654770Sgreen		}
2571573Srgrimes	}
2581573Srgrimes
25937349Sphk	/* Free up the stream pointer. */
26037349Sphk	free(sp);
2611573Srgrimes	return (0);
2621573Srgrimes}
2631573Srgrimes
2641573Srgrimes/*
26528913Simp * Special case of "/" at the end of the path so that slashes aren't
26628913Simp * appended which would cause paths to be written as "....//foo".
2671573Srgrimes */
2681573Srgrimes#define	NAPPEND(p)							\
26928913Simp	(p->fts_path[p->fts_pathlen - 1] == '/'				\
27028913Simp	    ? p->fts_pathlen - 1 : p->fts_pathlen)
2711573Srgrimes
2721573SrgrimesFTSENT *
2731573Srgrimesfts_read(sp)
27490045Sobrien	FTS *sp;
2751573Srgrimes{
27690045Sobrien	FTSENT *p, *tmp;
27790045Sobrien	int instr;
27890045Sobrien	char *t;
2791573Srgrimes	int saved_errno;
2801573Srgrimes
2811573Srgrimes	/* If finished or unrecoverable error, return NULL. */
2821573Srgrimes	if (sp->fts_cur == NULL || ISSET(FTS_STOP))
2831573Srgrimes		return (NULL);
2841573Srgrimes
2851573Srgrimes	/* Set current node pointer. */
2861573Srgrimes	p = sp->fts_cur;
2871573Srgrimes
2881573Srgrimes	/* Save and zero out user instructions. */
2891573Srgrimes	instr = p->fts_instr;
2901573Srgrimes	p->fts_instr = FTS_NOINSTR;
2911573Srgrimes
2921573Srgrimes	/* Any type of file may be re-visited; re-stat and re-turn. */
2931573Srgrimes	if (instr == FTS_AGAIN) {
2941573Srgrimes		p->fts_info = fts_stat(sp, p, 0);
2951573Srgrimes		return (p);
2961573Srgrimes	}
2971573Srgrimes
2981573Srgrimes	/*
2991573Srgrimes	 * Following a symlink -- SLNONE test allows application to see
3001573Srgrimes	 * SLNONE and recover.  If indirecting through a symlink, have
3011573Srgrimes	 * keep a pointer to current location.  If unable to get that
3021573Srgrimes	 * pointer, follow fails.
3031573Srgrimes	 */
3041573Srgrimes	if (instr == FTS_FOLLOW &&
3051573Srgrimes	    (p->fts_info == FTS_SL || p->fts_info == FTS_SLNONE)) {
3061573Srgrimes		p->fts_info = fts_stat(sp, p, 1);
30754770Sgreen		if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
30856698Sjasone			if ((p->fts_symfd = _open(".", O_RDONLY, 0)) < 0) {
3091573Srgrimes				p->fts_errno = errno;
3101573Srgrimes				p->fts_info = FTS_ERR;
3111573Srgrimes			} else
3121573Srgrimes				p->fts_flags |= FTS_SYMFOLLOW;
31354770Sgreen		}
3141573Srgrimes		return (p);
3151573Srgrimes	}
3161573Srgrimes
3171573Srgrimes	/* Directory in pre-order. */
3181573Srgrimes	if (p->fts_info == FTS_D) {
3191573Srgrimes		/* If skipped or crossed mount point, do post-order visit. */
3201573Srgrimes		if (instr == FTS_SKIP ||
32128913Simp		    (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
3221573Srgrimes			if (p->fts_flags & FTS_SYMFOLLOW)
32356698Sjasone				(void)_close(p->fts_symfd);
3241573Srgrimes			if (sp->fts_child) {
3251573Srgrimes				fts_lfree(sp->fts_child);
3261573Srgrimes				sp->fts_child = NULL;
3271573Srgrimes			}
3281573Srgrimes			p->fts_info = FTS_DP;
3291573Srgrimes			return (p);
3308870Srgrimes		}
3311573Srgrimes
3321573Srgrimes		/* Rebuild if only read the names and now traversing. */
33364740Sgreen		if (sp->fts_child != NULL && ISSET(FTS_NAMEONLY)) {
33428913Simp			CLR(FTS_NAMEONLY);
3351573Srgrimes			fts_lfree(sp->fts_child);
3361573Srgrimes			sp->fts_child = NULL;
3371573Srgrimes		}
3381573Srgrimes
3391573Srgrimes		/*
3401573Srgrimes		 * Cd to the subdirectory.
3411573Srgrimes		 *
3421573Srgrimes		 * If have already read and now fail to chdir, whack the list
3431573Srgrimes		 * to make the names come out right, and set the parent errno
3441573Srgrimes		 * so the application will eventually get an error condition.
3451573Srgrimes		 * Set the FTS_DONTCHDIR flag so that when we logically change
3461573Srgrimes		 * directories back to the parent we don't do a chdir.
3471573Srgrimes		 *
3481573Srgrimes		 * If haven't read do so.  If the read fails, fts_build sets
3491573Srgrimes		 * FTS_STOP or the fts_info field of the node.
3501573Srgrimes		 */
35164740Sgreen		if (sp->fts_child != NULL) {
35277599Skris			if (fts_safe_changedir(sp, p, -1, p->fts_accpath)) {
3531573Srgrimes				p->fts_errno = errno;
3541573Srgrimes				p->fts_flags |= FTS_DONTCHDIR;
35564740Sgreen				for (p = sp->fts_child; p != NULL;
35664740Sgreen				    p = p->fts_link)
3571573Srgrimes					p->fts_accpath =
3581573Srgrimes					    p->fts_parent->fts_accpath;
3591573Srgrimes			}
3601573Srgrimes		} else if ((sp->fts_child = fts_build(sp, BREAD)) == NULL) {
3611573Srgrimes			if (ISSET(FTS_STOP))
3621573Srgrimes				return (NULL);
3631573Srgrimes			return (p);
3641573Srgrimes		}
3651573Srgrimes		p = sp->fts_child;
3661573Srgrimes		sp->fts_child = NULL;
3671573Srgrimes		goto name;
3681573Srgrimes	}
3691573Srgrimes
3701573Srgrimes	/* Move to the next node on this level. */
3711573Srgrimesnext:	tmp = p;
37264740Sgreen	if ((p = p->fts_link) != NULL) {
3731573Srgrimes		free(tmp);
3741573Srgrimes
3751573Srgrimes		/*
37654770Sgreen		 * If reached the top, return to the original directory (or
37754770Sgreen		 * the root of the tree), and load the paths for the next root.
3781573Srgrimes		 */
3791573Srgrimes		if (p->fts_level == FTS_ROOTLEVEL) {
38028913Simp			if (FCHDIR(sp, sp->fts_rfd)) {
3811573Srgrimes				SET(FTS_STOP);
3821573Srgrimes				return (NULL);
3831573Srgrimes			}
3841573Srgrimes			fts_load(sp, p);
3851573Srgrimes			return (sp->fts_cur = p);
3861573Srgrimes		}
3871573Srgrimes
3881573Srgrimes		/*
3891573Srgrimes		 * User may have called fts_set on the node.  If skipped,
3901573Srgrimes		 * ignore.  If followed, get a file descriptor so we can
3911573Srgrimes		 * get back if necessary.
3921573Srgrimes		 */
3931573Srgrimes		if (p->fts_instr == FTS_SKIP)
3941573Srgrimes			goto next;
3951573Srgrimes		if (p->fts_instr == FTS_FOLLOW) {
3961573Srgrimes			p->fts_info = fts_stat(sp, p, 1);
39754770Sgreen			if (p->fts_info == FTS_D && !ISSET(FTS_NOCHDIR)) {
3981573Srgrimes				if ((p->fts_symfd =
39956698Sjasone				    _open(".", O_RDONLY, 0)) < 0) {
4001573Srgrimes					p->fts_errno = errno;
4011573Srgrimes					p->fts_info = FTS_ERR;
4021573Srgrimes				} else
4031573Srgrimes					p->fts_flags |= FTS_SYMFOLLOW;
40454770Sgreen			}
4051573Srgrimes			p->fts_instr = FTS_NOINSTR;
4061573Srgrimes		}
4071573Srgrimes
4081573Srgrimesname:		t = sp->fts_path + NAPPEND(p->fts_parent);
4091573Srgrimes		*t++ = '/';
4101573Srgrimes		memmove(t, p->fts_name, p->fts_namelen + 1);
4111573Srgrimes		return (sp->fts_cur = p);
4121573Srgrimes	}
4131573Srgrimes
4141573Srgrimes	/* Move up to the parent node. */
4151573Srgrimes	p = tmp->fts_parent;
4161573Srgrimes	free(tmp);
4171573Srgrimes
4181573Srgrimes	if (p->fts_level == FTS_ROOTPARENTLEVEL) {
4191573Srgrimes		/*
4201573Srgrimes		 * Done; free everything up and set errno to 0 so the user
4211573Srgrimes		 * can distinguish between error and EOF.
4221573Srgrimes		 */
4231573Srgrimes		free(p);
4241573Srgrimes		errno = 0;
4251573Srgrimes		return (sp->fts_cur = NULL);
4261573Srgrimes	}
4271573Srgrimes
42854770Sgreen	/* NUL terminate the pathname. */
4291573Srgrimes	sp->fts_path[p->fts_pathlen] = '\0';
4301573Srgrimes
4311573Srgrimes	/*
4321573Srgrimes	 * Return to the parent directory.  If at a root node or came through
4331573Srgrimes	 * a symlink, go back through the file descriptor.  Otherwise, cd up
4341573Srgrimes	 * one directory.
4351573Srgrimes	 */
4361573Srgrimes	if (p->fts_level == FTS_ROOTLEVEL) {
43728913Simp		if (FCHDIR(sp, sp->fts_rfd)) {
4381573Srgrimes			SET(FTS_STOP);
4391573Srgrimes			return (NULL);
4401573Srgrimes		}
4411573Srgrimes	} else if (p->fts_flags & FTS_SYMFOLLOW) {
4421573Srgrimes		if (FCHDIR(sp, p->fts_symfd)) {
4431573Srgrimes			saved_errno = errno;
44456698Sjasone			(void)_close(p->fts_symfd);
4451573Srgrimes			errno = saved_errno;
4461573Srgrimes			SET(FTS_STOP);
4471573Srgrimes			return (NULL);
4481573Srgrimes		}
44956698Sjasone		(void)_close(p->fts_symfd);
45077497Skris	} else if (!(p->fts_flags & FTS_DONTCHDIR) &&
45177599Skris		   fts_safe_changedir(sp, p->fts_parent, -1, "..")) {
45277599Skris		SET(FTS_STOP);
45377599Skris		return (NULL);
4541573Srgrimes	}
4551573Srgrimes	p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
4561573Srgrimes	return (sp->fts_cur = p);
4571573Srgrimes}
4581573Srgrimes
4591573Srgrimes/*
4601573Srgrimes * Fts_set takes the stream as an argument although it's not used in this
4611573Srgrimes * implementation; it would be necessary if anyone wanted to add global
4621573Srgrimes * semantics to fts using fts_set.  An error return is allowed for similar
4631573Srgrimes * reasons.
4641573Srgrimes */
4651573Srgrimes/* ARGSUSED */
4661573Srgrimesint
4671573Srgrimesfts_set(sp, p, instr)
4681573Srgrimes	FTS *sp;
4691573Srgrimes	FTSENT *p;
4701573Srgrimes	int instr;
4711573Srgrimes{
47264740Sgreen	if (instr != 0 && instr != FTS_AGAIN && instr != FTS_FOLLOW &&
4731573Srgrimes	    instr != FTS_NOINSTR && instr != FTS_SKIP) {
4741573Srgrimes		errno = EINVAL;
4751573Srgrimes		return (1);
4761573Srgrimes	}
4771573Srgrimes	p->fts_instr = instr;
4781573Srgrimes	return (0);
4791573Srgrimes}
4801573Srgrimes
4811573SrgrimesFTSENT *
4821573Srgrimesfts_children(sp, instr)
48390045Sobrien	FTS *sp;
4841573Srgrimes	int instr;
4851573Srgrimes{
48690045Sobrien	FTSENT *p;
4871573Srgrimes	int fd;
4881573Srgrimes
48964740Sgreen	if (instr != 0 && instr != FTS_NAMEONLY) {
4901573Srgrimes		errno = EINVAL;
4911573Srgrimes		return (NULL);
4921573Srgrimes	}
4931573Srgrimes
4941573Srgrimes	/* Set current node pointer. */
4951573Srgrimes	p = sp->fts_cur;
4961573Srgrimes
4971573Srgrimes	/*
4981573Srgrimes	 * Errno set to 0 so user can distinguish empty directory from
4991573Srgrimes	 * an error.
5001573Srgrimes	 */
5011573Srgrimes	errno = 0;
5021573Srgrimes
5031573Srgrimes	/* Fatal errors stop here. */
5041573Srgrimes	if (ISSET(FTS_STOP))
5051573Srgrimes		return (NULL);
5061573Srgrimes
5071573Srgrimes	/* Return logical hierarchy of user's arguments. */
5081573Srgrimes	if (p->fts_info == FTS_INIT)
5091573Srgrimes		return (p->fts_link);
5101573Srgrimes
5111573Srgrimes	/*
5121573Srgrimes	 * If not a directory being visited in pre-order, stop here.  Could
5131573Srgrimes	 * allow FTS_DNR, assuming the user has fixed the problem, but the
5141573Srgrimes	 * same effect is available with FTS_AGAIN.
5151573Srgrimes	 */
5161573Srgrimes	if (p->fts_info != FTS_D /* && p->fts_info != FTS_DNR */)
5171573Srgrimes		return (NULL);
5181573Srgrimes
5191573Srgrimes	/* Free up any previous child list. */
52064740Sgreen	if (sp->fts_child != NULL)
5211573Srgrimes		fts_lfree(sp->fts_child);
5221573Srgrimes
5231573Srgrimes	if (instr == FTS_NAMEONLY) {
52428913Simp		SET(FTS_NAMEONLY);
5251573Srgrimes		instr = BNAMES;
5268870Srgrimes	} else
5271573Srgrimes		instr = BCHILD;
5281573Srgrimes
5291573Srgrimes	/*
5301573Srgrimes	 * If using chdir on a relative path and called BEFORE fts_read does
5311573Srgrimes	 * its chdir to the root of a traversal, we can lose -- we need to
5321573Srgrimes	 * chdir into the subdirectory, and we don't know where the current
5331573Srgrimes	 * directory is, so we can't get back so that the upcoming chdir by
5341573Srgrimes	 * fts_read will work.
5351573Srgrimes	 */
5361573Srgrimes	if (p->fts_level != FTS_ROOTLEVEL || p->fts_accpath[0] == '/' ||
5371573Srgrimes	    ISSET(FTS_NOCHDIR))
5381573Srgrimes		return (sp->fts_child = fts_build(sp, instr));
5391573Srgrimes
54056698Sjasone	if ((fd = _open(".", O_RDONLY, 0)) < 0)
5411573Srgrimes		return (NULL);
5421573Srgrimes	sp->fts_child = fts_build(sp, instr);
5431573Srgrimes	if (fchdir(fd))
5441573Srgrimes		return (NULL);
54556698Sjasone	(void)_close(fd);
5461573Srgrimes	return (sp->fts_child);
5471573Srgrimes}
5481573Srgrimes
549103726Swollman#ifndef fts_get_clientptr
550103726Swollman#error "fts_get_clientptr not defined"
551103726Swollman#endif
552103726Swollman
553103726Swollmanvoid *
554103726Swollman(fts_get_clientptr)(FTS *sp)
555103726Swollman{
556103726Swollman
557103726Swollman	return (fts_get_clientptr(sp));
558103726Swollman}
559103726Swollman
560103726Swollman#ifndef fts_get_stream
561103726Swollman#error "fts_get_stream not defined"
562103726Swollman#endif
563103726Swollman
564103726SwollmanFTS *
565103726Swollman(fts_get_stream)(FTSENT *p)
566103726Swollman{
567103726Swollman	return (fts_get_stream(p));
568103726Swollman}
569103726Swollman
570103726Swollmanvoid
571103726Swollmanfts_set_clientptr(FTS *sp, void *clientptr)
572103726Swollman{
573103726Swollman
574103726Swollman	sp->fts_clientptr = clientptr;
575103726Swollman}
576103726Swollman
5771573Srgrimes/*
5781573Srgrimes * This is the tricky part -- do not casually change *anything* in here.  The
5791573Srgrimes * idea is to build the linked list of entries that are used by fts_children
5801573Srgrimes * and fts_read.  There are lots of special cases.
5811573Srgrimes *
5821573Srgrimes * The real slowdown in walking the tree is the stat calls.  If FTS_NOSTAT is
5831573Srgrimes * set and it's a physical walk (so that symbolic links can't be directories),
5841573Srgrimes * we can do things quickly.  First, if it's a 4.4BSD file system, the type
5851573Srgrimes * of the file is in the directory entry.  Otherwise, we assume that the number
5861573Srgrimes * of subdirectories in a node is equal to the number of links to the parent.
5871573Srgrimes * The former skips all stat calls.  The latter skips stat calls in any leaf
5881573Srgrimes * directories and for any files after the subdirectories in the directory have
5891573Srgrimes * been found, cutting the stat calls by about 2/3.
5901573Srgrimes */
5911573Srgrimesstatic FTSENT *
5921573Srgrimesfts_build(sp, type)
59390045Sobrien	FTS *sp;
5941573Srgrimes	int type;
5951573Srgrimes{
59690045Sobrien	struct dirent *dp;
59790045Sobrien	FTSENT *p, *head;
59890045Sobrien	int nitems;
5991573Srgrimes	FTSENT *cur, *tail;
6001573Srgrimes	DIR *dirp;
60154770Sgreen	void *oldaddr;
602128946Skientzle	size_t dnamlen;
60354770Sgreen	int cderrno, descend, len, level, maxlen, nlinks, oflag, saved_errno,
60454770Sgreen	    nostat, doadjust;
6051573Srgrimes	char *cp;
6061573Srgrimes
6071573Srgrimes	/* Set current node pointer. */
6081573Srgrimes	cur = sp->fts_cur;
6091573Srgrimes
6101573Srgrimes	/*
6111573Srgrimes	 * Open the directory for reading.  If this fails, we're done.
6121573Srgrimes	 * If being called from fts_read, set the fts_info field.
6131573Srgrimes	 */
61423668Speter#ifdef FTS_WHITEOUT
61523668Speter	if (ISSET(FTS_WHITEOUT))
61623668Speter		oflag = DTF_NODUP|DTF_REWIND;
61723668Speter	else
61823668Speter		oflag = DTF_HIDEW|DTF_NODUP|DTF_REWIND;
61923668Speter#else
62023668Speter#define __opendir2(path, flag) opendir(path)
62123668Speter#endif
62223668Speter	if ((dirp = __opendir2(cur->fts_accpath, oflag)) == NULL) {
6231573Srgrimes		if (type == BREAD) {
6241573Srgrimes			cur->fts_info = FTS_DNR;
6251573Srgrimes			cur->fts_errno = errno;
6261573Srgrimes		}
6271573Srgrimes		return (NULL);
6281573Srgrimes	}
6291573Srgrimes
6301573Srgrimes	/*
6311573Srgrimes	 * Nlinks is the number of possible entries of type directory in the
6321573Srgrimes	 * directory if we're cheating on stat calls, 0 if we're not doing
6331573Srgrimes	 * any stat calls at all, -1 if we're doing stats on everything.
6341573Srgrimes	 */
63554770Sgreen	if (type == BNAMES) {
6361573Srgrimes		nlinks = 0;
63754770Sgreen		/* Be quiet about nostat, GCC. */
63854770Sgreen		nostat = 0;
63954770Sgreen	} else if (ISSET(FTS_NOSTAT) && ISSET(FTS_PHYSICAL)) {
6401573Srgrimes		nlinks = cur->fts_nlink - (ISSET(FTS_SEEDOT) ? 0 : 2);
64154770Sgreen		nostat = 1;
64254770Sgreen	} else {
6431573Srgrimes		nlinks = -1;
64454770Sgreen		nostat = 0;
64554770Sgreen	}
6461573Srgrimes
6471573Srgrimes#ifdef notdef
6481573Srgrimes	(void)printf("nlinks == %d (cur: %d)\n", nlinks, cur->fts_nlink);
6491573Srgrimes	(void)printf("NOSTAT %d PHYSICAL %d SEEDOT %d\n",
6501573Srgrimes	    ISSET(FTS_NOSTAT), ISSET(FTS_PHYSICAL), ISSET(FTS_SEEDOT));
6511573Srgrimes#endif
6521573Srgrimes	/*
6531573Srgrimes	 * If we're going to need to stat anything or we want to descend
6541573Srgrimes	 * and stay in the directory, chdir.  If this fails we keep going,
6551573Srgrimes	 * but set a flag so we don't chdir after the post-order visit.
6561573Srgrimes	 * We won't be able to stat anything, but we can still return the
6571573Srgrimes	 * names themselves.  Note, that since fts_read won't be able to
6581573Srgrimes	 * chdir into the directory, it will have to return different path
6591573Srgrimes	 * names than before, i.e. "a/b" instead of "b".  Since the node
6601573Srgrimes	 * has already been visited in pre-order, have to wait until the
6611573Srgrimes	 * post-order visit to return the error.  There is a special case
6621573Srgrimes	 * here, if there was nothing to stat then it's not an error to
6631573Srgrimes	 * not be able to stat.  This is all fairly nasty.  If a program
6641573Srgrimes	 * needed sorted entries or stat information, they had better be
6651573Srgrimes	 * checking FTS_NS on the returned nodes.
6661573Srgrimes	 */
6671573Srgrimes	cderrno = 0;
66854770Sgreen	if (nlinks || type == BREAD) {
66977599Skris		if (fts_safe_changedir(sp, cur, dirfd(dirp), NULL)) {
6701573Srgrimes			if (nlinks && type == BREAD)
6711573Srgrimes				cur->fts_errno = errno;
6721573Srgrimes			cur->fts_flags |= FTS_DONTCHDIR;
6731573Srgrimes			descend = 0;
6741573Srgrimes			cderrno = errno;
67528913Simp			(void)closedir(dirp);
67628913Simp			dirp = NULL;
6771573Srgrimes		} else
6781573Srgrimes			descend = 1;
67954770Sgreen	} else
6801573Srgrimes		descend = 0;
6811573Srgrimes
6821573Srgrimes	/*
6831573Srgrimes	 * Figure out the max file name length that can be stored in the
6841573Srgrimes	 * current path -- the inner loop allocates more path as necessary.
6851573Srgrimes	 * We really wouldn't have to do the maxlen calculations here, we
6861573Srgrimes	 * could do them in fts_read before returning the path, but it's a
6871573Srgrimes	 * lot easier here since the length is part of the dirent structure.
6881573Srgrimes	 *
6891573Srgrimes	 * If not changing directories set a pointer so that can just append
6901573Srgrimes	 * each new name into the path.
6911573Srgrimes	 */
6921573Srgrimes	len = NAPPEND(cur);
6931573Srgrimes	if (ISSET(FTS_NOCHDIR)) {
6941573Srgrimes		cp = sp->fts_path + len;
6951573Srgrimes		*cp++ = '/';
69654770Sgreen	} else {
69754770Sgreen		/* GCC, you're too verbose. */
69854770Sgreen		cp = NULL;
6991573Srgrimes	}
70054770Sgreen	len++;
70154770Sgreen	maxlen = sp->fts_pathlen - len;
7021573Srgrimes
7031573Srgrimes	level = cur->fts_level + 1;
7041573Srgrimes
7051573Srgrimes	/* Read the directory, attaching each entry to the `link' pointer. */
70654770Sgreen	doadjust = 0;
70728913Simp	for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) {
708128946Skientzle		dnamlen = dp->d_namlen;
7091573Srgrimes		if (!ISSET(FTS_SEEDOT) && ISDOT(dp->d_name))
7101573Srgrimes			continue;
7111573Srgrimes
712128946Skientzle		if ((p = fts_alloc(sp, dp->d_name, (int)dnamlen)) == NULL)
7131573Srgrimes			goto mem1;
714128946Skientzle		if (dnamlen >= maxlen) {	/* include space for NUL */
71554770Sgreen			oldaddr = sp->fts_path;
716128946Skientzle			if (fts_palloc(sp, dnamlen + len + 1)) {
7171573Srgrimes				/*
7181573Srgrimes				 * No more memory for path or structures.  Save
7191573Srgrimes				 * errno, free up the current structure and the
7201573Srgrimes				 * structures already allocated.
7211573Srgrimes				 */
7221573Srgrimesmem1:				saved_errno = errno;
7231573Srgrimes				if (p)
7241573Srgrimes					free(p);
7251573Srgrimes				fts_lfree(head);
7261573Srgrimes				(void)closedir(dirp);
7271573Srgrimes				cur->fts_info = FTS_ERR;
7281573Srgrimes				SET(FTS_STOP);
72954770Sgreen				errno = saved_errno;
7301573Srgrimes				return (NULL);
7311573Srgrimes			}
73254770Sgreen			/* Did realloc() change the pointer? */
73354770Sgreen			if (oldaddr != sp->fts_path) {
73454770Sgreen				doadjust = 1;
73554770Sgreen				if (ISSET(FTS_NOCHDIR))
73654770Sgreen					cp = sp->fts_path + len;
73754770Sgreen			}
73854770Sgreen			maxlen = sp->fts_pathlen - len;
7391573Srgrimes		}
7401573Srgrimes
741128946Skientzle		if (len + dnamlen >= USHRT_MAX) {
74254770Sgreen			/*
74354770Sgreen			 * In an FTSENT, fts_pathlen is a u_short so it is
74454770Sgreen			 * possible to wraparound here.  If we do, free up
74554770Sgreen			 * the current structure and the structures already
74654770Sgreen			 * allocated, then error out with ENAMETOOLONG.
74754770Sgreen			 */
74854770Sgreen			free(p);
74954770Sgreen			fts_lfree(head);
75054770Sgreen			(void)closedir(dirp);
75154770Sgreen			cur->fts_info = FTS_ERR;
75254770Sgreen			SET(FTS_STOP);
75354770Sgreen			errno = ENAMETOOLONG;
75454770Sgreen			return (NULL);
75554770Sgreen		}
75654770Sgreen		p->fts_level = level;
7571573Srgrimes		p->fts_parent = sp->fts_cur;
758128946Skientzle		p->fts_pathlen = len + dnamlen;
7591573Srgrimes
76023668Speter#ifdef FTS_WHITEOUT
76123668Speter		if (dp->d_type == DT_WHT)
76223668Speter			p->fts_flags |= FTS_ISW;
76323668Speter#endif
76423668Speter
7651573Srgrimes		if (cderrno) {
7661573Srgrimes			if (nlinks) {
7671573Srgrimes				p->fts_info = FTS_NS;
7681573Srgrimes				p->fts_errno = cderrno;
7691573Srgrimes			} else
7701573Srgrimes				p->fts_info = FTS_NSOK;
7711573Srgrimes			p->fts_accpath = cur->fts_accpath;
7721573Srgrimes		} else if (nlinks == 0
7731573Srgrimes#ifdef DT_DIR
77454770Sgreen		    || (nostat &&
77517141Sjkh		    dp->d_type != DT_DIR && dp->d_type != DT_UNKNOWN)
7761573Srgrimes#endif
7771573Srgrimes		    ) {
7781573Srgrimes			p->fts_accpath =
7791573Srgrimes			    ISSET(FTS_NOCHDIR) ? p->fts_path : p->fts_name;
7801573Srgrimes			p->fts_info = FTS_NSOK;
7811573Srgrimes		} else {
7821573Srgrimes			/* Build a file name for fts_stat to stat. */
7831573Srgrimes			if (ISSET(FTS_NOCHDIR)) {
7841573Srgrimes				p->fts_accpath = p->fts_path;
7851573Srgrimes				memmove(cp, p->fts_name, p->fts_namelen + 1);
7861573Srgrimes			} else
7871573Srgrimes				p->fts_accpath = p->fts_name;
7881573Srgrimes			/* Stat it. */
7891573Srgrimes			p->fts_info = fts_stat(sp, p, 0);
7901573Srgrimes
7911573Srgrimes			/* Decrement link count if applicable. */
7921573Srgrimes			if (nlinks > 0 && (p->fts_info == FTS_D ||
7931573Srgrimes			    p->fts_info == FTS_DC || p->fts_info == FTS_DOT))
7941573Srgrimes				--nlinks;
7951573Srgrimes		}
7961573Srgrimes
7971573Srgrimes		/* We walk in directory order so "ls -f" doesn't get upset. */
7981573Srgrimes		p->fts_link = NULL;
7991573Srgrimes		if (head == NULL)
8001573Srgrimes			head = tail = p;
8011573Srgrimes		else {
8021573Srgrimes			tail->fts_link = p;
8031573Srgrimes			tail = p;
8041573Srgrimes		}
8051573Srgrimes		++nitems;
8061573Srgrimes	}
80728913Simp	if (dirp)
80828913Simp		(void)closedir(dirp);
8091573Srgrimes
8101573Srgrimes	/*
81154770Sgreen	 * If realloc() changed the address of the path, adjust the
81254770Sgreen	 * addresses for the rest of the tree and the dir list.
8131573Srgrimes	 */
81454770Sgreen	if (doadjust)
81554770Sgreen		fts_padjust(sp, head);
8161573Srgrimes
8171573Srgrimes	/*
8181573Srgrimes	 * If not changing directories, reset the path back to original
8191573Srgrimes	 * state.
8201573Srgrimes	 */
8211573Srgrimes	if (ISSET(FTS_NOCHDIR)) {
82254770Sgreen		if (len == sp->fts_pathlen || nitems == 0)
8231573Srgrimes			--cp;
8241573Srgrimes		*cp = '\0';
8251573Srgrimes	}
8261573Srgrimes
8271573Srgrimes	/*
8281573Srgrimes	 * If descended after called from fts_children or after called from
8291573Srgrimes	 * fts_read and nothing found, get back.  At the root level we use
8301573Srgrimes	 * the saved fd; if one of fts_open()'s arguments is a relative path
8311573Srgrimes	 * to an empty directory, we wind up here with no other way back.  If
8321573Srgrimes	 * can't get back, we're done.
8331573Srgrimes	 */
8341573Srgrimes	if (descend && (type == BCHILD || !nitems) &&
8351573Srgrimes	    (cur->fts_level == FTS_ROOTLEVEL ?
83677599Skris	    FCHDIR(sp, sp->fts_rfd) :
83777599Skris	    fts_safe_changedir(sp, cur->fts_parent, -1, ".."))) {
8381573Srgrimes		cur->fts_info = FTS_ERR;
8391573Srgrimes		SET(FTS_STOP);
8401573Srgrimes		return (NULL);
8411573Srgrimes	}
8421573Srgrimes
8431573Srgrimes	/* If didn't find anything, return NULL. */
8441573Srgrimes	if (!nitems) {
8451573Srgrimes		if (type == BREAD)
8461573Srgrimes			cur->fts_info = FTS_DP;
8471573Srgrimes		return (NULL);
8481573Srgrimes	}
8491573Srgrimes
8501573Srgrimes	/* Sort the entries. */
8511573Srgrimes	if (sp->fts_compar && nitems > 1)
8521573Srgrimes		head = fts_sort(sp, head, nitems);
8531573Srgrimes	return (head);
8541573Srgrimes}
8551573Srgrimes
8561573Srgrimesstatic u_short
8571573Srgrimesfts_stat(sp, p, follow)
8581573Srgrimes	FTS *sp;
85990045Sobrien	FTSENT *p;
8601573Srgrimes	int follow;
8611573Srgrimes{
86290045Sobrien	FTSENT *t;
86390045Sobrien	dev_t dev;
86490045Sobrien	ino_t ino;
8651573Srgrimes	struct stat *sbp, sb;
8661573Srgrimes	int saved_errno;
8671573Srgrimes
8681573Srgrimes	/* If user needs stat info, stat buffer already allocated. */
8691573Srgrimes	sbp = ISSET(FTS_NOSTAT) ? &sb : p->fts_statp;
8708870Srgrimes
87123668Speter#ifdef FTS_WHITEOUT
87223668Speter	/* check for whiteout */
87323668Speter	if (p->fts_flags & FTS_ISW) {
87423668Speter		if (sbp != &sb) {
87523668Speter			memset(sbp, '\0', sizeof (*sbp));
87623668Speter			sbp->st_mode = S_IFWHT;
87723668Speter		}
87823668Speter		return (FTS_W);
87923668Speter	}
88023668Speter#endif
88123668Speter
8821573Srgrimes	/*
8831573Srgrimes	 * If doing a logical walk, or application requested FTS_FOLLOW, do
8841573Srgrimes	 * a stat(2).  If that fails, check for a non-existent symlink.  If
8851573Srgrimes	 * fail, set the errno from the stat call.
8861573Srgrimes	 */
8871573Srgrimes	if (ISSET(FTS_LOGICAL) || follow) {
8881573Srgrimes		if (stat(p->fts_accpath, sbp)) {
8891573Srgrimes			saved_errno = errno;
8901573Srgrimes			if (!lstat(p->fts_accpath, sbp)) {
8911573Srgrimes				errno = 0;
8921573Srgrimes				return (FTS_SLNONE);
8938870Srgrimes			}
8941573Srgrimes			p->fts_errno = saved_errno;
8951573Srgrimes			goto err;
8961573Srgrimes		}
8971573Srgrimes	} else if (lstat(p->fts_accpath, sbp)) {
8981573Srgrimes		p->fts_errno = errno;
8991573Srgrimeserr:		memset(sbp, 0, sizeof(struct stat));
9001573Srgrimes		return (FTS_NS);
9011573Srgrimes	}
9021573Srgrimes
9031573Srgrimes	if (S_ISDIR(sbp->st_mode)) {
9041573Srgrimes		/*
9051573Srgrimes		 * Set the device/inode.  Used to find cycles and check for
9061573Srgrimes		 * crossing mount points.  Also remember the link count, used
9071573Srgrimes		 * in fts_build to limit the number of stat calls.  It is
9081573Srgrimes		 * understood that these fields are only referenced if fts_info
9091573Srgrimes		 * is set to FTS_D.
9101573Srgrimes		 */
9111573Srgrimes		dev = p->fts_dev = sbp->st_dev;
9121573Srgrimes		ino = p->fts_ino = sbp->st_ino;
9131573Srgrimes		p->fts_nlink = sbp->st_nlink;
9141573Srgrimes
9151573Srgrimes		if (ISDOT(p->fts_name))
9161573Srgrimes			return (FTS_DOT);
9171573Srgrimes
9181573Srgrimes		/*
9191573Srgrimes		 * Cycle detection is done by brute force when the directory
9201573Srgrimes		 * is first encountered.  If the tree gets deep enough or the
9211573Srgrimes		 * number of symbolic links to directories is high enough,
9221573Srgrimes		 * something faster might be worthwhile.
9231573Srgrimes		 */
9241573Srgrimes		for (t = p->fts_parent;
9251573Srgrimes		    t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
9261573Srgrimes			if (ino == t->fts_ino && dev == t->fts_dev) {
9271573Srgrimes				p->fts_cycle = t;
9281573Srgrimes				return (FTS_DC);
9291573Srgrimes			}
9301573Srgrimes		return (FTS_D);
9311573Srgrimes	}
9321573Srgrimes	if (S_ISLNK(sbp->st_mode))
9331573Srgrimes		return (FTS_SL);
9341573Srgrimes	if (S_ISREG(sbp->st_mode))
9351573Srgrimes		return (FTS_F);
9361573Srgrimes	return (FTS_DEFAULT);
9371573Srgrimes}
9381573Srgrimes
939103726Swollman/*
940103726Swollman * The comparison function takes pointers to pointers to FTSENT structures.
941103726Swollman * Qsort wants a comparison function that takes pointers to void.
942103726Swollman * (Both with appropriate levels of const-poisoning, of course!)
943103726Swollman * Use a trampoline function to deal with the difference.
944103726Swollman */
945103726Swollmanstatic int
946103726Swollmanfts_compar(const void *a, const void *b)
947103726Swollman{
948103726Swollman	FTS *parent;
949103726Swollman
950103726Swollman	parent = (*(const FTSENT * const *)a)->fts_fts;
951103726Swollman	return (*parent->fts_compar)(a, b);
952103726Swollman}
953103726Swollman
9541573Srgrimesstatic FTSENT *
9551573Srgrimesfts_sort(sp, head, nitems)
9561573Srgrimes	FTS *sp;
9571573Srgrimes	FTSENT *head;
95890045Sobrien	int nitems;
9591573Srgrimes{
96090045Sobrien	FTSENT **ap, *p;
9611573Srgrimes
9621573Srgrimes	/*
9631573Srgrimes	 * Construct an array of pointers to the structures and call qsort(3).
9641573Srgrimes	 * Reassemble the array in the order returned by qsort.  If unable to
9651573Srgrimes	 * sort for memory reasons, return the directory entries in their
9661573Srgrimes	 * current order.  Allocate enough space for the current needs plus
9671573Srgrimes	 * 40 so don't realloc one entry at a time.
9681573Srgrimes	 */
9691573Srgrimes	if (nitems > sp->fts_nitems) {
9701573Srgrimes		sp->fts_nitems = nitems + 40;
97164740Sgreen		if ((sp->fts_array = reallocf(sp->fts_array,
97254770Sgreen		    sp->fts_nitems * sizeof(FTSENT *))) == NULL) {
9731573Srgrimes			sp->fts_nitems = 0;
9741573Srgrimes			return (head);
9751573Srgrimes		}
9761573Srgrimes	}
9771573Srgrimes	for (ap = sp->fts_array, p = head; p; p = p->fts_link)
9781573Srgrimes		*ap++ = p;
979103726Swollman	qsort(sp->fts_array, nitems, sizeof(FTSENT *), fts_compar);
9801573Srgrimes	for (head = *(ap = sp->fts_array); --nitems; ++ap)
9811573Srgrimes		ap[0]->fts_link = ap[1];
9821573Srgrimes	ap[0]->fts_link = NULL;
9831573Srgrimes	return (head);
9841573Srgrimes}
9851573Srgrimes
9861573Srgrimesstatic FTSENT *
9871573Srgrimesfts_alloc(sp, name, namelen)
9881573Srgrimes	FTS *sp;
9891573Srgrimes	char *name;
99090045Sobrien	int namelen;
9911573Srgrimes{
99290045Sobrien	FTSENT *p;
9931573Srgrimes	size_t len;
9941573Srgrimes
995103726Swollman	struct ftsent_withstat {
996103726Swollman		FTSENT	ent;
997103726Swollman		struct	stat statbuf;
998103726Swollman	};
999103726Swollman
10001573Srgrimes	/*
10011573Srgrimes	 * The file name is a variable length array and no stat structure is
10021573Srgrimes	 * necessary if the user has set the nostat bit.  Allocate the FTSENT
10031573Srgrimes	 * structure, the file name and the stat structure in one chunk, but
1004103726Swollman	 * be careful that the stat structure is reasonably aligned.
10051573Srgrimes	 */
1006103726Swollman	if (ISSET(FTS_NOSTAT))
1007103726Swollman		len = sizeof(FTSENT) + namelen + 1;
1008103726Swollman	else
1009103726Swollman		len = sizeof(struct ftsent_withstat) + namelen + 1;
1010103726Swollman
10111573Srgrimes	if ((p = malloc(len)) == NULL)
10121573Srgrimes		return (NULL);
10131573Srgrimes
1014103726Swollman	if (ISSET(FTS_NOSTAT)) {
1015103726Swollman		p->fts_name = (char *)(p + 1);
1016103726Swollman		p->fts_statp = NULL;
1017103726Swollman	} else {
1018103726Swollman		p->fts_name = (char *)((struct ftsent_withstat *)p + 1);
1019103726Swollman		p->fts_statp = &((struct ftsent_withstat *)p)->statbuf;
1020103726Swollman	}
1021103726Swollman
102254770Sgreen	/* Copy the name and guarantee NUL termination. */
1023103726Swollman	memcpy(p->fts_name, name, namelen);
102454770Sgreen	p->fts_name[namelen] = '\0';
10251573Srgrimes	p->fts_namelen = namelen;
10261573Srgrimes	p->fts_path = sp->fts_path;
10271573Srgrimes	p->fts_errno = 0;
10281573Srgrimes	p->fts_flags = 0;
10291573Srgrimes	p->fts_instr = FTS_NOINSTR;
10301573Srgrimes	p->fts_number = 0;
10311573Srgrimes	p->fts_pointer = NULL;
1032103726Swollman	p->fts_fts = sp;
10331573Srgrimes	return (p);
10341573Srgrimes}
10351573Srgrimes
10361573Srgrimesstatic void
10371573Srgrimesfts_lfree(head)
103890045Sobrien	FTSENT *head;
10391573Srgrimes{
104090045Sobrien	FTSENT *p;
10411573Srgrimes
10421573Srgrimes	/* Free a linked list of structures. */
104328913Simp	while ((p = head)) {
10441573Srgrimes		head = head->fts_link;
10451573Srgrimes		free(p);
10461573Srgrimes	}
10471573Srgrimes}
10481573Srgrimes
10491573Srgrimes/*
10501573Srgrimes * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
10511573Srgrimes * Most systems will allow creation of paths much longer than MAXPATHLEN, even
10521573Srgrimes * though the kernel won't resolve them.  Add the size (not just what's needed)
10538870Srgrimes * plus 256 bytes so don't realloc the path 2 bytes at a time.
10541573Srgrimes */
10551573Srgrimesstatic int
10561573Srgrimesfts_palloc(sp, more)
10571573Srgrimes	FTS *sp;
10581573Srgrimes	size_t more;
10591573Srgrimes{
106054770Sgreen
10611573Srgrimes	sp->fts_pathlen += more + 256;
106254770Sgreen	/*
106354770Sgreen	 * Check for possible wraparound.  In an FTS, fts_pathlen is
106454770Sgreen	 * a signed int but in an FTSENT it is an unsigned short.
106554770Sgreen	 * We limit fts_pathlen to USHRT_MAX to be safe in both cases.
106654770Sgreen	 */
106754770Sgreen	if (sp->fts_pathlen < 0 || sp->fts_pathlen >= USHRT_MAX) {
106854770Sgreen		if (sp->fts_path)
106954770Sgreen			free(sp->fts_path);
107054770Sgreen		sp->fts_path = NULL;
107154770Sgreen		errno = ENAMETOOLONG;
107254770Sgreen		return (1);
107350790Simp	}
107464740Sgreen	sp->fts_path = reallocf(sp->fts_path, sp->fts_pathlen);
107564740Sgreen	return (sp->fts_path == NULL);
107650790Simp}
107750790Simp
10781573Srgrimes/*
10791573Srgrimes * When the path is realloc'd, have to fix all of the pointers in structures
10801573Srgrimes * already returned.
10811573Srgrimes */
10821573Srgrimesstatic void
108354770Sgreenfts_padjust(sp, head)
10841573Srgrimes	FTS *sp;
108554770Sgreen	FTSENT *head;
10861573Srgrimes{
10871573Srgrimes	FTSENT *p;
108854770Sgreen	char *addr = sp->fts_path;
10891573Srgrimes
109064740Sgreen#define	ADJUST(p) do {							\
109154770Sgreen	if ((p)->fts_accpath != (p)->fts_name) {			\
109254770Sgreen		(p)->fts_accpath =					\
109354770Sgreen		    (char *)addr + ((p)->fts_accpath - (p)->fts_path);	\
109454770Sgreen	}								\
10951573Srgrimes	(p)->fts_path = addr;						\
109664740Sgreen} while (0)
10971573Srgrimes	/* Adjust the current set of children. */
10981573Srgrimes	for (p = sp->fts_child; p; p = p->fts_link)
109954770Sgreen		ADJUST(p);
11001573Srgrimes
110154770Sgreen	/* Adjust the rest of the tree, including the current level. */
110254770Sgreen	for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
110354770Sgreen		ADJUST(p);
11041573Srgrimes		p = p->fts_link ? p->fts_link : p->fts_parent;
11051573Srgrimes	}
11061573Srgrimes}
11071573Srgrimes
11081573Srgrimesstatic size_t
11091573Srgrimesfts_maxarglen(argv)
11101573Srgrimes	char * const *argv;
11111573Srgrimes{
11121573Srgrimes	size_t len, max;
11131573Srgrimes
11141573Srgrimes	for (max = 0; *argv; ++argv)
11151573Srgrimes		if ((len = strlen(*argv)) > max)
11161573Srgrimes			max = len;
111754770Sgreen	return (max + 1);
11181573Srgrimes}
111928913Simp
112028913Simp/*
112128913Simp * Change to dir specified by fd or p->fts_accpath without getting
112228913Simp * tricked by someone changing the world out from underneath us.
112328913Simp * Assumes p->fts_dev and p->fts_ino are filled in.
112428913Simp */
112528913Simpstatic int
112677599Skrisfts_safe_changedir(sp, p, fd, path)
112728913Simp	FTS *sp;
112828913Simp	FTSENT *p;
112928913Simp	int fd;
113077599Skris	char *path;
113128913Simp{
113228913Simp	int ret, oerrno, newfd;
113328913Simp	struct stat sb;
113428913Simp
113528913Simp	newfd = fd;
113628913Simp	if (ISSET(FTS_NOCHDIR))
113728913Simp		return (0);
113877599Skris	if (fd < 0 && (newfd = _open(path, O_RDONLY, 0)) < 0)
113928913Simp		return (-1);
114071579Sdeischen	if (_fstat(newfd, &sb)) {
114128913Simp		ret = -1;
114228913Simp		goto bail;
114328913Simp	}
114428913Simp	if (p->fts_dev != sb.st_dev || p->fts_ino != sb.st_ino) {
114528913Simp		errno = ENOENT;		/* disinformation */
114628913Simp		ret = -1;
114728913Simp		goto bail;
114828913Simp	}
114928913Simp	ret = fchdir(newfd);
115028913Simpbail:
115128913Simp	oerrno = errno;
115228913Simp	if (fd < 0)
115356698Sjasone		(void)_close(newfd);
115428913Simp	errno = oerrno;
115528913Simp	return (ret);
115628913Simp}
1157