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"
10
11struct history
12{
13	struct history *chain;
14	dev_t dev;
15	ino_t ino;
16	int level;
17	int base;
18};
19
20#undef dirfd
21#define dirfd(d) (*(int *)d)
22
23static int do_nftw(char *path, int (*fn)(const char *, const struct stat *, int, struct FTW *), int fd_limit, int flags, struct history *h)
24{
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;
32
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;
47	}
48
49	if ((flags & FTW_MOUNT) && h && st.st_dev != h->dev)
50		return 0;
51
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;
57
58	lev.level = new.level;
59	lev.base = h ? h->base : (name=strrchr(path, '/')) ? name-path : 0;
60
61	if (!(flags & FTW_DEPTH) && (r=fn(path, &st, type, &lev)))
62		return r;
63
64	for (; h; h = h->chain)
65		if (h->dev == st.st_dev && h->ino == st.st_ino)
66			return 0;
67
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;
81				}
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;
87				}
88			}
89			closedir(d);
90		} else if (errno != EACCES) {
91			return -1;
92		}
93	}
94
95	path[l] = 0;
96	if ((flags & FTW_DEPTH) && (r=fn(path, &st, type, &lev)))
97		return r;
98
99	return 0;
100}
101
102int nftw(const char *path, int (*fn)(const char *, const struct stat *, int, struct FTW *), int fd_limit, int flags)
103{
104	int r, cs;
105	size_t l;
106	char pathbuf[PATH_MAX+1];
107
108	if (fd_limit <= 0) return 0;
109
110	l = strlen(path);
111	if (l > PATH_MAX) {
112		errno = ENAMETOOLONG;
113		return -1;
114	}
115	memcpy(pathbuf, path, l+1);
116
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;
121}
122
123LFS64(nftw);
124