]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/dirent-util.c
Add SPDX license identifiers to source files under the LGPL
[thirdparty/systemd.git] / src / basic / dirent-util.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2010-2012 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 <fcntl.h>
22 #include <sys/stat.h>
23
24 #include "dirent-util.h"
25 #include "path-util.h"
26 #include "string-util.h"
27
28 int dirent_ensure_type(DIR *d, struct dirent *de) {
29 struct stat st;
30
31 assert(d);
32 assert(de);
33
34 if (de->d_type != DT_UNKNOWN)
35 return 0;
36
37 if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
38 return -errno;
39
40 de->d_type =
41 S_ISREG(st.st_mode) ? DT_REG :
42 S_ISDIR(st.st_mode) ? DT_DIR :
43 S_ISLNK(st.st_mode) ? DT_LNK :
44 S_ISFIFO(st.st_mode) ? DT_FIFO :
45 S_ISSOCK(st.st_mode) ? DT_SOCK :
46 S_ISCHR(st.st_mode) ? DT_CHR :
47 S_ISBLK(st.st_mode) ? DT_BLK :
48 DT_UNKNOWN;
49
50 return 0;
51 }
52
53 bool dirent_is_file(const struct dirent *de) {
54 assert(de);
55
56 if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN))
57 return false;
58
59 if (hidden_or_backup_file(de->d_name))
60 return false;
61
62 return true;
63 }
64
65 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
66 assert(de);
67
68 if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN))
69 return false;
70
71 if (de->d_name[0] == '.')
72 return false;
73
74 if (!suffix)
75 return true;
76
77 return endswith(de->d_name, suffix);
78 }
79
80 struct dirent* readdir_no_dot(DIR *dirp) {
81 struct dirent* d;
82
83 for (;;) {
84 d = readdir(dirp);
85 if (d && dot_or_dot_dot(d->d_name))
86 continue;
87 return d;
88 }
89 }