]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/glob-util.c
headers: remove unneeded includes from util.h
[thirdparty/systemd.git] / src / basic / glob-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2
3 #include <dirent.h>
4 #include <errno.h>
5 #include <glob.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <unistd.h>
9
10 #include "dirent-util.h"
11 #include "glob-util.h"
12 #include "macro.h"
13 #include "path-util.h"
14 #include "strv.h"
15
16 static void closedir_wrapper(void* v) {
17 (void) closedir(v);
18 }
19
20 int safe_glob(const char *path, int flags, glob_t *pglob) {
21 int k;
22
23 /* We want to set GLOB_ALTDIRFUNC ourselves, don't allow it to be set. */
24 assert(!(flags & GLOB_ALTDIRFUNC));
25
26 if (!pglob->gl_closedir)
27 pglob->gl_closedir = closedir_wrapper;
28 if (!pglob->gl_readdir)
29 pglob->gl_readdir = (struct dirent *(*)(void *)) readdir_no_dot;
30 if (!pglob->gl_opendir)
31 pglob->gl_opendir = (void *(*)(const char *)) opendir;
32 if (!pglob->gl_lstat)
33 pglob->gl_lstat = lstat;
34 if (!pglob->gl_stat)
35 pglob->gl_stat = stat;
36
37 errno = 0;
38 k = glob(path, flags | GLOB_ALTDIRFUNC, NULL, pglob);
39
40 if (k == GLOB_NOMATCH)
41 return -ENOENT;
42 if (k == GLOB_NOSPACE)
43 return -ENOMEM;
44 if (k != 0)
45 return errno > 0 ? -errno : -EIO;
46 if (strv_isempty(pglob->gl_pathv))
47 return -ENOENT;
48
49 return 0;
50 }
51
52 int glob_exists(const char *path) {
53 _cleanup_globfree_ glob_t g = {};
54 int k;
55
56 assert(path);
57
58 k = safe_glob(path, GLOB_NOSORT|GLOB_BRACE, &g);
59 if (k == -ENOENT)
60 return false;
61 if (k < 0)
62 return k;
63 return true;
64 }
65
66 int glob_extend(char ***strv, const char *path) {
67 _cleanup_globfree_ glob_t g = {};
68 int k;
69
70 k = safe_glob(path, GLOB_NOSORT|GLOB_BRACE, &g);
71 if (k < 0)
72 return k;
73
74 return strv_extend_strv(strv, g.gl_pathv, false);
75 }