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