chiark / gitweb /
e093a3bba18861548ecac85dea40b01dbcdf997c
[elogind.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
8 #include <fcntl.h>
9 #include <sys/stat.h>
10
11 #include "dirent-util.h"
12 #include "path-util.h"
13 #include "string-util.h"
14
15 int dirent_ensure_type(DIR *d, struct dirent *de) {
16         struct stat st;
17
18         assert(d);
19         assert(de);
20
21         if (de->d_type != DT_UNKNOWN)
22                 return 0;
23
24         if (fstatat(dirfd(d), de->d_name, &st, AT_SYMLINK_NOFOLLOW) < 0)
25                 return -errno;
26
27         de->d_type =
28                 S_ISREG(st.st_mode)  ? DT_REG  :
29                 S_ISDIR(st.st_mode)  ? DT_DIR  :
30                 S_ISLNK(st.st_mode)  ? DT_LNK  :
31                 S_ISFIFO(st.st_mode) ? DT_FIFO :
32                 S_ISSOCK(st.st_mode) ? DT_SOCK :
33                 S_ISCHR(st.st_mode)  ? DT_CHR  :
34                 S_ISBLK(st.st_mode)  ? DT_BLK  :
35                                        DT_UNKNOWN;
36
37         return 0;
38 }
39
40 bool dirent_is_file(const struct dirent *de) {
41         assert(de);
42
43         if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN))
44                 return false;
45
46         if (hidden_or_backup_file(de->d_name))
47                 return false;
48
49         return true;
50 }
51
52 bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) {
53         assert(de);
54
55         if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN))
56                 return false;
57
58         if (de->d_name[0] == '.')
59                 return false;
60
61         if (!suffix)
62                 return true;
63
64         return endswith(de->d_name, suffix);
65 }
66
67 struct dirent* readdir_no_dot(DIR *dirp) {
68         struct dirent* d;
69
70         for (;;) {
71                 d = readdir(dirp);
72                 if (d && dot_or_dot_dot(d->d_name))
73                         continue;
74                 return d;
75         }
76 }