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