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