1 /* vi: set sw=4 ts=4: */
5 * Copyright (C) 1999-2004 by Erik Andersen <andersen@codepoet.org>
7 * Licensed under GPLv2 or later, see file LICENSE in this tarball for details.
12 #undef DEBUG_RECURS_ACTION
15 * Walk down all the directories under the specified
16 * location, and do something (something specified
17 * by the fileAction and dirAction function pointers).
19 * Unfortunately, while nftw(3) could replace this and reduce
20 * code size a bit, nftw() wasn't supported before GNU libc 2.1,
21 * and so isn't sufficiently portable to take over since glibc2.1
22 * is so stinking huge.
25 static int true_action(const char *fileName, struct stat *statbuf, void* userData, int depth)
30 /* fileAction return value of 0 on any file in directory will make
31 * recursive_action() return 0, but it doesn't stop directory traversal
32 * (fileAction/dirAction will be called on each file).
34 * if !depthFirst, dirAction return value of 0 (FALSE) or 2 (SKIP)
35 * prevents recursion into that directory, instead
36 * recursive_action() returns 0 (if FALSE) or 1 (if SKIP).
38 * followLinks=0/1 differs mainly in handling of links to dirs.
39 * 0: lstat(statbuf). Calls fileAction on link name even if points to dir.
40 * 1: stat(statbuf). Calls dirAction and optionally recurse on link to dir.
43 int recursive_action(const char *fileName,
44 int recurse, int followLinks, int depthFirst,
45 int (*fileAction)(const char *fileName, struct stat *statbuf, void* userData, int depth),
46 int (*dirAction)(const char *fileName, struct stat *statbuf, void* userData, int depth),
55 if (!fileAction) fileAction = true_action;
56 if (!dirAction) dirAction = true_action;
58 status = (followLinks ? stat : lstat)(fileName, &statbuf);
61 #ifdef DEBUG_RECURS_ACTION
62 bb_error_msg("status=%d followLinks=%d TRUE=%d",
63 status, followLinks, TRUE);
65 bb_perror_msg("%s", fileName);
69 /* If S_ISLNK(m), then we know that !S_ISDIR(m).
70 * Then we can skip checking first part: if it is true, then
71 * (!dir) is also true! */
72 if ( /* (!followLinks && S_ISLNK(statbuf.st_mode)) || */
73 !S_ISDIR(statbuf.st_mode)
75 return fileAction(fileName, &statbuf, userData, depth);
78 /* It's a directory (or a link to one, and followLinks is set) */
81 return dirAction(fileName, &statbuf, userData, depth);
85 status = dirAction(fileName, &statbuf, userData, depth);
87 bb_perror_msg("%s", fileName);
94 dir = opendir(fileName);
99 while ((next = readdir(dir)) != NULL) {
102 nextFile = concat_subpath_file(fileName, next->d_name);
103 if (nextFile == NULL)
105 if (!recursive_action(nextFile, TRUE, followLinks, depthFirst,
106 fileAction, dirAction, userData, depth+1)) {
113 if (!dirAction(fileName, &statbuf, userData, depth)) {
114 bb_perror_msg("%s", fileName);