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