1/* $NetBSD$ */
2
3/*	From OpenBSD: ftw.c,v 1.2 2003/07/21 21:15:32 millert Exp 	*/
4
5/*
6 * Copyright (c) 2003 Todd C. Miller <Todd.Miller@courtesan.com>
7 *
8 * Permission to use, copy, modify, and distribute this software for any
9 * purpose with or without fee is hereby granted, provided that the above
10 * copyright notice and this permission notice appear in all copies.
11 *
12 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
13 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
14 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
15 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
16 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
17 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
18 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
19 *
20 * Sponsored in part by the Defense Advanced Research Projects
21 * Agency (DARPA) and Air Force Research Laboratory, Air Force
22 * Materiel Command, USAF, under agreement number F39502-99-1-0512.
23 */
24#include <sys/cdefs.h>
25
26#ifndef lint
27__RCSID("$NetBSD$");
28#endif
29
30#include <sys/types.h>
31#include <sys/stat.h>
32#include <errno.h>
33#include <fts.h>
34#include <ftw.h>
35#include <limits.h>
36
37int
38ftw(const char *path, int (*fn)(const char *, const struct stat *, int),
39    int nfds)
40{
41	/* LINTED */
42	char * const paths[2] = { __UNCONST(path), NULL };
43	FTSENT *cur;
44	FTS *ftsp;
45	int fnflag, error, sverrno;
46
47	/* XXX - nfds is currently unused */
48	if (nfds < 1 || nfds > OPEN_MAX) {
49		errno = EINVAL;
50		return (-1);
51	}
52
53	ftsp = fts_open(paths, FTS_COMFOLLOW | FTS_NOCHDIR, NULL);
54	if (ftsp == NULL)
55		return (-1);
56	error = 0;
57	while ((cur = fts_read(ftsp)) != NULL) {
58		switch (cur->fts_info) {
59		case FTS_D:
60			fnflag = FTW_D;
61			break;
62		case FTS_DNR:
63			fnflag = FTW_DNR;
64			break;
65		case FTS_DP:
66			/* we only visit in preorder */
67			continue;
68		case FTS_F:
69		case FTS_DEFAULT:
70			fnflag = FTW_F;
71			break;
72		case FTS_NS:
73		case FTS_NSOK:
74		case FTS_SLNONE:
75			fnflag = FTW_NS;
76			break;
77		case FTS_SL:
78			fnflag = FTW_SL;
79			break;
80		case FTS_DC:
81			errno = ELOOP;
82			/* FALLTHROUGH */
83		default:
84			error = -1;
85			goto done;
86		}
87		error = fn(cur->fts_path, cur->fts_statp, fnflag);
88		if (error != 0)
89			break;
90	}
91done:
92	sverrno = errno;
93	if (fts_close(ftsp) != 0 && error == 0)
94		error = -1;
95	else
96		errno = sverrno;
97	return (error);
98}
99