VERSION: Bump version up to Samba 4.17.8...
[Samba.git] / lib / util / tftw.c
blobc59bb6a3b1b851476b683913dc1414c3b3d03bf0
1 /*
2 * Copyright (c) 2008-2018 by Andreas Schneider <asn@samba.org>
4 * Adopted from the csync source code
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20 #include "replace.h"
21 #include "system/filesys.h"
22 #include "system/dir.h"
23 #include "lib/util/debug.h"
25 #include "tftw.h"
28 int tftw(TALLOC_CTX *mem_ctx, const char *fpath, tftw_walker_fn fn, size_t depth, void *userdata)
30 char *filename = NULL;
31 char *d_name = NULL;
32 DIR *dh = NULL;
33 struct dirent *dirent = NULL;
34 struct stat sb = {0};
35 int rc = 0;
37 if (fpath[0] == '\0') {
38 errno = ENOENT;
39 goto error;
42 if ((dh = opendir(fpath)) == NULL) {
43 /* permission denied */
44 if (errno == EACCES) {
45 return 0;
46 } else {
47 DBG_ERR("opendir failed for: [%s]\n", strerror(errno));
48 goto error;
52 while ((dirent = readdir(dh))) {
53 int flag;
55 d_name = dirent->d_name;
56 if (d_name == NULL) {
57 goto error;
60 /* skip "." and ".." */
61 if (d_name[0] == '.' && (d_name[1] == '\0'
62 || (d_name[1] == '.' && d_name[2] == '\0'))) {
63 dirent = NULL;
64 continue;
67 filename = talloc_asprintf(mem_ctx, "%s/%s", fpath, d_name);
68 if (filename == NULL) {
69 goto error;
72 rc = lstat(filename, &sb);
73 if (rc < 0) {
74 dirent = NULL;
75 goto error;
78 switch (sb.st_mode & S_IFMT) {
79 case S_IFLNK:
80 flag = TFTW_FLAG_SLINK;
81 break;
82 case S_IFDIR:
83 flag = TFTW_FLAG_DIR;
84 break;
85 case S_IFBLK:
86 case S_IFCHR:
87 case S_IFSOCK:
88 case S_IFIFO:
89 flag = TFTW_FLAG_SPEC;
90 break;
91 default:
92 flag = TFTW_FLAG_FILE;
93 break;
96 DBG_INFO("walk: [%s]\n", filename);
98 /* Call walker function for each file */
99 rc = fn(mem_ctx, filename, &sb, flag, userdata);
101 if (rc < 0) {
102 DBG_ERR("provided callback fn() failed: [%s]\n",
103 strerror(errno));
104 closedir(dh);
105 goto done;
108 if (flag == TFTW_FLAG_DIR && depth) {
109 rc = tftw(mem_ctx, filename, fn, depth - 1, userdata);
110 if (rc < 0) {
111 closedir(dh);
112 goto done;
115 TALLOC_FREE(filename);
116 dirent = NULL;
118 closedir(dh);
120 done:
121 TALLOC_FREE(filename);
122 return rc;
123 error:
124 if (dh != NULL) {
125 closedir(dh);
127 TALLOC_FREE(filename);
128 return -1;