eliminate protected-visibility data in libc.so with vis.h preinclude
[musl.git] / src / misc / nftw.c
blobefb2b89524747397b0ccf3e5bbfb5438fd9ecd87
1 #include <ftw.h>
2 #include <dirent.h>
3 #include <sys/stat.h>
4 #include <errno.h>
5 #include <unistd.h>
6 #include <string.h>
7 #include <limits.h>
8 #include <pthread.h>
9 #include "libc.h"
11 struct history
13 struct history *chain;
14 dev_t dev;
15 ino_t ino;
16 int level;
17 int base;
20 #undef dirfd
21 #define dirfd(d) (*(int *)d)
23 static int do_nftw(char *path, int (*fn)(const char *, const struct stat *, int, struct FTW *), int fd_limit, int flags, struct history *h)
25 size_t l = strlen(path), j = l && path[l-1]=='/' ? l-1 : l;
26 struct stat st;
27 struct history new;
28 int type;
29 int r;
30 struct FTW lev;
31 char *name;
33 if ((flags & FTW_PHYS) ? lstat(path, &st) : stat(path, &st) < 0) {
34 if (!(flags & FTW_PHYS) && errno==ENOENT && !lstat(path, &st))
35 type = FTW_SLN;
36 else if (errno != EACCES) return -1;
37 else type = FTW_NS;
38 } else if (S_ISDIR(st.st_mode)) {
39 if (access(path, R_OK) < 0) type = FTW_DNR;
40 else if (flags & FTW_DEPTH) type = FTW_DP;
41 else type = FTW_D;
42 } else if (S_ISLNK(st.st_mode)) {
43 if (flags & FTW_PHYS) type = FTW_SL;
44 else type = FTW_SLN;
45 } else {
46 type = FTW_F;
49 if ((flags & FTW_MOUNT) && h && st.st_dev != h->dev)
50 return 0;
52 new.chain = h;
53 new.dev = st.st_dev;
54 new.ino = st.st_ino;
55 new.level = h ? h->level+1 : 0;
56 new.base = l+1;
58 lev.level = new.level;
59 lev.base = h ? h->base : (name=strrchr(path, '/')) ? name-path : 0;
61 if (!(flags & FTW_DEPTH) && (r=fn(path, &st, type, &lev)))
62 return r;
64 for (; h; h = h->chain)
65 if (h->dev == st.st_dev && h->ino == st.st_ino)
66 return 0;
68 if ((type == FTW_D || type == FTW_DP) && fd_limit) {
69 DIR *d = opendir(path);
70 if (d) {
71 struct dirent *de;
72 while ((de = readdir(d))) {
73 if (de->d_name[0] == '.'
74 && (!de->d_name[1]
75 || (de->d_name[1]=='.'
76 && !de->d_name[2]))) continue;
77 if (strlen(de->d_name) >= PATH_MAX-l) {
78 errno = ENAMETOOLONG;
79 closedir(d);
80 return -1;
82 path[j]='/';
83 strcpy(path+j+1, de->d_name);
84 if ((r=do_nftw(path, fn, fd_limit-1, flags, &new))) {
85 closedir(d);
86 return r;
89 closedir(d);
90 } else if (errno != EACCES) {
91 return -1;
95 path[l] = 0;
96 if ((flags & FTW_DEPTH) && (r=fn(path, &st, type, &lev)))
97 return r;
99 return 0;
102 int nftw(const char *path, int (*fn)(const char *, const struct stat *, int, struct FTW *), int fd_limit, int flags)
104 int r, cs;
105 size_t l;
106 char pathbuf[PATH_MAX+1];
108 if (fd_limit <= 0) return 0;
110 l = strlen(path);
111 if (l > PATH_MAX) {
112 errno = ENAMETOOLONG;
113 return -1;
115 memcpy(pathbuf, path, l+1);
117 pthread_setcancelstate(PTHREAD_CANCEL_DISABLE, &cs);
118 r = do_nftw(pathbuf, fn, fd_limit, flags, NULL);
119 pthread_setcancelstate(cs, 0);
120 return r;
123 LFS64(nftw);