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