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