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