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