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