| 1 |
/* SPDX-License-Identifier: LGPL-2.1-or-later */ |
| 2 |
|
| 3 |
#include <fcntl.h> |
| 4 |
#include <sys/stat.h> |
| 5 |
|
| 6 |
#include "dirent-util.h" |
| 7 |
#include "path-util.h" |
| 8 |
#include "stat-util.h" |
| 9 |
#include "string-util.h" |
| 10 |
|
| 11 |
int dirent_ensure_type(int dir_fd, struct dirent *de) { |
| 12 |
int r; |
| 13 |
|
| 14 |
assert(dir_fd >= 0); |
| 15 |
assert(de); |
| 16 |
|
| 17 |
if (de->d_type != DT_UNKNOWN) |
| 18 |
return 0; |
| 19 |
|
| 20 |
if (dot_or_dot_dot(de->d_name)) { |
| 21 |
de->d_type = DT_DIR; |
| 22 |
return 0; |
| 23 |
} |
| 24 |
|
| 25 |
/* Let's ask only for the type, nothing else. */ |
| 26 |
struct statx sx; |
| 27 |
r = xstatx_full(dir_fd, |
| 28 |
de->d_name, |
| 29 |
AT_SYMLINK_NOFOLLOW|AT_NO_AUTOMOUNT, |
| 30 |
/* xstatx_flags= */ 0, |
| 31 |
/* mandatory_mask= */ STATX_TYPE, |
| 32 |
/* optional_mask= */ STATX_INO, |
| 33 |
/* mandatory_attributes= */ 0, |
| 34 |
&sx); |
| 35 |
if (r < 0) |
| 36 |
return r; |
| 37 |
|
| 38 |
assert(FLAGS_SET(sx.stx_mask, STATX_TYPE)); |
| 39 |
de->d_type = IFTODT(sx.stx_mode); |
| 40 |
|
| 41 |
/* If the inode is passed too, update the field, i.e. report most recent data */ |
| 42 |
if (FLAGS_SET(sx.stx_mask, STATX_INO)) |
| 43 |
de->d_ino = sx.stx_ino; |
| 44 |
|
| 45 |
return 0; |
| 46 |
} |
| 47 |
|
| 48 |
bool dirent_is_file(const struct dirent *de) { |
| 49 |
assert(de); |
| 50 |
|
| 51 |
if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN)) |
| 52 |
return false; |
| 53 |
|
| 54 |
if (hidden_or_backup_file(de->d_name)) |
| 55 |
return false; |
| 56 |
|
| 57 |
return true; |
| 58 |
} |
| 59 |
|
| 60 |
bool dirent_is_file_with_suffix(const struct dirent *de, const char *suffix) { |
| 61 |
assert(de); |
| 62 |
|
| 63 |
if (!IN_SET(de->d_type, DT_REG, DT_LNK, DT_UNKNOWN)) |
| 64 |
return false; |
| 65 |
|
| 66 |
if (de->d_name[0] == '.') |
| 67 |
return false; |
| 68 |
|
| 69 |
if (!suffix) |
| 70 |
return true; |
| 71 |
|
| 72 |
return endswith(de->d_name, suffix); |
| 73 |
} |
| 74 |
|
| 75 |
struct dirent* readdir_ensure_type(DIR *d) { |
| 76 |
int r; |
| 77 |
|
| 78 |
assert(d); |
| 79 |
|
| 80 |
/* Like readdir(), but fills in .d_type if it is DT_UNKNOWN */ |
| 81 |
|
| 82 |
for (;;) { |
| 83 |
struct dirent *de; |
| 84 |
|
| 85 |
errno = 0; |
| 86 |
de = readdir(d); |
| 87 |
if (!de) |
| 88 |
return NULL; |
| 89 |
|
| 90 |
r = dirent_ensure_type(dirfd(d), de); |
| 91 |
if (r >= 0) |
| 92 |
return de; |
| 93 |
if (r != -ENOENT) { |
| 94 |
errno = -r; /* We want to be compatible with readdir(), hence propagate error via errno here */ |
| 95 |
return NULL; |
| 96 |
} |
| 97 |
|
| 98 |
/* Vanished by now? Then skip immediately to next */ |
| 99 |
} |
| 100 |
} |
| 101 |
|
| 102 |
struct dirent* readdir_no_dot(DIR *d) { |
| 103 |
assert(d); |
| 104 |
|
| 105 |
for (;;) { |
| 106 |
struct dirent *de; |
| 107 |
|
| 108 |
de = readdir_ensure_type(d); |
| 109 |
if (!de || !dot_or_dot_dot(de->d_name)) |
| 110 |
return de; |
| 111 |
} |
| 112 |
} |