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