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