source: rtems/cpukit/libmisc/shell/fts.c @ d526708e

4.104.115
Last change on this file since d526708e was 9a77af8, checked in by Ralf Corsepius <ralf.corsepius@…>, on 03/26/10 at 17:18:43

Add HAVE_CONFIG_H support to let files receive configure defines.

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