]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/glob-util.c
Merge pull request #7388 from keszybz/doc-tweak
[thirdparty/systemd.git] / src / basic / glob-util.c
1 /***
2 This file is part of systemd.
3
4 Copyright 2010 Lennart Poettering
5
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
10
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
15
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
18 ***/
19
20 #include <dirent.h>
21 #include <errno.h>
22 #include <glob.h>
23 #include <sys/types.h>
24
25 #include "dirent-util.h"
26 #include "glob-util.h"
27 #include "macro.h"
28 #include "path-util.h"
29 #include "strv.h"
30
31 int safe_glob(const char *path, int flags, glob_t *pglob) {
32 int k;
33
34 /* We want to set GLOB_ALTDIRFUNC ourselves, don't allow it to be set. */
35 assert(!(flags & GLOB_ALTDIRFUNC));
36
37 if (!pglob->gl_closedir)
38 pglob->gl_closedir = (void (*)(void *)) closedir;
39 if (!pglob->gl_readdir)
40 pglob->gl_readdir = (struct dirent *(*)(void *)) readdir_no_dot;
41 if (!pglob->gl_opendir)
42 pglob->gl_opendir = (void *(*)(const char *)) opendir;
43 if (!pglob->gl_lstat)
44 pglob->gl_lstat = lstat;
45 if (!pglob->gl_stat)
46 pglob->gl_stat = stat;
47
48 errno = 0;
49 k = glob(path, flags | GLOB_ALTDIRFUNC, NULL, pglob);
50
51 if (k == GLOB_NOMATCH)
52 return -ENOENT;
53 if (k == GLOB_NOSPACE)
54 return -ENOMEM;
55 if (k != 0)
56 return errno > 0 ? -errno : -EIO;
57 if (strv_isempty(pglob->gl_pathv))
58 return -ENOENT;
59
60 return 0;
61 }
62
63 int glob_exists(const char *path) {
64 _cleanup_globfree_ glob_t g = {};
65 int k;
66
67 assert(path);
68
69 k = safe_glob(path, GLOB_NOSORT|GLOB_BRACE, &g);
70 if (k == -ENOENT)
71 return false;
72 if (k < 0)
73 return k;
74 return true;
75 }
76
77 int glob_extend(char ***strv, const char *path) {
78 _cleanup_globfree_ glob_t g = {};
79 int k;
80
81 k = safe_glob(path, GLOB_NOSORT|GLOB_BRACE, &g);
82 if (k < 0)
83 return k;
84
85 return strv_extend_strv(strv, g.gl_pathv, false);
86 }