9 /* $Id: compat_fts.c,v 1.9 2015/03/18 19:29:48 schwarze Exp $ */
10 /* $OpenBSD: fts.c,v 1.50 2015/01/16 16:48:51 deraadt Exp $ */
13 * Copyright (c) 1990, 1993, 1994
14 * The Regents of the University of California. All rights reserved.
16 * Redistribution and use in source and binary forms, with or without
17 * modification, are permitted provided that the following conditions
19 * 1. Redistributions of source code must retain the above copyright
20 * notice, this list of conditions and the following disclaimer.
21 * 2. Redistributions in binary form must reproduce the above copyright
22 * notice, this list of conditions and the following disclaimer in the
23 * documentation and/or other materials provided with the distribution.
24 * 3. Neither the name of the University nor the names of its contributors
25 * may be used to endorse or promote products derived from this software
26 * without specific prior written permission.
28 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31 * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
42 #include <sys/types.h>
51 #include "compat_fts.h"
53 #define MAXIMUM(a, b) (((a) > (b)) ? (a) : (b))
55 static FTSENT *fts_alloc(FTS *, const char *, size_t);
56 static FTSENT *fts_build(FTS *);
57 static void fts_lfree(FTSENT *);
58 static void fts_load(FTS *, FTSENT *);
59 static size_t fts_maxarglen(char * const *);
60 static void fts_padjust(FTS *, FTSENT *);
61 static int fts_palloc(FTS *, size_t);
62 static unsigned short fts_stat(FTS *, FTSENT *);
64 #define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2])))
72 #define CLR(opt) (sp->fts_options &= ~(opt))
73 #define ISSET(opt) (sp->fts_options & (opt))
74 #define SET(opt) (sp->fts_options |= (opt))
77 fts_open(char * const *argv, int options, void *dummy)
86 if (options & ~FTS_OPTIONMASK) {
91 /* Allocate/initialize the stream */
92 if ((sp = calloc(1, sizeof(FTS))) == NULL)
94 sp->fts_options = options;
97 * Start out with 1K of path space, and enough, in any case,
98 * to hold the user's paths.
100 if (fts_palloc(sp, MAXIMUM(fts_maxarglen(argv), PATH_MAX)))
103 /* Allocate/initialize root's parent. */
104 if ((parent = fts_alloc(sp, "", 0)) == NULL)
106 parent->fts_level = FTS_ROOTPARENTLEVEL;
108 /* Allocate/initialize root(s). */
109 for (root = NULL, nitems = 0; *argv; ++argv, ++nitems) {
110 /* Don't allow zero-length paths. */
111 if ((len = strlen(*argv)) == 0) {
116 if ((p = fts_alloc(sp, *argv, len)) == NULL)
118 p->fts_level = FTS_ROOTLEVEL;
119 p->fts_parent = parent;
120 p->fts_accpath = p->fts_name;
121 p->fts_info = fts_stat(sp, p);
123 /* Command-line "." and ".." are real directories. */
124 if (p->fts_info == FTS_DOT)
137 * Allocate a dummy pointer and make fts_read think that we've just
138 * finished the node before the root(s); set p->fts_info to FTS_INIT
139 * so that everything about the "current" node is ignored.
141 if ((sp->fts_cur = fts_alloc(sp, "", 0)) == NULL)
143 sp->fts_cur->fts_link = root;
144 sp->fts_cur->fts_info = FTS_INIT;
151 mem3: fts_lfree(root);
153 mem2: free(sp->fts_path);
159 fts_load(FTS *sp, FTSENT *p)
165 * Load the stream structure for the next traversal. Since we don't
166 * actually enter the directory until after the preorder visit, set
167 * the fts_accpath field specially so the chdir gets done to the right
168 * place and the user can access the first node. From fts_open it's
169 * known that the path will fit.
171 len = p->fts_pathlen = p->fts_namelen;
172 memmove(sp->fts_path, p->fts_name, len + 1);
173 if ((cp = strrchr(p->fts_name, '/')) && (cp != p->fts_name || cp[1])) {
175 memmove(p->fts_name, cp, len + 1);
176 p->fts_namelen = len;
178 p->fts_accpath = p->fts_path = sp->fts_path;
179 sp->fts_dev = p->fts_dev;
188 * This still works if we haven't read anything -- the dummy structure
189 * points to the root list, so we step through to the end of the root
190 * list which has a valid parent pointer.
193 for (p = sp->fts_cur; p->fts_level >= FTS_ROOTLEVEL;) {
195 p = p->fts_link ? p->fts_link : p->fts_parent;
201 /* Free up child linked list, sort array, path buffer, stream ptr.*/
203 fts_lfree(sp->fts_child);
211 * Special case of "/" at the end of the path so that slashes aren't
212 * appended which would cause paths to be written as "....//foo".
215 (p->fts_path[p->fts_pathlen - 1] == '/' \
216 ? p->fts_pathlen - 1 : p->fts_pathlen)
225 /* If finished or unrecoverable error, return NULL. */
226 if (sp->fts_cur == NULL || ISSET(FTS_STOP))
229 /* Set current node pointer. */
232 /* Save and zero out user instructions. */
233 instr = p->fts_instr;
234 p->fts_instr = FTS_NOINSTR;
236 /* Directory in pre-order. */
237 if (p->fts_info == FTS_D) {
238 /* If skipped or crossed mount point, do post-order visit. */
239 if (instr == FTS_SKIP ||
240 (ISSET(FTS_XDEV) && p->fts_dev != sp->fts_dev)) {
242 fts_lfree(sp->fts_child);
243 sp->fts_child = NULL;
245 p->fts_info = FTS_DP;
250 * If haven't read do so. If the read fails, fts_build sets
251 * FTS_STOP or the fts_info field of the node.
255 } else if ((sp->fts_child = fts_build(sp)) == NULL) {
261 sp->fts_child = NULL;
265 /* Move to the next node on this level. */
267 if ((p = p->fts_link)) {
271 * If reached the top, return to the original directory (or
272 * the root of the tree), and load the paths for the next root.
274 if (p->fts_level == FTS_ROOTLEVEL) {
276 return (sp->fts_cur = p);
280 * User may have called fts_set on the node. If skipped,
281 * ignore. If followed, get a file descriptor so we can
282 * get back if necessary.
284 if (p->fts_instr == FTS_SKIP)
287 name: t = sp->fts_path + NAPPEND(p->fts_parent);
289 memmove(t, p->fts_name, p->fts_namelen + 1);
290 return (sp->fts_cur = p);
293 /* Move up to the parent node. */
297 if (p->fts_level == FTS_ROOTPARENTLEVEL) {
299 * Done; free everything up and set errno to 0 so the user
300 * can distinguish between error and EOF.
304 return (sp->fts_cur = NULL);
307 /* NUL terminate the pathname. */
308 sp->fts_path[p->fts_pathlen] = '\0';
310 p->fts_info = p->fts_errno ? FTS_ERR : FTS_DP;
311 return (sp->fts_cur = p);
315 * Fts_set takes the stream as an argument although it's not used in this
316 * implementation; it would be necessary if anyone wanted to add global
317 * semantics to fts using fts_set. An error return is allowed for similar
322 fts_set(FTS *sp, FTSENT *p, int instr)
324 if (instr && instr != FTS_NOINSTR && instr != FTS_SKIP) {
328 p->fts_instr = instr;
333 * This is the tricky part -- do not casually change *anything* in here. The
334 * idea is to build the linked list of entries that are used by fts_children
335 * and fts_read. There are lots of special cases.
337 * The real slowdown in walking the tree is the stat calls. If FTS_NOSTAT is
338 * set and it's a physical walk (so that symbolic links can't be directories),
339 * we can do things quickly. First, if it's a 4.4BSD file system, the type
340 * of the file is in the directory entry. Otherwise, we assume that the number
341 * of subdirectories in a node is equal to the number of links to the parent.
342 * The former skips all stat calls. The latter skips stat calls in any leaf
343 * directories and for any files after the subdirectories in the directory have
344 * been found, cutting the stat calls by about 2/3.
354 size_t dlen, len, maxlen;
355 int nitems, level, doadjust;
359 /* Set current node pointer. */
363 * Open the directory for reading. If this fails, we're done.
364 * If being called from fts_read, set the fts_info field.
366 if ((dirp = opendir(cur->fts_accpath)) == NULL) {
367 cur->fts_info = FTS_DNR;
368 cur->fts_errno = errno;
373 * Figure out the max file name length that can be stored in the
374 * current path -- the inner loop allocates more path as necessary.
375 * We really wouldn't have to do the maxlen calculations here, we
376 * could do them in fts_read before returning the path, but it's a
377 * lot easier here since the length is part of the dirent structure.
379 * If not changing directories set a pointer so that can just append
380 * each new name into the path.
383 cp = sp->fts_path + len;
386 maxlen = sp->fts_pathlen - len;
389 * fts_level is signed so we must prevent it from wrapping
390 * around to FTS_ROOTLEVEL and FTS_ROOTPARENTLEVEL.
392 level = cur->fts_level;
393 if (level < FTS_MAXLEVEL)
396 /* Read the directory, attaching each entry to the `link' pointer. */
398 for (head = tail = NULL, nitems = 0; dirp && (dp = readdir(dirp));) {
399 if (ISDOT(dp->d_name))
402 #if HAVE_DIRENT_NAMLEN
405 dlen = strlen(dp->d_name);
408 if (!(p = fts_alloc(sp, dp->d_name, dlen)))
410 if (dlen >= maxlen) { /* include space for NUL */
411 oldaddr = sp->fts_path;
412 if (fts_palloc(sp, dlen + len + 1)) {
414 * No more memory for path or structures. Save
415 * errno, free up the current structure and the
416 * structures already allocated.
418 mem1: saved_errno = errno;
422 (void)closedir(dirp);
423 cur->fts_info = FTS_ERR;
428 /* Did realloc() change the pointer? */
429 if (oldaddr != sp->fts_path) {
431 cp = sp->fts_path + len;
433 maxlen = sp->fts_pathlen - len;
436 p->fts_level = level;
437 p->fts_parent = sp->fts_cur;
438 p->fts_pathlen = len + dlen;
439 if (p->fts_pathlen < len) {
441 * If we wrap, free up the current structure and
442 * the structures already allocated, then error
443 * out with ENAMETOOLONG.
447 (void)closedir(dirp);
448 cur->fts_info = FTS_ERR;
450 errno = ENAMETOOLONG;
454 /* Build a file name for fts_stat to stat. */
455 p->fts_accpath = p->fts_path;
456 memmove(cp, p->fts_name, p->fts_namelen + 1);
458 p->fts_info = fts_stat(sp, p);
460 /* We walk in directory order so "ls -f" doesn't get upset. */
471 (void)closedir(dirp);
474 * If realloc() changed the address of the path, adjust the
475 * addresses for the rest of the tree and the dir list.
478 fts_padjust(sp, head);
481 * If not changing directories, reset the path back to original
484 if (len == sp->fts_pathlen || nitems == 0)
488 /* If didn't find anything, return NULL. */
490 cur->fts_info = FTS_DP;
496 static unsigned short
497 fts_stat(FTS *sp, FTSENT *p)
504 /* If user needs stat info, stat buffer already allocated. */
507 if (lstat(p->fts_accpath, sbp)) {
508 p->fts_errno = errno;
509 memset(sbp, 0, sizeof(struct stat));
513 if (S_ISDIR(sbp->st_mode)) {
515 * Set the device/inode. Used to find cycles and check for
516 * crossing mount points. Also remember the link count, used
517 * in fts_build to limit the number of stat calls. It is
518 * understood that these fields are only referenced if fts_info
521 dev = p->fts_dev = sbp->st_dev;
522 ino = p->fts_ino = sbp->st_ino;
523 p->fts_nlink = sbp->st_nlink;
525 if (ISDOT(p->fts_name))
529 * Cycle detection is done by brute force when the directory
530 * is first encountered. If the tree gets deep enough or the
531 * number of symbolic links to directories is high enough,
532 * something faster might be worthwhile.
534 for (t = p->fts_parent;
535 t->fts_level >= FTS_ROOTLEVEL; t = t->fts_parent)
536 if (ino == t->fts_ino && dev == t->fts_dev) {
542 if (S_ISLNK(sbp->st_mode))
544 if (S_ISREG(sbp->st_mode))
546 return (FTS_DEFAULT);
550 fts_alloc(FTS *sp, const char *name, size_t namelen)
555 len = sizeof(FTSENT) + namelen;
556 if ((p = calloc(1, len)) == NULL)
559 p->fts_path = sp->fts_path;
560 p->fts_namelen = namelen;
561 p->fts_instr = FTS_NOINSTR;
562 p->fts_statp = malloc(sizeof(struct stat));
563 if (p->fts_statp == NULL) {
567 memcpy(p->fts_name, name, namelen);
573 fts_lfree(FTSENT *head)
577 /* Free a linked list of structures. */
579 head = head->fts_link;
585 * Allow essentially unlimited paths; find, rm, ls should all work on any tree.
586 * Most systems will allow creation of paths much longer than PATH_MAX, even
587 * though the kernel won't resolve them. Add the size (not just what's needed)
588 * plus 256 bytes so don't realloc the path 2 bytes at a time.
591 fts_palloc(FTS *sp, size_t more)
596 * Check for possible wraparound.
599 if (sp->fts_pathlen + more < sp->fts_pathlen) {
603 errno = ENAMETOOLONG;
606 sp->fts_pathlen += more;
607 p = realloc(sp->fts_path, sp->fts_pathlen);
619 * When the path is realloc'd, have to fix all of the pointers in structures
623 fts_padjust(FTS *sp, FTSENT *head)
626 char *addr = sp->fts_path;
628 #define ADJUST(p) { \
629 if ((p)->fts_accpath != (p)->fts_name) { \
631 (char *)addr + ((p)->fts_accpath - (p)->fts_path); \
633 (p)->fts_path = addr; \
635 /* Adjust the current set of children. */
636 for (p = sp->fts_child; p; p = p->fts_link)
639 /* Adjust the rest of the tree, including the current level. */
640 for (p = head; p->fts_level >= FTS_ROOTLEVEL;) {
642 p = p->fts_link ? p->fts_link : p->fts_parent;
647 fts_maxarglen(char * const *argv)
651 for (max = 0; *argv; ++argv)
652 if ((len = strlen(*argv)) > max)