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