chiark / gitweb /
nspawn: make -U a tiny bit smarter
[elogind.git] / src / basic / dirent-util.c
1 /***
2   This file is part of systemd.
3
4   Copyright 2010-2012 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 <fcntl.h>
21 #include <sys/stat.h>
22
23 #include "dirent-util.h"
24 #include "path-util.h"
25 #include "string-util.h"
26
27 int dirent_ensure_type(DIR *d, struct dirent *de) {
28         struct stat st;
29
30         assert(d);
31         assert(de);
32
33         if (de->d_type != DT_UNKNOWN)
34                 return 0;
35
36         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
37                 return -errno;
38
39         de->d_type =
40                 S_ISREG(st.st_mode)  ? DT_REG  :
41                 S_ISDIR(st.st_mode)  ? DT_DIR  :
42                 S_ISLNK(st.st_mode)  ? DT_LNK  :
43                 S_ISFIFO(st.st_mode) ? DT_FIFO :
44                 S_ISSOCK(st.st_mode) ? DT_SOCK :
45                 S_ISCHR(st.st_mode)  ? DT_CHR  :
46                 S_ISBLK(st.st_mode)  ? DT_BLK  :
47                                        DT_UNKNOWN;
48
49         return 0;
50 }
51
52 bool dirent_is_file(const struct dirent *de) {
53         assert(de);
54
55         if (hidden_file(de->d_name))
56                 return false;
57
58         if (de->d_type != DT_REG &&
59             de->d_type != DT_LNK &&
60             de->d_type != DT_UNKNOWN)
61                 return false;
62
63         return true;
64 }
65
66 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
67         assert(de);
68
69         if (de->d_type != DT_REG &&
70             de->d_type != DT_LNK &&
71             de->d_type != DT_UNKNOWN)
72                 return false;
73
74         if (hidden_file_allow_backup(de->d_name))
75                 return false;
76
77         return endswith(de->d_name, suffix);
78 }