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