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