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