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