repo
stringlengths 1
152
⌀ | file
stringlengths 14
221
| code
stringlengths 501
25k
| file_length
int64 501
25k
| avg_line_length
float64 20
99.5
| max_line_length
int64 21
134
| extension_type
stringclasses 2
values |
---|---|---|---|---|---|---|
null | systemd-main/src/basic/extract-word.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdarg.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <syslog.h>
#include "alloc-util.h"
#include "escape.h"
#include "extract-word.h"
#include "log.h"
#include "macro.h"
#include "string-util.h"
#include "strv.h"
#include "utf8.h"
int extract_first_word(const char **p, char **ret, const char *separators, ExtractFlags flags) {
_cleanup_free_ char *s = NULL;
size_t sz = 0;
char quote = 0; /* 0 or ' or " */
bool backslash = false; /* whether we've just seen a backslash */
char c;
int r;
assert(p);
assert(ret);
assert(!FLAGS_SET(flags, EXTRACT_KEEP_QUOTE | EXTRACT_UNQUOTE));
/* Bail early if called after last value or with no input */
if (!*p)
goto finish;
c = **p;
if (!separators)
separators = WHITESPACE;
/* Parses the first word of a string, and returns it in
* *ret. Removes all quotes in the process. When parsing fails
* (because of an uneven number of quotes or similar), leaves
* the pointer *p at the first invalid character. */
if (flags & EXTRACT_DONT_COALESCE_SEPARATORS)
if (!GREEDY_REALLOC(s, sz+1))
return -ENOMEM;
for (;; (*p)++, c = **p) {
if (c == 0)
goto finish_force_terminate;
else if (strchr(separators, c)) {
if (flags & EXTRACT_DONT_COALESCE_SEPARATORS) {
if (!(flags & EXTRACT_RETAIN_SEPARATORS))
(*p)++;
goto finish_force_next;
}
} else {
/* We found a non-blank character, so we will always
* want to return a string (even if it is empty),
* allocate it here. */
if (!GREEDY_REALLOC(s, sz+1))
return -ENOMEM;
break;
}
}
for (;; (*p)++, c = **p) {
if (backslash) {
if (!GREEDY_REALLOC(s, sz+7))
return -ENOMEM;
if (c == 0) {
if ((flags & EXTRACT_UNESCAPE_RELAX) &&
(quote == 0 || flags & EXTRACT_RELAX)) {
/* If we find an unquoted trailing backslash and we're in
* EXTRACT_UNESCAPE_RELAX mode, keep it verbatim in the
* output.
*
* Unbalanced quotes will only be allowed in EXTRACT_RELAX
* mode, EXTRACT_UNESCAPE_RELAX mode does not allow them.
*/
s[sz++] = '\\';
goto finish_force_terminate;
}
if (flags & EXTRACT_RELAX)
goto finish_force_terminate;
return -EINVAL;
}
if (flags & (EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS)) {
bool eight_bit = false;
char32_t u;
if ((flags & EXTRACT_CUNESCAPE) &&
(r = cunescape_one(*p, SIZE_MAX, &u, &eight_bit, false)) >= 0) {
/* A valid escaped sequence */
assert(r >= 1);
(*p) += r - 1;
if (eight_bit)
s[sz++] = u;
else
sz += utf8_encode_unichar(s + sz, u);
} else if ((flags & EXTRACT_UNESCAPE_SEPARATORS) &&
(strchr(separators, **p) || **p == '\\'))
/* An escaped separator char or the escape char itself */
s[sz++] = c;
else if (flags & EXTRACT_UNESCAPE_RELAX) {
s[sz++] = '\\';
s[sz++] = c;
} else
return -EINVAL;
} else
s[sz++] = c;
backslash = false;
} else if (quote != 0) { /* inside either single or double quotes */
for (;; (*p)++, c = **p) {
if (c == 0) {
if (flags & EXTRACT_RELAX)
goto finish_force_terminate;
return -EINVAL;
} else if (c == quote) { /* found the end quote */
quote = 0;
if (flags & EXTRACT_UNQUOTE)
break;
} else if (c == '\\' && !(flags & EXTRACT_RETAIN_ESCAPE)) {
backslash = true;
break;
}
if (!GREEDY_REALLOC(s, sz+2))
return -ENOMEM;
s[sz++] = c;
if (quote == 0)
break;
}
} else {
for (;; (*p)++, c = **p) {
if (c == 0)
goto finish_force_terminate;
else if (IN_SET(c, '\'', '"') && (flags & (EXTRACT_KEEP_QUOTE | EXTRACT_UNQUOTE))) {
quote = c;
if (flags & EXTRACT_UNQUOTE)
break;
} else if (c == '\\' && !(flags & EXTRACT_RETAIN_ESCAPE)) {
backslash = true;
break;
} else if (strchr(separators, c)) {
if (flags & EXTRACT_DONT_COALESCE_SEPARATORS) {
if (!(flags & EXTRACT_RETAIN_SEPARATORS))
(*p)++;
goto finish_force_next;
}
if (!(flags & EXTRACT_RETAIN_SEPARATORS))
/* Skip additional coalesced separators. */
for (;; (*p)++, c = **p) {
if (c == 0)
goto finish_force_terminate;
if (!strchr(separators, c))
break;
}
goto finish;
}
if (!GREEDY_REALLOC(s, sz+2))
return -ENOMEM;
s[sz++] = c;
if (quote != 0)
break;
}
}
}
finish_force_terminate:
*p = NULL;
finish:
if (!s) {
*p = NULL;
*ret = NULL;
return 0;
}
finish_force_next:
s[sz] = 0;
*ret = TAKE_PTR(s);
return 1;
}
int extract_first_word_and_warn(
const char **p,
char **ret,
const char *separators,
ExtractFlags flags,
const char *unit,
const char *filename,
unsigned line,
const char *rvalue) {
/* Try to unquote it, if it fails, warn about it and try again
* but this time using EXTRACT_UNESCAPE_RELAX to keep the
* backslashes verbatim in invalid escape sequences. */
const char *save;
int r;
save = *p;
r = extract_first_word(p, ret, separators, flags);
if (r >= 0)
return r;
if (r == -EINVAL && !(flags & EXTRACT_UNESCAPE_RELAX)) {
/* Retry it with EXTRACT_UNESCAPE_RELAX. */
*p = save;
r = extract_first_word(p, ret, separators, flags|EXTRACT_UNESCAPE_RELAX);
if (r >= 0) {
/* It worked this time, hence it must have been an invalid escape sequence. */
log_syntax(unit, LOG_WARNING, filename, line, EINVAL, "Ignoring unknown escape sequences: \"%s\"", *ret);
return r;
}
/* If it's still EINVAL; then it must be unbalanced quoting, report this. */
if (r == -EINVAL)
return log_syntax(unit, LOG_ERR, filename, line, r, "Unbalanced quoting, ignoring: \"%s\"", rvalue);
}
/* Can be any error, report it */
return log_syntax(unit, LOG_ERR, filename, line, r, "Unable to decode word \"%s\", ignoring: %m", rvalue);
}
/* We pass ExtractFlags as unsigned int (to avoid undefined behaviour when passing
* an object that undergoes default argument promotion as an argument to va_start).
* Let's make sure that ExtractFlags fits into an unsigned int. */
assert_cc(sizeof(enum ExtractFlags) <= sizeof(unsigned));
int extract_many_words(const char **p, const char *separators, unsigned flags, ...) {
va_list ap;
char **l;
int n = 0, i, c, r;
/* Parses a number of words from a string, stripping any
* quotes if necessary. */
assert(p);
/* Count how many words are expected */
va_start(ap, flags);
for (;;) {
if (!va_arg(ap, char **))
break;
n++;
}
va_end(ap);
if (n <= 0)
return 0;
/* Read all words into a temporary array */
l = newa0(char*, n);
for (c = 0; c < n; c++) {
r = extract_first_word(p, &l[c], separators, flags);
if (r < 0) {
int j;
for (j = 0; j < c; j++)
free(l[j]);
return r;
}
if (r == 0)
break;
}
/* If we managed to parse all words, return them in the passed
* in parameters */
va_start(ap, flags);
for (i = 0; i < n; i++) {
char **v;
v = va_arg(ap, char **);
assert(v);
*v = l[i];
}
va_end(ap);
return c;
}
| 11,832 | 38.182119 | 129 | c |
null | systemd-main/src/basic/fd-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <dirent.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdio.h>
#include <sys/socket.h>
#include "macro.h"
#include "stdio-util.h"
/* maximum length of fdname */
#define FDNAME_MAX 255
/* Make sure we can distinguish fd 0 and NULL */
#define FD_TO_PTR(fd) INT_TO_PTR((fd)+1)
#define PTR_TO_FD(p) (PTR_TO_INT(p)-1)
#define PIPE_EBADF { -EBADF, -EBADF }
int close_nointr(int fd);
int safe_close(int fd);
void safe_close_pair(int p[static 2]);
static inline int safe_close_above_stdio(int fd) {
if (fd < 3) /* Don't close stdin/stdout/stderr, but still invalidate the fd by returning -EBADF. */
return -EBADF;
return safe_close(fd);
}
void close_many(const int fds[], size_t n_fd);
int fclose_nointr(FILE *f);
FILE* safe_fclose(FILE *f);
DIR* safe_closedir(DIR *f);
static inline void closep(int *fd) {
safe_close(*fd);
}
static inline void close_pairp(int (*p)[2]) {
safe_close_pair(*p);
}
static inline void fclosep(FILE **f) {
safe_fclose(*f);
}
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(FILE*, pclose, NULL);
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(DIR*, closedir, NULL);
#define _cleanup_close_ _cleanup_(closep)
#define _cleanup_fclose_ _cleanup_(fclosep)
#define _cleanup_pclose_ _cleanup_(pclosep)
#define _cleanup_closedir_ _cleanup_(closedirp)
#define _cleanup_close_pair_ _cleanup_(close_pairp)
int fd_nonblock(int fd, bool nonblock);
int fd_cloexec(int fd, bool cloexec);
int fd_cloexec_many(const int fds[], size_t n_fds, bool cloexec);
int get_max_fd(void);
int close_all_fds(const int except[], size_t n_except);
int close_all_fds_without_malloc(const int except[], size_t n_except);
int same_fd(int a, int b);
void cmsg_close_all(struct msghdr *mh);
bool fdname_is_valid(const char *s);
int fd_get_path(int fd, char **ret);
int move_fd(int from, int to, int cloexec);
int fd_move_above_stdio(int fd);
int rearrange_stdio(int original_input_fd, int original_output_fd, int original_error_fd);
static inline int make_null_stdio(void) {
return rearrange_stdio(-EBADF, -EBADF, -EBADF);
}
/* Like TAKE_PTR() but for file descriptors, resetting them to -EBADF */
#define TAKE_FD(fd) TAKE_GENERIC(fd, int, -EBADF)
/* Like free_and_replace(), but for file descriptors */
#define close_and_replace(a, b) \
({ \
int *_fdp_ = &(a); \
safe_close(*_fdp_); \
*_fdp_ = TAKE_FD(b); \
0; \
})
int fd_reopen(int fd, int flags);
int fd_reopen_condition(int fd, int flags, int mask, int *ret_new_fd);
int fd_is_opath(int fd);
int read_nr_open(void);
int fd_get_diskseq(int fd, uint64_t *ret);
int path_is_root_at(int dir_fd, const char *path);
static inline int dir_fd_is_root(int dir_fd) {
return path_is_root_at(dir_fd, NULL);
}
static inline int dir_fd_is_root_or_cwd(int dir_fd) {
return dir_fd == AT_FDCWD ? true : path_is_root_at(dir_fd, NULL);
}
/* The maximum length a buffer for a /proc/self/fd/<fd> path needs */
#define PROC_FD_PATH_MAX \
(STRLEN("/proc/self/fd/") + DECIMAL_STR_MAX(int))
static inline char *format_proc_fd_path(char buf[static PROC_FD_PATH_MAX], int fd) {
assert(buf);
assert(fd >= 0);
assert_se(snprintf_ok(buf, PROC_FD_PATH_MAX, "/proc/self/fd/%i", fd));
return buf;
}
#define FORMAT_PROC_FD_PATH(fd) \
format_proc_fd_path((char[PROC_FD_PATH_MAX]) {}, (fd))
const char *accmode_to_string(int flags);
/* Like ASSERT_PTR, but for fds */
#define ASSERT_FD(fd) \
({ \
int _fd_ = (fd); \
assert(_fd_ >= 0); \
_fd_; \
})
| 3,941 | 28.2 | 107 | h |
null | systemd-main/src/basic/filesystems.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "filesystems-gperf.h"
#include "stat-util.h"
const char *fs_type_to_string(statfs_f_type_t magic) {
switch (magic) {
#include "filesystem-switch-case.h"
}
return NULL;
}
int fs_type_from_string(const char *name, const statfs_f_type_t **ret) {
const struct FilesystemMagic *fs_magic;
assert(name);
assert(ret);
fs_magic = filesystems_gperf_lookup(name, strlen(name));
if (!fs_magic)
return -EINVAL;
*ret = fs_magic->magic;
return 0;
}
bool fs_in_group(const struct statfs *s, FilesystemGroups fs_group) {
int r;
NULSTR_FOREACH(fs, filesystem_sets[fs_group].value) {
const statfs_f_type_t *magic;
r = fs_type_from_string(fs, &magic);
if (r >= 0)
for (size_t i = 0; i < FILESYSTEM_MAGIC_MAX; i++) {
if (magic[i] == 0)
break;
if (is_fs_type(s, magic[i]))
return true;
}
}
return false;
}
const FilesystemSet filesystem_sets[_FILESYSTEM_SET_MAX] = {
[FILESYSTEM_SET_BASIC_API] = {
.name = "@basic-api",
.help = "Basic filesystem API",
.value =
"cgroup\0"
"cgroup2\0"
"devpts\0"
"devtmpfs\0"
"mqueue\0"
"proc\0"
"sysfs\0"
},
[FILESYSTEM_SET_ANONYMOUS] = {
.name = "@anonymous",
.help = "Anonymous inodes",
.value =
"anon_inodefs\0"
"pipefs\0"
"sockfs\0"
},
[FILESYSTEM_SET_APPLICATION] = {
.name = "@application",
.help = "Application virtual filesystems",
.value =
"autofs\0"
"fuse\0"
"overlay\0"
},
[FILESYSTEM_SET_AUXILIARY_API] = {
.name = "@auxiliary-api",
.help = "Auxiliary filesystem API",
.value =
"binfmt_misc\0"
"configfs\0"
"efivarfs\0"
"fusectl\0"
"hugetlbfs\0"
"rpc_pipefs\0"
"securityfs\0"
},
[FILESYSTEM_SET_COMMON_BLOCK] = {
.name = "@common-block",
.help = "Common block device filesystems",
.value =
"btrfs\0"
"erofs\0"
"exfat\0"
"ext4\0"
"f2fs\0"
"iso9660\0"
"ntfs3\0"
"squashfs\0"
"udf\0"
"vfat\0"
"xfs\0"
},
[FILESYSTEM_SET_HISTORICAL_BLOCK] = {
.name = "@historical-block",
.help = "Historical block device filesystems",
.value =
"ext2\0"
"ext3\0"
"minix\0"
},
[FILESYSTEM_SET_NETWORK] = {
.name = "@network",
.help = "Well-known network filesystems",
.value =
"afs\0"
"ceph\0"
"cifs\0"
"gfs\0"
"gfs2\0"
"ncp\0"
"ncpfs\0"
"nfs\0"
"nfs4\0"
"ocfs2\0"
"orangefs\0"
"pvfs2\0"
"smb3\0"
"smbfs\0"
},
[FILESYSTEM_SET_PRIVILEGED_API] = {
.name = "@privileged-api",
.help = "Privileged filesystem API",
.value =
"bpf\0"
"debugfs\0"
"pstore\0"
"tracefs\0"
},
[FILESYSTEM_SET_SECURITY] = {
.name = "@security",
.help = "Security/MAC API VFS",
.value =
"apparmorfs\0"
"selinuxfs\0"
"smackfs\0"
},
[FILESYSTEM_SET_TEMPORARY] = {
.name = "@temporary",
.help = "Temporary filesystems",
.value =
"ramfs\0"
"tmpfs\0"
},
[FILESYSTEM_SET_KNOWN] = {
.name = "@known",
.help = "All known filesystems declared in the kernel",
.value =
#include "filesystem-list.h"
},
};
const FilesystemSet *filesystem_set_find(const char *name) {
if (isempty(name) || name[0] != '@')
return NULL;
for (FilesystemGroups i = 0; i < _FILESYSTEM_SET_MAX; i++)
if (streq(filesystem_sets[i].name, name))
return filesystem_sets + i;
return NULL;
}
| 5,060 | 27.755682 | 75 | c |
null | systemd-main/src/basic/filesystems.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "nulstr-util.h"
#include "stat-util.h"
#include "string-util.h"
#define FILESYSTEM_MAGIC_MAX 10
typedef enum FilesystemGroups {
/* Please leave BASIC_API first and KNOWN last, but sort the rest alphabetically */
FILESYSTEM_SET_BASIC_API,
FILESYSTEM_SET_ANONYMOUS,
FILESYSTEM_SET_APPLICATION,
FILESYSTEM_SET_AUXILIARY_API,
FILESYSTEM_SET_COMMON_BLOCK,
FILESYSTEM_SET_HISTORICAL_BLOCK,
FILESYSTEM_SET_NETWORK,
FILESYSTEM_SET_PRIVILEGED_API,
FILESYSTEM_SET_SECURITY,
FILESYSTEM_SET_TEMPORARY,
FILESYSTEM_SET_KNOWN,
_FILESYSTEM_SET_MAX,
_FILESYSTEM_SET_INVALID = -EINVAL,
} FilesystemGroups;
typedef struct FilesystemSet {
const char *name;
const char *help;
const char *value;
} FilesystemSet;
extern const FilesystemSet filesystem_sets[];
const FilesystemSet *filesystem_set_find(const char *name);
const char *fs_type_to_string(statfs_f_type_t magic);
int fs_type_from_string(const char *name, const statfs_f_type_t **ret);
bool fs_in_group(const struct statfs *s, enum FilesystemGroups fs_group);
/* gperf prototypes */
const struct FilesystemMagic* filesystems_gperf_lookup(const char *key, GPERF_LEN_TYPE length);
| 1,331 | 29.976744 | 95 | h |
null | systemd-main/src/basic/format-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "format-util.h"
#include "memory-util.h"
#include "stdio-util.h"
#include "strxcpyx.h"
assert_cc(STRLEN("%") + DECIMAL_STR_MAX(int) <= IF_NAMESIZE);
int format_ifname_full(int ifindex, FormatIfnameFlag flag, char buf[static IF_NAMESIZE]) {
if (ifindex <= 0)
return -EINVAL;
if (if_indextoname(ifindex, buf))
return 0;
if (!FLAGS_SET(flag, FORMAT_IFNAME_IFINDEX))
return -errno;
if (FLAGS_SET(flag, FORMAT_IFNAME_IFINDEX_WITH_PERCENT))
assert(snprintf_ok(buf, IF_NAMESIZE, "%%%d", ifindex));
else
assert(snprintf_ok(buf, IF_NAMESIZE, "%d", ifindex));
return 0;
}
int format_ifname_full_alloc(int ifindex, FormatIfnameFlag flag, char **ret) {
char buf[IF_NAMESIZE], *copy;
int r;
assert(ret);
r = format_ifname_full(ifindex, flag, buf);
if (r < 0)
return r;
copy = strdup(buf);
if (!copy)
return -ENOMEM;
*ret = copy;
return 0;
}
char *format_bytes_full(char *buf, size_t l, uint64_t t, FormatBytesFlag flag) {
typedef struct {
const char *suffix;
uint64_t factor;
} suffix_table;
static const suffix_table table_iec[] = {
{ "E", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
{ "P", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
{ "T", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
{ "G", UINT64_C(1024)*UINT64_C(1024)*UINT64_C(1024) },
{ "M", UINT64_C(1024)*UINT64_C(1024) },
{ "K", UINT64_C(1024) },
}, table_si[] = {
{ "E", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) },
{ "P", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) },
{ "T", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) },
{ "G", UINT64_C(1000)*UINT64_C(1000)*UINT64_C(1000) },
{ "M", UINT64_C(1000)*UINT64_C(1000) },
{ "K", UINT64_C(1000) },
};
const suffix_table *table;
size_t n;
assert_cc(ELEMENTSOF(table_iec) == ELEMENTSOF(table_si));
if (t == UINT64_MAX)
return NULL;
table = flag & FORMAT_BYTES_USE_IEC ? table_iec : table_si;
n = ELEMENTSOF(table_iec);
for (size_t i = 0; i < n; i++)
if (t >= table[i].factor) {
if (flag & FORMAT_BYTES_BELOW_POINT) {
(void) snprintf(buf, l,
"%" PRIu64 ".%" PRIu64 "%s",
t / table[i].factor,
i != n - 1 ?
(t / table[i + 1].factor * UINT64_C(10) / table[n - 1].factor) % UINT64_C(10):
(t * UINT64_C(10) / table[i].factor) % UINT64_C(10),
table[i].suffix);
} else
(void) snprintf(buf, l,
"%" PRIu64 "%s",
t / table[i].factor,
table[i].suffix);
goto finish;
}
(void) snprintf(buf, l, "%" PRIu64 "%s", t, flag & FORMAT_BYTES_TRAILING_B ? "B" : "");
finish:
buf[l-1] = 0;
return buf;
}
| 3,839 | 36.647059 | 126 | c |
null | systemd-main/src/basic/format-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include <net/if.h>
#include <stdbool.h>
#include "cgroup-util.h"
#include "macro.h"
assert_cc(sizeof(pid_t) == sizeof(int32_t));
#define PID_PRI PRIi32
#define PID_FMT "%" PID_PRI
assert_cc(sizeof(uid_t) == sizeof(uint32_t));
#define UID_FMT "%" PRIu32
assert_cc(sizeof(gid_t) == sizeof(uint32_t));
#define GID_FMT "%" PRIu32
#if SIZEOF_TIME_T == 8
# define PRI_TIME PRIi64
#elif SIZEOF_TIME_T == 4
# define PRI_TIME "li"
#else
# error Unknown time_t size
#endif
#if SIZEOF_TIMEX_MEMBER == 8
# define PRI_TIMEX PRIi64
#elif SIZEOF_TIMEX_MEMBER == 4
# define PRI_TIMEX "li"
#else
# error Unknown timex member size
#endif
#if SIZEOF_RLIM_T == 8
# define RLIM_FMT "%" PRIu64
#elif SIZEOF_RLIM_T == 4
# define RLIM_FMT "%" PRIu32
#else
# error Unknown rlim_t size
#endif
#if SIZEOF_DEV_T == 8
# define DEV_FMT "%" PRIu64
#elif SIZEOF_DEV_T == 4
# define DEV_FMT "%" PRIu32
#else
# error Unknown dev_t size
#endif
#if SIZEOF_INO_T == 8
# define INO_FMT "%" PRIu64
#elif SIZEOF_INO_T == 4
# define INO_FMT "%" PRIu32
#else
# error Unknown ino_t size
#endif
typedef enum {
FORMAT_IFNAME_IFINDEX = 1 << 0,
FORMAT_IFNAME_IFINDEX_WITH_PERCENT = (1 << 1) | FORMAT_IFNAME_IFINDEX,
} FormatIfnameFlag;
int format_ifname_full(int ifindex, FormatIfnameFlag flag, char buf[static IF_NAMESIZE]);
int format_ifname_full_alloc(int ifindex, FormatIfnameFlag flag, char **ret);
static inline int format_ifname(int ifindex, char buf[static IF_NAMESIZE]) {
return format_ifname_full(ifindex, 0, buf);
}
static inline int format_ifname_alloc(int ifindex, char **ret) {
return format_ifname_full_alloc(ifindex, 0, ret);
}
static inline char *_format_ifname_full(int ifindex, FormatIfnameFlag flag, char buf[static IF_NAMESIZE]) {
(void) format_ifname_full(ifindex, flag, buf);
return buf;
}
#define FORMAT_IFNAME_FULL(index, flag) _format_ifname_full(index, flag, (char[IF_NAMESIZE]){})
#define FORMAT_IFNAME(index) _format_ifname_full(index, 0, (char[IF_NAMESIZE]){})
typedef enum {
FORMAT_BYTES_USE_IEC = 1 << 0,
FORMAT_BYTES_BELOW_POINT = 1 << 1,
FORMAT_BYTES_TRAILING_B = 1 << 2,
} FormatBytesFlag;
#define FORMAT_BYTES_MAX 16U
char *format_bytes_full(char *buf, size_t l, uint64_t t, FormatBytesFlag flag) _warn_unused_result_;
_warn_unused_result_
static inline char *format_bytes(char *buf, size_t l, uint64_t t) {
return format_bytes_full(buf, l, t, FORMAT_BYTES_USE_IEC | FORMAT_BYTES_BELOW_POINT | FORMAT_BYTES_TRAILING_B);
}
/* Note: the lifetime of the compound literal is the immediately surrounding block,
* see C11 §6.5.2.5, and
* https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */
#define FORMAT_BYTES(t) format_bytes((char[FORMAT_BYTES_MAX]){}, FORMAT_BYTES_MAX, t)
#define FORMAT_BYTES_FULL(t, flag) format_bytes_full((char[FORMAT_BYTES_MAX]){}, FORMAT_BYTES_MAX, t, flag)
#define FORMAT_BYTES_CGROUP_PROTECTION(t) (t == CGROUP_LIMIT_MAX ? "infinity" : FORMAT_BYTES(t))
| 3,121 | 28.45283 | 119 | h |
null | systemd-main/src/basic/fs-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <dirent.h>
#include <fcntl.h>
#include <limits.h>
#include <stdbool.h>
#include <stdint.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#include "alloc-util.h"
#include "errno-util.h"
#include "lock-util.h"
#include "time-util.h"
#include "user-util.h"
#define MODE_INVALID ((mode_t) -1)
/* The following macros add 1 when converting things, since 0 is a valid mode, while the pointer
* NULL is special */
#define PTR_TO_MODE(p) ((mode_t) ((uintptr_t) (p)-1))
#define MODE_TO_PTR(u) ((void *) ((uintptr_t) (u)+1))
int rmdir_parents(const char *path, const char *stop);
int rename_noreplace(int olddirfd, const char *oldpath, int newdirfd, const char *newpath);
int readlinkat_malloc(int fd, const char *p, char **ret);
int readlink_malloc(const char *p, char **r);
int readlink_value(const char *p, char **ret);
int readlink_and_make_absolute(const char *p, char **r);
int chmod_and_chown_at(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid);
static inline int chmod_and_chown(const char *path, mode_t mode, uid_t uid, gid_t gid) {
return chmod_and_chown_at(AT_FDCWD, path, mode, uid, gid);
}
int fchmod_and_chown_with_fallback(int fd, const char *path, mode_t mode, uid_t uid, gid_t gid);
static inline int fchmod_and_chown(int fd, mode_t mode, uid_t uid, gid_t gid) {
return fchmod_and_chown_with_fallback(fd, NULL, mode, uid, gid); /* no fallback */
}
int fchmod_umask(int fd, mode_t mode);
int fchmod_opath(int fd, mode_t m);
int futimens_opath(int fd, const struct timespec ts[2]);
int fd_warn_permissions(const char *path, int fd);
int stat_warn_permissions(const char *path, const struct stat *st);
#define laccess(path, mode) \
RET_NERRNO(faccessat(AT_FDCWD, (path), (mode), AT_SYMLINK_NOFOLLOW))
int touch_file(const char *path, bool parents, usec_t stamp, uid_t uid, gid_t gid, mode_t mode);
static inline int touch(const char *path) {
return touch_file(path, false, USEC_INFINITY, UID_INVALID, GID_INVALID, MODE_INVALID);
}
int symlink_idempotent(const char *from, const char *to, bool make_relative);
int symlinkat_atomic_full(const char *from, int atfd, const char *to, bool make_relative);
static inline int symlink_atomic(const char *from, const char *to) {
return symlinkat_atomic_full(from, AT_FDCWD, to, false);
}
int mknodat_atomic(int atfd, const char *path, mode_t mode, dev_t dev);
static inline int mknod_atomic(const char *path, mode_t mode, dev_t dev) {
return mknodat_atomic(AT_FDCWD, path, mode, dev);
}
int mkfifoat_atomic(int dir_fd, const char *path, mode_t mode);
static inline int mkfifo_atomic(const char *path, mode_t mode) {
return mkfifoat_atomic(AT_FDCWD, path, mode);
}
int get_files_in_directory(const char *path, char ***list);
int tmp_dir(const char **ret);
int var_tmp_dir(const char **ret);
int unlink_or_warn(const char *filename);
/* Useful for usage with _cleanup_(), removes a directory and frees the pointer */
static inline char *rmdir_and_free(char *p) {
PROTECT_ERRNO;
if (!p)
return NULL;
(void) rmdir(p);
return mfree(p);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(char*, rmdir_and_free);
static inline char* unlink_and_free(char *p) {
if (!p)
return NULL;
(void) unlink(p);
return mfree(p);
}
DEFINE_TRIVIAL_CLEANUP_FUNC(char*, unlink_and_free);
int access_fd(int fd, int mode);
void unlink_tempfilep(char (*p)[]);
typedef enum UnlinkDeallocateFlags {
UNLINK_REMOVEDIR = 1 << 0,
UNLINK_ERASE = 1 << 1,
} UnlinkDeallocateFlags;
int unlinkat_deallocate(int fd, const char *name, UnlinkDeallocateFlags flags);
int open_parent_at(int dir_fd, const char *path, int flags, mode_t mode);
static inline int open_parent(const char *path, int flags, mode_t mode) {
return open_parent_at(AT_FDCWD, path, flags, mode);
}
int conservative_renameat(int olddirfd, const char *oldpath, int newdirfd, const char *newpath);
static inline int conservative_rename(const char *oldpath, const char *newpath) {
return conservative_renameat(AT_FDCWD, oldpath, AT_FDCWD, newpath);
}
int posix_fallocate_loop(int fd, uint64_t offset, uint64_t size);
int parse_cifs_service(const char *s, char **ret_host, char **ret_service, char **ret_path);
int open_mkdir_at(int dirfd, const char *path, int flags, mode_t mode);
int openat_report_new(int dirfd, const char *pathname, int flags, mode_t mode, bool *ret_newly_created);
typedef enum XOpenFlags {
XO_LABEL = 1 << 0,
} XOpenFlags;
int xopenat(int dir_fd, const char *path, int open_flags, XOpenFlags xopen_flags, mode_t mode);
int xopenat_lock(int dir_fd, const char *path, int open_flags, XOpenFlags xopen_flags, mode_t mode, LockType locktype, int operation);
| 4,903 | 33.535211 | 134 | h |
null | systemd-main/src/basic/gcrypt-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#if HAVE_GCRYPT
#include "gcrypt-util.h"
#include "hexdecoct.h"
void initialize_libgcrypt(bool secmem) {
if (gcry_control(GCRYCTL_INITIALIZATION_FINISHED_P))
return;
gcry_control(GCRYCTL_SET_PREFERRED_RNG_TYPE, GCRY_RNG_TYPE_SYSTEM);
assert_se(gcry_check_version("1.4.5"));
/* Turn off "secmem". Clients which wish to make use of this
* feature should initialize the library manually */
if (!secmem)
gcry_control(GCRYCTL_DISABLE_SECMEM);
gcry_control(GCRYCTL_INITIALIZATION_FINISHED, 0);
}
# if !PREFER_OPENSSL
int string_hashsum(const char *s, size_t len, int md_algorithm, char **out) {
_cleanup_(gcry_md_closep) gcry_md_hd_t md = NULL;
gcry_error_t err;
size_t hash_size;
void *hash;
char *enc;
initialize_libgcrypt(false);
hash_size = gcry_md_get_algo_dlen(md_algorithm);
assert(hash_size > 0);
err = gcry_md_open(&md, md_algorithm, 0);
if (gcry_err_code(err) != GPG_ERR_NO_ERROR || !md)
return -EIO;
gcry_md_write(md, s, len);
hash = gcry_md_read(md, 0);
if (!hash)
return -EIO;
enc = hexmem(hash, hash_size);
if (!enc)
return -ENOMEM;
*out = enc;
return 0;
}
# endif
#endif
| 1,418 | 24.8 | 77 | c |
null | systemd-main/src/basic/gcrypt-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#if HAVE_GCRYPT
#include <gcrypt.h>
#include "macro.h"
void initialize_libgcrypt(bool secmem);
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(gcry_md_hd_t, gcry_md_close, NULL);
#endif
#if !PREFER_OPENSSL
# if HAVE_GCRYPT
int string_hashsum(const char *s, size_t len, int md_algorithm, char **out);
# endif
static inline int string_hashsum_sha224(const char *s, size_t len, char **out) {
# if HAVE_GCRYPT
return string_hashsum(s, len, GCRY_MD_SHA224, out);
# else
return -EOPNOTSUPP;
# endif
}
static inline int string_hashsum_sha256(const char *s, size_t len, char **out) {
# if HAVE_GCRYPT
return string_hashsum(s, len, GCRY_MD_SHA256, out);
# else
return -EOPNOTSUPP;
# endif
}
#endif
| 845 | 20.15 | 80 | h |
null | systemd-main/src/basic/getopt-defs.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <getopt.h>
#define SYSTEMD_GETOPT_SHORT_OPTIONS "hDbsz:"
#define COMMON_GETOPT_ARGS \
ARG_LOG_LEVEL = 0x100, \
ARG_LOG_TARGET, \
ARG_LOG_COLOR, \
ARG_LOG_LOCATION, \
ARG_LOG_TIME
#define SYSTEMD_GETOPT_ARGS \
ARG_UNIT, \
ARG_SYSTEM, \
ARG_USER, \
ARG_TEST, \
ARG_NO_PAGER, \
ARG_VERSION, \
ARG_DUMP_CONFIGURATION_ITEMS, \
ARG_DUMP_BUS_PROPERTIES, \
ARG_BUS_INTROSPECT, \
ARG_DUMP_CORE, \
ARG_CRASH_CHVT, \
ARG_CRASH_SHELL, \
ARG_CRASH_REBOOT, \
ARG_CONFIRM_SPAWN, \
ARG_SHOW_STATUS, \
ARG_DESERIALIZE, \
ARG_SWITCHED_ROOT, \
ARG_DEFAULT_STD_OUTPUT, \
ARG_DEFAULT_STD_ERROR, \
ARG_MACHINE_ID, \
ARG_SERVICE_WATCHDOGS
#define SHUTDOWN_GETOPT_ARGS \
ARG_EXIT_CODE, \
ARG_TIMEOUT
#define COMMON_GETOPT_OPTIONS \
{ "log-level", required_argument, NULL, ARG_LOG_LEVEL }, \
{ "log-target", required_argument, NULL, ARG_LOG_TARGET }, \
{ "log-color", optional_argument, NULL, ARG_LOG_COLOR }, \
{ "log-location", optional_argument, NULL, ARG_LOG_LOCATION }, \
{ "log-time", optional_argument, NULL, ARG_LOG_TIME }
#define SYSTEMD_GETOPT_OPTIONS \
{ "unit", required_argument, NULL, ARG_UNIT }, \
{ "system", no_argument, NULL, ARG_SYSTEM }, \
{ "user", no_argument, NULL, ARG_USER }, \
{ "test", no_argument, NULL, ARG_TEST }, \
{ "no-pager", no_argument, NULL, ARG_NO_PAGER }, \
{ "help", no_argument, NULL, 'h' }, \
{ "version", no_argument, NULL, ARG_VERSION }, \
{ "dump-configuration-items", no_argument, NULL, ARG_DUMP_CONFIGURATION_ITEMS }, \
{ "dump-bus-properties", no_argument, NULL, ARG_DUMP_BUS_PROPERTIES }, \
{ "bus-introspect", required_argument, NULL, ARG_BUS_INTROSPECT }, \
{ "dump-core", optional_argument, NULL, ARG_DUMP_CORE }, \
{ "crash-chvt", required_argument, NULL, ARG_CRASH_CHVT }, \
{ "crash-shell", optional_argument, NULL, ARG_CRASH_SHELL }, \
{ "crash-reboot", optional_argument, NULL, ARG_CRASH_REBOOT }, \
{ "confirm-spawn", optional_argument, NULL, ARG_CONFIRM_SPAWN }, \
{ "show-status", optional_argument, NULL, ARG_SHOW_STATUS }, \
{ "deserialize", required_argument, NULL, ARG_DESERIALIZE }, \
{ "switched-root", no_argument, NULL, ARG_SWITCHED_ROOT }, \
{ "default-standard-output", required_argument, NULL, ARG_DEFAULT_STD_OUTPUT, }, \
{ "default-standard-error", required_argument, NULL, ARG_DEFAULT_STD_ERROR, }, \
{ "machine-id", required_argument, NULL, ARG_MACHINE_ID }, \
{ "service-watchdogs", required_argument, NULL, ARG_SERVICE_WATCHDOGS }
#define SHUTDOWN_GETOPT_OPTIONS \
{ "exit-code", required_argument, NULL, ARG_EXIT_CODE }, \
{ "timeout", required_argument, NULL, ARG_TIMEOUT }
| 4,609 | 59.657895 | 96 | h |
null | systemd-main/src/basic/glob-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include "dirent-util.h"
#include "errno-util.h"
#include "glob-util.h"
#include "macro.h"
#include "path-util.h"
#include "strv.h"
static void closedir_wrapper(void* v) {
(void) closedir(v);
}
int safe_glob(const char *path, int flags, glob_t *pglob) {
int k;
/* We want to set GLOB_ALTDIRFUNC ourselves, don't allow it to be set. */
assert(!(flags & GLOB_ALTDIRFUNC));
if (!pglob->gl_closedir)
pglob->gl_closedir = closedir_wrapper;
if (!pglob->gl_readdir)
pglob->gl_readdir = (struct dirent *(*)(void *)) readdir_no_dot;
if (!pglob->gl_opendir)
pglob->gl_opendir = (void *(*)(const char *)) opendir;
if (!pglob->gl_lstat)
pglob->gl_lstat = lstat;
if (!pglob->gl_stat)
pglob->gl_stat = stat;
errno = 0;
k = glob(path, flags | GLOB_ALTDIRFUNC, NULL, pglob);
if (k == GLOB_NOMATCH)
return -ENOENT;
if (k == GLOB_NOSPACE)
return -ENOMEM;
if (k != 0)
return errno_or_else(EIO);
if (strv_isempty(pglob->gl_pathv))
return -ENOENT;
return 0;
}
int glob_first(const char *path, char **ret_first) {
_cleanup_globfree_ glob_t g = {};
int k;
assert(path);
k = safe_glob(path, GLOB_NOSORT|GLOB_BRACE, &g);
if (k == -ENOENT) {
if (ret_first)
*ret_first = NULL;
return false;
}
if (k < 0)
return k;
if (ret_first) {
char *first = strdup(g.gl_pathv[0]);
if (!first)
return log_oom_debug();
*ret_first = first;
}
return true;
}
int glob_extend(char ***strv, const char *path, int flags) {
_cleanup_globfree_ glob_t g = {};
int k;
k = safe_glob(path, GLOB_NOSORT|GLOB_BRACE|flags, &g);
if (k < 0)
return k;
return strv_extend_strv(strv, g.gl_pathv, false);
}
int glob_non_glob_prefix(const char *path, char **ret) {
/* Return the path of the path that has no glob characters. */
size_t n = strcspn(path, GLOB_CHARS);
if (path[n] != '\0')
while (n > 0 && path[n-1] != '/')
n--;
if (n == 0)
return -ENOENT;
char *ans = strndup(path, n);
if (!ans)
return -ENOMEM;
*ret = ans;
return 0;
}
| 2,712 | 25.086538 | 81 | c |
null | systemd-main/src/basic/glob-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <glob.h>
#include <stdbool.h>
#include "macro.h"
#include "string-util.h"
/* Note: this function modifies pglob to set various functions. */
int safe_glob(const char *path, int flags, glob_t *pglob);
/* Note: which match is returned depends on the implementation/system and not guaranteed to be stable */
int glob_first(const char *path, char **ret_first);
#define glob_exists(path) glob_first(path, NULL)
int glob_extend(char ***strv, const char *path, int flags);
int glob_non_glob_prefix(const char *path, char **ret);
#define _cleanup_globfree_ _cleanup_(globfree)
_pure_ static inline bool string_is_glob(const char *p) {
/* Check if a string contains any glob patterns. */
return !!strpbrk(p, GLOB_CHARS);
}
| 808 | 30.115385 | 104 | h |
null | systemd-main/src/basic/glyph-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include <stdbool.h>
#include "macro.h"
typedef enum SpecialGlyph {
SPECIAL_GLYPH_TREE_VERTICAL,
SPECIAL_GLYPH_TREE_BRANCH,
SPECIAL_GLYPH_TREE_RIGHT,
SPECIAL_GLYPH_TREE_SPACE,
SPECIAL_GLYPH_TREE_TOP,
SPECIAL_GLYPH_VERTICAL_DOTTED,
SPECIAL_GLYPH_TRIANGULAR_BULLET,
SPECIAL_GLYPH_BLACK_CIRCLE,
SPECIAL_GLYPH_WHITE_CIRCLE,
SPECIAL_GLYPH_MULTIPLICATION_SIGN,
SPECIAL_GLYPH_CIRCLE_ARROW,
SPECIAL_GLYPH_BULLET,
SPECIAL_GLYPH_MU,
SPECIAL_GLYPH_CHECK_MARK,
SPECIAL_GLYPH_CROSS_MARK,
SPECIAL_GLYPH_ARROW_LEFT,
SPECIAL_GLYPH_ARROW_RIGHT,
SPECIAL_GLYPH_ARROW_UP,
SPECIAL_GLYPH_ARROW_DOWN,
SPECIAL_GLYPH_ELLIPSIS,
SPECIAL_GLYPH_LIGHT_SHADE,
SPECIAL_GLYPH_DARK_SHADE,
SPECIAL_GLYPH_SIGMA,
SPECIAL_GLYPH_EXTERNAL_LINK,
_SPECIAL_GLYPH_FIRST_EMOJI,
SPECIAL_GLYPH_ECSTATIC_SMILEY = _SPECIAL_GLYPH_FIRST_EMOJI,
SPECIAL_GLYPH_HAPPY_SMILEY,
SPECIAL_GLYPH_SLIGHTLY_HAPPY_SMILEY,
SPECIAL_GLYPH_NEUTRAL_SMILEY,
SPECIAL_GLYPH_SLIGHTLY_UNHAPPY_SMILEY,
SPECIAL_GLYPH_UNHAPPY_SMILEY,
SPECIAL_GLYPH_DEPRESSED_SMILEY,
SPECIAL_GLYPH_LOCK_AND_KEY,
SPECIAL_GLYPH_TOUCH,
SPECIAL_GLYPH_RECYCLING,
SPECIAL_GLYPH_DOWNLOAD,
SPECIAL_GLYPH_SPARKLES,
SPECIAL_GLYPH_LOW_BATTERY,
SPECIAL_GLYPH_WARNING_SIGN,
_SPECIAL_GLYPH_MAX,
_SPECIAL_GLYPH_INVALID = -EINVAL,
} SpecialGlyph;
bool emoji_enabled(void);
const char *special_glyph_full(SpecialGlyph code, bool force_utf) _const_;
static inline const char *special_glyph(SpecialGlyph code) {
return special_glyph_full(code, false);
}
static inline const char *special_glyph_check_mark(bool b) {
return b ? special_glyph(SPECIAL_GLYPH_CHECK_MARK) : special_glyph(SPECIAL_GLYPH_CROSS_MARK);
}
static inline const char *special_glyph_check_mark_space(bool b) {
return b ? special_glyph(SPECIAL_GLYPH_CHECK_MARK) : " ";
}
| 2,165 | 30.852941 | 101 | h |
null | systemd-main/src/basic/gunicode.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
/* gunicode.c - Unicode manipulation functions
*
* Copyright (C) 1999, 2000 Tom Tromey
* Copyright © 2000, 2005 Red Hat, Inc.
*/
#include "gunicode.h"
#define unichar uint32_t
/**
* g_utf8_prev_char:
* @p: a pointer to a position within a UTF-8 encoded string
*
* Finds the previous UTF-8 character in the string before @p.
*
* @p does not have to be at the beginning of a UTF-8 character. No check
* is made to see if the character found is actually valid other than
* it starts with an appropriate byte. If @p might be the first
* character of the string, you must use g_utf8_find_prev_char() instead.
*
* Return value: a pointer to the found character.
**/
char *
utf8_prev_char (const char *p)
{
for (;;)
{
p--;
if ((*p & 0xc0) != 0x80)
return (char *)p;
}
}
struct Interval
{
unichar start, end;
};
static int
interval_compare (const void *key, const void *elt)
{
unichar c = (unichar) (long) (key);
struct Interval *interval = (struct Interval *)elt;
if (c < interval->start)
return -1;
if (c > interval->end)
return +1;
return 0;
}
/*
* NOTE:
*
* The tables for g_unichar_iswide() and g_unichar_iswide_cjk() are
* generated from the Unicode Character Database's file
* extracted/DerivedEastAsianWidth.txt using the gen-iswide-table.py
* in this way:
*
* ./gen-iswide-table.py < path/to/ucd/extracted/DerivedEastAsianWidth.txt | fmt
*
* Last update for Unicode 6.0.
*/
/**
* g_unichar_iswide:
* @c: a Unicode character
*
* Determines if a character is typically rendered in a double-width
* cell.
*
* Return value: %TRUE if the character is wide
**/
bool
unichar_iswide (unichar c)
{
/* See NOTE earlier for how to update this table. */
static const struct Interval wide[] = {
{0x1100, 0x115F}, {0x2329, 0x232A}, {0x2E80, 0x2E99}, {0x2E9B, 0x2EF3},
{0x2F00, 0x2FD5}, {0x2FF0, 0x2FFB}, {0x3000, 0x303E}, {0x3041, 0x3096},
{0x3099, 0x30FF}, {0x3105, 0x312D}, {0x3131, 0x318E}, {0x3190, 0x31BA},
{0x31C0, 0x31E3}, {0x31F0, 0x321E}, {0x3220, 0x3247}, {0x3250, 0x32FE},
{0x3300, 0x4DBF}, {0x4E00, 0xA48C}, {0xA490, 0xA4C6}, {0xA960, 0xA97C},
{0xAC00, 0xD7A3}, {0xF900, 0xFAFF}, {0xFE10, 0xFE19}, {0xFE30, 0xFE52},
{0xFE54, 0xFE66}, {0xFE68, 0xFE6B}, {0xFF01, 0xFF60}, {0xFFE0, 0xFFE6},
{0x1B000, 0x1B001}, {0x1F200, 0x1F202}, {0x1F210, 0x1F23A},
{0x1F240, 0x1F248}, {0x1F250, 0x1F251},
{0x1F300, 0x1F567}, /* Miscellaneous Symbols and Pictographs */
{0x20000, 0x2FFFD}, {0x30000, 0x3FFFD},
};
if (bsearch ((void *)(uintptr_t)c, wide, (sizeof (wide) / sizeof ((wide)[0])), sizeof wide[0],
interval_compare))
return true;
return false;
}
const char utf8_skip_data[256] = {
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,5,5,5,5,6,6,1,1
};
| 3,333 | 28.767857 | 96 | c |
null | systemd-main/src/basic/gunicode.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
/* gunicode.h - Unicode manipulation functions
*
* Copyright (C) 1999, 2000 Tom Tromey
* Copyright © 2000, 2005 Red Hat, Inc.
*/
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
char *utf8_prev_char (const char *p);
extern const char utf8_skip_data[256];
/**
* g_utf8_next_char:
* @p: Pointer to the start of a valid UTF-8 character
*
* Skips to the next character in a UTF-8 string. The string must be
* valid; this macro is as fast as possible, and has no error-checking.
* You would use this macro to iterate over a string character by
* character. The macro returns the start of the next UTF-8 character.
* Before using this macro, use g_utf8_validate() to validate strings
* that may contain invalid UTF-8.
*/
#define utf8_next_char(p) (char *)((p) + utf8_skip_data[*(const unsigned char *)(p)])
bool unichar_iswide (uint32_t c);
| 930 | 29.032258 | 85 | h |
null | systemd-main/src/basic/hash-funcs.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <string.h>
#include "hash-funcs.h"
#include "path-util.h"
#include "strv.h"
void string_hash_func(const char *p, struct siphash *state) {
siphash24_compress(p, strlen(p) + 1, state);
}
DEFINE_HASH_OPS(string_hash_ops, char, string_hash_func, string_compare_func);
DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(string_hash_ops_free,
char, string_hash_func, string_compare_func, free);
DEFINE_HASH_OPS_FULL(string_hash_ops_free_free,
char, string_hash_func, string_compare_func, free,
void, free);
DEFINE_HASH_OPS_FULL(string_hash_ops_free_strv_free,
char, string_hash_func, string_compare_func, free,
char*, strv_free);
void path_hash_func(const char *q, struct siphash *state) {
bool add_slash = false;
assert(q);
assert(state);
/* Calculates a hash for a path in a way this duplicate inner slashes don't make a differences, and also
* whether there's a trailing slash or not. This fits well with the semantics of path_compare(), which does
* similar checks and also doesn't care for trailing slashes. Note that relative and absolute paths (i.e. those
* which begin in a slash or not) will hash differently though. */
/* if path is absolute, add one "/" to the hash. */
if (path_is_absolute(q))
siphash24_compress("/", 1, state);
for (;;) {
const char *e;
int r;
r = path_find_first_component(&q, true, &e);
if (r == 0)
return;
if (add_slash)
siphash24_compress_byte('/', state);
if (r < 0) {
/* if a component is invalid, then add remaining part as a string. */
string_hash_func(q, state);
return;
}
/* Add this component to the hash. */
siphash24_compress(e, r, state);
add_slash = true;
}
}
DEFINE_HASH_OPS(path_hash_ops, char, path_hash_func, path_compare);
DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(path_hash_ops_free,
char, path_hash_func, path_compare, free);
DEFINE_HASH_OPS_FULL(path_hash_ops_free_free,
char, path_hash_func, path_compare, free,
void, free);
void trivial_hash_func(const void *p, struct siphash *state) {
siphash24_compress(&p, sizeof(p), state);
}
int trivial_compare_func(const void *a, const void *b) {
return CMP(a, b);
}
const struct hash_ops trivial_hash_ops = {
.hash = trivial_hash_func,
.compare = trivial_compare_func,
};
const struct hash_ops trivial_hash_ops_free = {
.hash = trivial_hash_func,
.compare = trivial_compare_func,
.free_key = free,
};
const struct hash_ops trivial_hash_ops_free_free = {
.hash = trivial_hash_func,
.compare = trivial_compare_func,
.free_key = free,
.free_value = free,
};
void uint64_hash_func(const uint64_t *p, struct siphash *state) {
siphash24_compress(p, sizeof(uint64_t), state);
}
int uint64_compare_func(const uint64_t *a, const uint64_t *b) {
return CMP(*a, *b);
}
DEFINE_HASH_OPS(uint64_hash_ops, uint64_t, uint64_hash_func, uint64_compare_func);
#if SIZEOF_DEV_T != 8
void devt_hash_func(const dev_t *p, struct siphash *state) {
siphash24_compress(p, sizeof(dev_t), state);
}
#endif
int devt_compare_func(const dev_t *a, const dev_t *b) {
int r;
r = CMP(major(*a), major(*b));
if (r != 0)
return r;
return CMP(minor(*a), minor(*b));
}
DEFINE_HASH_OPS(devt_hash_ops, dev_t, devt_hash_func, devt_compare_func);
| 3,912 | 31.07377 | 119 | c |
null | systemd-main/src/basic/hash-funcs.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "alloc-util.h"
#include "macro.h"
#include "siphash24.h"
typedef void (*hash_func_t)(const void *p, struct siphash *state);
typedef int (*compare_func_t)(const void *a, const void *b);
struct hash_ops {
hash_func_t hash;
compare_func_t compare;
free_func_t free_key;
free_func_t free_value;
};
#define _DEFINE_HASH_OPS(uq, name, type, hash_func, compare_func, free_key_func, free_value_func, scope) \
_unused_ static void (* UNIQ_T(static_hash_wrapper, uq))(const type *, struct siphash *) = hash_func; \
_unused_ static int (* UNIQ_T(static_compare_wrapper, uq))(const type *, const type *) = compare_func; \
scope const struct hash_ops name = { \
.hash = (hash_func_t) hash_func, \
.compare = (compare_func_t) compare_func, \
.free_key = free_key_func, \
.free_value = free_value_func, \
}
#define _DEFINE_FREE_FUNC(uq, type, wrapper_name, func) \
/* Type-safe free function */ \
static void UNIQ_T(wrapper_name, uq)(void *a) { \
type *_a = a; \
func(_a); \
}
#define _DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(uq, name, type, hash_func, compare_func, free_func, scope) \
_DEFINE_FREE_FUNC(uq, type, static_free_wrapper, free_func); \
_DEFINE_HASH_OPS(uq, name, type, hash_func, compare_func, \
UNIQ_T(static_free_wrapper, uq), NULL, scope)
#define _DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(uq, name, type, hash_func, compare_func, type_value, free_func, scope) \
_DEFINE_FREE_FUNC(uq, type_value, static_free_wrapper, free_func); \
_DEFINE_HASH_OPS(uq, name, type, hash_func, compare_func, \
NULL, UNIQ_T(static_free_wrapper, uq), scope)
#define _DEFINE_HASH_OPS_FULL(uq, name, type, hash_func, compare_func, free_key_func, type_value, free_value_func, scope) \
_DEFINE_FREE_FUNC(uq, type, static_free_key_wrapper, free_key_func); \
_DEFINE_FREE_FUNC(uq, type_value, static_free_value_wrapper, free_value_func); \
_DEFINE_HASH_OPS(uq, name, type, hash_func, compare_func, \
UNIQ_T(static_free_key_wrapper, uq), \
UNIQ_T(static_free_value_wrapper, uq), scope)
#define DEFINE_HASH_OPS(name, type, hash_func, compare_func) \
_DEFINE_HASH_OPS(UNIQ, name, type, hash_func, compare_func, NULL, NULL,)
#define DEFINE_PRIVATE_HASH_OPS(name, type, hash_func, compare_func) \
_DEFINE_HASH_OPS(UNIQ, name, type, hash_func, compare_func, NULL, NULL, static)
#define DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(name, type, hash_func, compare_func, free_func) \
_DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(UNIQ, name, type, hash_func, compare_func, free_func,)
#define DEFINE_PRIVATE_HASH_OPS_WITH_KEY_DESTRUCTOR(name, type, hash_func, compare_func, free_func) \
_DEFINE_HASH_OPS_WITH_KEY_DESTRUCTOR(UNIQ, name, type, hash_func, compare_func, free_func, static)
#define DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(name, type, hash_func, compare_func, value_type, free_func) \
_DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(UNIQ, name, type, hash_func, compare_func, value_type, free_func,)
#define DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(name, type, hash_func, compare_func, value_type, free_func) \
_DEFINE_HASH_OPS_WITH_VALUE_DESTRUCTOR(UNIQ, name, type, hash_func, compare_func, value_type, free_func, static)
#define DEFINE_HASH_OPS_FULL(name, type, hash_func, compare_func, free_key_func, value_type, free_value_func) \
_DEFINE_HASH_OPS_FULL(UNIQ, name, type, hash_func, compare_func, free_key_func, value_type, free_value_func,)
#define DEFINE_PRIVATE_HASH_OPS_FULL(name, type, hash_func, compare_func, free_key_func, value_type, free_value_func) \
_DEFINE_HASH_OPS_FULL(UNIQ, name, type, hash_func, compare_func, free_key_func, value_type, free_value_func, static)
void string_hash_func(const char *p, struct siphash *state);
#define string_compare_func strcmp
extern const struct hash_ops string_hash_ops;
extern const struct hash_ops string_hash_ops_free;
extern const struct hash_ops string_hash_ops_free_free;
extern const struct hash_ops string_hash_ops_free_strv_free;
void path_hash_func(const char *p, struct siphash *state);
extern const struct hash_ops path_hash_ops;
extern const struct hash_ops path_hash_ops_free;
extern const struct hash_ops path_hash_ops_free_free;
/* This will compare the passed pointers directly, and will not dereference them. This is hence not useful for strings
* or suchlike. */
void trivial_hash_func(const void *p, struct siphash *state);
int trivial_compare_func(const void *a, const void *b) _const_;
extern const struct hash_ops trivial_hash_ops;
extern const struct hash_ops trivial_hash_ops_free;
extern const struct hash_ops trivial_hash_ops_free_free;
/* 32-bit values we can always just embed in the pointer itself, but in order to support 32-bit archs we need store 64-bit
* values indirectly, since they don't fit in a pointer. */
void uint64_hash_func(const uint64_t *p, struct siphash *state);
int uint64_compare_func(const uint64_t *a, const uint64_t *b) _pure_;
extern const struct hash_ops uint64_hash_ops;
/* On some archs dev_t is 32-bit, and on others 64-bit. And sometimes it's 64-bit on 32-bit archs, and sometimes 32-bit on
* 64-bit archs. Yuck! */
#if SIZEOF_DEV_T != 8
void devt_hash_func(const dev_t *p, struct siphash *state);
#else
#define devt_hash_func uint64_hash_func
#endif
int devt_compare_func(const dev_t *a, const dev_t *b) _pure_;
extern const struct hash_ops devt_hash_ops;
| 6,033 | 52.875 | 124 | h |
null | systemd-main/src/basic/hexdecoct.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdio.h>
#include <sys/types.h>
#include "macro.h"
char octchar(int x) _const_;
int unoctchar(char c) _const_;
char decchar(int x) _const_;
int undecchar(char c) _const_;
char hexchar(int x) _const_;
int unhexchar(char c) _const_;
char *hexmem(const void *p, size_t l);
int unhexmem_full(const char *p, size_t l, bool secure, void **mem, size_t *len);
static inline int unhexmem(const char *p, size_t l, void **mem, size_t *len) {
return unhexmem_full(p, l, false, mem, len);
}
char base32hexchar(int x) _const_;
int unbase32hexchar(char c) _const_;
char base64char(int x) _const_;
char urlsafe_base64char(int x) _const_;
int unbase64char(char c) _const_;
char *base32hexmem(const void *p, size_t l, bool padding);
int unbase32hexmem(const char *p, size_t l, bool padding, void **mem, size_t *len);
ssize_t base64mem_full(const void *p, size_t l, size_t line_break, char **ret);
static inline ssize_t base64mem(const void *p, size_t l, char **ret) {
return base64mem_full(p, l, SIZE_MAX, ret);
}
ssize_t base64_append(
char **prefix,
size_t plen,
const void *p,
size_t l,
size_t margin,
size_t width);
int unbase64mem_full(const char *p, size_t l, bool secure, void **mem, size_t *len);
static inline int unbase64mem(const char *p, size_t l, void **mem, size_t *len) {
return unbase64mem_full(p, l, false, mem, len);
}
void hexdump(FILE *f, const void *p, size_t s);
| 1,612 | 28.87037 | 84 | h |
null | systemd-main/src/basic/hmac.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <assert.h>
#include <string.h>
#include "hmac.h"
#include "sha256.h"
#define HMAC_BLOCK_SIZE 64
#define INNER_PADDING_BYTE 0x36
#define OUTER_PADDING_BYTE 0x5c
void hmac_sha256(const void *key,
size_t key_size,
const void *input,
size_t input_size,
uint8_t res[static SHA256_DIGEST_SIZE]) {
uint8_t inner_padding[HMAC_BLOCK_SIZE] = { };
uint8_t outer_padding[HMAC_BLOCK_SIZE] = { };
uint8_t replacement_key[SHA256_DIGEST_SIZE];
struct sha256_ctx hash;
assert(key);
assert(key_size > 0);
assert(res);
/* Implement algorithm as described by FIPS 198. */
/* The key needs to be block size length or less, hash it if it's longer. */
if (key_size > HMAC_BLOCK_SIZE) {
sha256_direct(key, key_size, replacement_key);
key = replacement_key;
key_size = SHA256_DIGEST_SIZE;
}
/* First, copy the key into the padding arrays. If it's shorter than
* the block size, the arrays are already initialized to 0. */
memcpy(inner_padding, key, key_size);
memcpy(outer_padding, key, key_size);
/* Then, XOR the provided key and any padding leftovers with the fixed
* padding bytes as defined in FIPS 198. */
for (size_t i = 0; i < HMAC_BLOCK_SIZE; i++) {
inner_padding[i] ^= INNER_PADDING_BYTE;
outer_padding[i] ^= OUTER_PADDING_BYTE;
}
/* First pass: hash the inner padding array and the input. */
sha256_init_ctx(&hash);
sha256_process_bytes(inner_padding, HMAC_BLOCK_SIZE, &hash);
sha256_process_bytes(input, input_size, &hash);
sha256_finish_ctx(&hash, res);
/* Second pass: hash the outer padding array and the result of the first pass. */
sha256_init_ctx(&hash);
sha256_process_bytes(outer_padding, HMAC_BLOCK_SIZE, &hash);
sha256_process_bytes(res, SHA256_DIGEST_SIZE, &hash);
sha256_finish_ctx(&hash, res);
}
| 2,148 | 34.229508 | 89 | c |
null | systemd-main/src/basic/hostname-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/utsname.h>
#include <unistd.h>
#include "alloc-util.h"
#include "env-file.h"
#include "hostname-util.h"
#include "os-util.h"
#include "string-util.h"
#include "strv.h"
char* get_default_hostname(void) {
int r;
const char *e = secure_getenv("SYSTEMD_DEFAULT_HOSTNAME");
if (e) {
if (hostname_is_valid(e, 0))
return strdup(e);
log_debug("Invalid hostname in $SYSTEMD_DEFAULT_HOSTNAME, ignoring: %s", e);
}
_cleanup_free_ char *f = NULL;
r = parse_os_release(NULL, "DEFAULT_HOSTNAME", &f);
if (r < 0)
log_debug_errno(r, "Failed to parse os-release, ignoring: %m");
else if (f) {
if (hostname_is_valid(f, 0))
return TAKE_PTR(f);
log_debug("Invalid hostname in os-release, ignoring: %s", f);
}
return strdup(FALLBACK_HOSTNAME);
}
int gethostname_full(GetHostnameFlags flags, char **ret) {
_cleanup_free_ char *buf = NULL, *fallback = NULL;
struct utsname u;
const char *s;
assert(ret);
assert_se(uname(&u) >= 0);
s = u.nodename;
if (isempty(s) || streq(s, "(none)") ||
(!FLAGS_SET(flags, GET_HOSTNAME_ALLOW_LOCALHOST) && is_localhost(s)) ||
(FLAGS_SET(flags, GET_HOSTNAME_SHORT) && s[0] == '.')) {
if (!FLAGS_SET(flags, GET_HOSTNAME_FALLBACK_DEFAULT))
return -ENXIO;
s = fallback = get_default_hostname();
if (!s)
return -ENOMEM;
if (FLAGS_SET(flags, GET_HOSTNAME_SHORT) && s[0] == '.')
return -ENXIO;
}
if (FLAGS_SET(flags, GET_HOSTNAME_SHORT))
buf = strdupcspn(s, ".");
else
buf = strdup(s);
if (!buf)
return -ENOMEM;
*ret = TAKE_PTR(buf);
return 0;
}
bool valid_ldh_char(char c) {
/* "LDH" → "Letters, digits, hyphens", as per RFC 5890, Section 2.3.1 */
return ascii_isalpha(c) ||
ascii_isdigit(c) ||
c == '-';
}
bool hostname_is_valid(const char *s, ValidHostnameFlags flags) {
unsigned n_dots = 0;
const char *p;
bool dot, hyphen;
/* Check if s looks like a valid hostname or FQDN. This does not do full DNS validation, but only
* checks if the name is composed of allowed characters and the length is not above the maximum
* allowed by Linux (c.f. dns_name_is_valid()). A trailing dot is allowed if
* VALID_HOSTNAME_TRAILING_DOT flag is set and at least two components are present in the name. Note
* that due to the restricted charset and length this call is substantially more conservative than
* dns_name_is_valid(). Doesn't accept empty hostnames, hostnames with leading dots, and hostnames
* with multiple dots in a sequence. Doesn't allow hyphens at the beginning or end of label. */
if (isempty(s))
return false;
if (streq(s, ".host")) /* Used by the container logic to denote the "root container" */
return FLAGS_SET(flags, VALID_HOSTNAME_DOT_HOST);
for (p = s, dot = hyphen = true; *p; p++)
if (*p == '.') {
if (dot || hyphen)
return false;
dot = true;
hyphen = false;
n_dots++;
} else if (*p == '-') {
if (dot)
return false;
dot = false;
hyphen = true;
} else {
if (!valid_ldh_char(*p))
return false;
dot = false;
hyphen = false;
}
if (dot && (n_dots < 2 || !FLAGS_SET(flags, VALID_HOSTNAME_TRAILING_DOT)))
return false;
if (hyphen)
return false;
if (p-s > HOST_NAME_MAX) /* Note that HOST_NAME_MAX is 64 on Linux, but DNS allows domain names up to
* 255 characters */
return false;
return true;
}
char* hostname_cleanup(char *s) {
char *p, *d;
bool dot, hyphen;
assert(s);
for (p = s, d = s, dot = hyphen = true; *p && d - s < HOST_NAME_MAX; p++)
if (*p == '.') {
if (dot || hyphen)
continue;
*(d++) = '.';
dot = true;
hyphen = false;
} else if (*p == '-') {
if (dot)
continue;
*(d++) = '-';
dot = false;
hyphen = true;
} else if (valid_ldh_char(*p)) {
*(d++) = *p;
dot = false;
hyphen = false;
}
if (d > s && IN_SET(d[-1], '-', '.'))
/* The dot can occur at most once, but we might have multiple
* hyphens, hence the loop */
d--;
*d = 0;
return s;
}
bool is_localhost(const char *hostname) {
assert(hostname);
/* This tries to identify local host and domain names
* described in RFC6761 plus the redhatism of localdomain */
return STRCASE_IN_SET(
hostname,
"localhost",
"localhost.",
"localhost.localdomain",
"localhost.localdomain.") ||
endswith_no_case(hostname, ".localhost") ||
endswith_no_case(hostname, ".localhost.") ||
endswith_no_case(hostname, ".localhost.localdomain") ||
endswith_no_case(hostname, ".localhost.localdomain.");
}
int get_pretty_hostname(char **ret) {
_cleanup_free_ char *n = NULL;
int r;
assert(ret);
r = parse_env_file(NULL, "/etc/machine-info", "PRETTY_HOSTNAME", &n);
if (r < 0)
return r;
if (isempty(n))
return -ENXIO;
*ret = TAKE_PTR(n);
return 0;
}
| 6,617 | 30.514286 | 109 | c |
null | systemd-main/src/basic/hostname-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stdio.h>
#include "macro.h"
#include "strv.h"
typedef enum GetHostnameFlags {
GET_HOSTNAME_ALLOW_LOCALHOST = 1 << 0, /* accepts "localhost" or friends. */
GET_HOSTNAME_FALLBACK_DEFAULT = 1 << 1, /* use default hostname if no hostname is set. */
GET_HOSTNAME_SHORT = 1 << 2, /* kills the FQDN part if present. */
} GetHostnameFlags;
int gethostname_full(GetHostnameFlags flags, char **ret);
static inline int gethostname_strict(char **ret) {
return gethostname_full(0, ret);
}
static inline char* gethostname_malloc(void) {
char *s;
if (gethostname_full(GET_HOSTNAME_ALLOW_LOCALHOST | GET_HOSTNAME_FALLBACK_DEFAULT, &s) < 0)
return NULL;
return s;
}
static inline char* gethostname_short_malloc(void) {
char *s;
if (gethostname_full(GET_HOSTNAME_ALLOW_LOCALHOST | GET_HOSTNAME_FALLBACK_DEFAULT | GET_HOSTNAME_SHORT, &s) < 0)
return NULL;
return s;
}
char* get_default_hostname(void);
bool valid_ldh_char(char c) _const_;
typedef enum ValidHostnameFlags {
VALID_HOSTNAME_TRAILING_DOT = 1 << 0, /* Accept trailing dot on multi-label names */
VALID_HOSTNAME_DOT_HOST = 1 << 1, /* Accept ".host" as valid hostname */
} ValidHostnameFlags;
bool hostname_is_valid(const char *s, ValidHostnameFlags flags) _pure_;
char* hostname_cleanup(char *s);
bool is_localhost(const char *hostname);
static inline bool is_gateway_hostname(const char *hostname) {
/* This tries to identify the valid syntaxes for the our synthetic "gateway" host. */
return STRCASE_IN_SET(hostname, "_gateway", "_gateway.");
}
static inline bool is_outbound_hostname(const char *hostname) {
/* This tries to identify the valid syntaxes for the our synthetic "outbound" host. */
return STRCASE_IN_SET(hostname, "_outbound", "_outbound.");
}
static inline bool is_dns_stub_hostname(const char *hostname) {
return STRCASE_IN_SET(hostname, "_localdnsstub", "_localdnsstub.");
}
static inline bool is_dns_proxy_stub_hostname(const char *hostname) {
return STRCASE_IN_SET(hostname, "_localdnsproxy", "_localdnsproxy.");
}
int get_pretty_hostname(char **ret);
| 2,324 | 31.291667 | 120 | h |
null | systemd-main/src/basic/initrd-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <unistd.h>
#include "env-util.h"
#include "errno-util.h"
#include "initrd-util.h"
#include "parse-util.h"
#include "stat-util.h"
#include "string-util.h"
static int saved_in_initrd = -1;
bool in_initrd(void) {
int r;
if (saved_in_initrd >= 0)
return saved_in_initrd;
/* If /etc/initrd-release exists, we're in an initrd.
* This can be overridden by setting SYSTEMD_IN_INITRD=0|1.
*/
r = getenv_bool_secure("SYSTEMD_IN_INITRD");
if (r < 0 && r != -ENXIO)
log_debug_errno(r, "Failed to parse $SYSTEMD_IN_INITRD, ignoring: %m");
if (r >= 0)
saved_in_initrd = r > 0;
else {
r = RET_NERRNO(access("/etc/initrd-release", F_OK));
if (r < 0 && r != -ENOENT)
log_debug_errno(r, "Failed to check if /etc/initrd-release exists, assuming it does not: %m");
saved_in_initrd = r >= 0;
}
return saved_in_initrd;
}
void in_initrd_force(bool value) {
saved_in_initrd = value;
}
| 1,147 | 25.697674 | 118 | c |
null | systemd-main/src/basic/inotify-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "fd-util.h"
#include "inotify-util.h"
#include "stat-util.h"
int inotify_add_watch_fd(int fd, int what, uint32_t mask) {
int wd, r;
/* This is like inotify_add_watch(), except that the file to watch is not referenced by a path, but by an fd */
wd = inotify_add_watch(fd, FORMAT_PROC_FD_PATH(what), mask);
if (wd < 0) {
if (errno != ENOENT)
return -errno;
/* Didn't work with ENOENT? If so, then either /proc/ isn't mounted, or the fd is bad */
r = proc_mounted();
if (r == 0)
return -ENOSYS;
if (r > 0)
return -EBADF;
return -ENOENT; /* OK, no clue, let's propagate the original error */
}
return wd;
}
int inotify_add_watch_and_warn(int fd, const char *pathname, uint32_t mask) {
int wd;
wd = inotify_add_watch(fd, pathname, mask);
if (wd < 0) {
if (errno == ENOSPC)
return log_error_errno(errno, "Failed to add a watch for %s: inotify watch limit reached", pathname);
return log_error_errno(errno, "Failed to add a watch for %s: %m", pathname);
}
return wd;
}
| 1,342 | 30.97619 | 125 | c |
null | systemd-main/src/basic/inotify-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include <limits.h>
#include <stddef.h>
#include <sys/inotify.h>
#include "log.h"
#define INOTIFY_EVENT_MAX (offsetof(struct inotify_event, name) + NAME_MAX + 1)
#define _FOREACH_INOTIFY_EVENT(e, buffer, sz, log_level, start, end) \
for (struct inotify_event \
*start = &((buffer).ev), \
*end = (struct inotify_event*) ((uint8_t*) start + (sz)), \
*e = start; \
(size_t) ((uint8_t*) end - (uint8_t*) e) >= sizeof(struct inotify_event) && \
((size_t) ((uint8_t*) end - (uint8_t*) e) >= sizeof(struct inotify_event) + e->len || \
(log_full(log_level, "Received invalid inotify event, ignoring."), false)); \
e = (struct inotify_event*) ((uint8_t*) e + sizeof(struct inotify_event) + e->len))
#define _FOREACH_INOTIFY_EVENT_FULL(e, buffer, sz, log_level) \
_FOREACH_INOTIFY_EVENT(e, buffer, sz, log_level, UNIQ_T(start, UNIQ), UNIQ_T(end, UNIQ))
#define FOREACH_INOTIFY_EVENT(e, buffer, sz) \
_FOREACH_INOTIFY_EVENT_FULL(e, buffer, sz, LOG_DEBUG)
#define FOREACH_INOTIFY_EVENT_WARN(e, buffer, sz) \
_FOREACH_INOTIFY_EVENT_FULL(e, buffer, sz, LOG_WARNING)
union inotify_event_buffer {
struct inotify_event ev;
uint8_t raw[INOTIFY_EVENT_MAX];
};
int inotify_add_watch_fd(int fd, int what, uint32_t mask);
int inotify_add_watch_and_warn(int fd, const char *pathname, uint32_t mask);
| 1,683 | 42.179487 | 100 | h |
null | systemd-main/src/basic/io-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <limits.h>
#include <stdio.h>
#include <unistd.h>
#include "io-util.h"
#include "string-util.h"
#include "time-util.h"
int flush_fd(int fd) {
int count = 0;
/* Read from the specified file descriptor, until POLLIN is not set anymore, throwing away everything
* read. Note that some file descriptors (notable IP sockets) will trigger POLLIN even when no data can be read
* (due to IP packet checksum mismatches), hence this function is only safe to be non-blocking if the fd used
* was set to non-blocking too. */
for (;;) {
char buf[LINE_MAX];
ssize_t l;
int r;
r = fd_wait_for_event(fd, POLLIN, 0);
if (r < 0) {
if (r == -EINTR)
continue;
return r;
}
if (r == 0)
return count;
l = read(fd, buf, sizeof(buf));
if (l < 0) {
if (errno == EINTR)
continue;
if (errno == EAGAIN)
return count;
return -errno;
} else if (l == 0)
return count;
count += (int) l;
}
}
ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll) {
uint8_t *p = ASSERT_PTR(buf);
ssize_t n = 0;
assert(fd >= 0);
/* If called with nbytes == 0, let's call read() at least once, to validate the operation */
if (nbytes > (size_t) SSIZE_MAX)
return -EINVAL;
do {
ssize_t k;
k = read(fd, p, nbytes);
if (k < 0) {
if (errno == EINTR)
continue;
if (errno == EAGAIN && do_poll) {
/* We knowingly ignore any return value here,
* and expect that any error/EOF is reported
* via read() */
(void) fd_wait_for_event(fd, POLLIN, USEC_INFINITY);
continue;
}
return n > 0 ? n : -errno;
}
if (k == 0)
return n;
assert((size_t) k <= nbytes);
p += k;
nbytes -= k;
n += k;
} while (nbytes > 0);
return n;
}
int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll) {
ssize_t n;
n = loop_read(fd, buf, nbytes, do_poll);
if (n < 0)
return (int) n;
if ((size_t) n != nbytes)
return -EIO;
return 0;
}
int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll) {
const uint8_t *p;
assert(fd >= 0);
if (nbytes == 0) {
static const dummy_t dummy[0];
assert_cc(sizeof(dummy) == 0);
p = (const void*) dummy; /* Some valid pointer, in case NULL was specified */
} else {
assert(buf);
if (nbytes == SIZE_MAX)
nbytes = strlen(buf);
else if (_unlikely_(nbytes > (size_t) SSIZE_MAX))
return -EINVAL;
p = buf;
}
do {
ssize_t k;
k = write(fd, p, nbytes);
if (k < 0) {
if (errno == EINTR)
continue;
if (errno == EAGAIN && do_poll) {
/* We knowingly ignore any return value here,
* and expect that any error/EOF is reported
* via write() */
(void) fd_wait_for_event(fd, POLLOUT, USEC_INFINITY);
continue;
}
return -errno;
}
if (_unlikely_(nbytes > 0 && k == 0)) /* Can't really happen */
return -EIO;
assert((size_t) k <= nbytes);
p += k;
nbytes -= k;
} while (nbytes > 0);
return 0;
}
int pipe_eof(int fd) {
int r;
r = fd_wait_for_event(fd, POLLIN, 0);
if (r <= 0)
return r;
return !!(r & POLLHUP);
}
int ppoll_usec(struct pollfd *fds, size_t nfds, usec_t timeout) {
int r;
assert(fds || nfds == 0);
/* This is a wrapper around ppoll() that does primarily two things:
*
* ✅ Takes a usec_t instead of a struct timespec
*
* ✅ Guarantees that if an invalid fd is specified we return EBADF (i.e. converts POLLNVAL to
* EBADF). This is done because EBADF is a programming error usually, and hence should bubble up
* as error, and not be eaten up as non-error POLLNVAL event.
*
* ⚠️ ⚠️ ⚠️ Note that this function does not add any special handling for EINTR. Don't forget
* poll()/ppoll() will return with EINTR on any received signal always, there is no automatic
* restarting via SA_RESTART available. Thus, typically you want to handle EINTR not as an error,
* but just as reason to restart things, under the assumption you use a more appropriate mechanism
* to handle signals, such as signalfd() or signal handlers. ⚠️ ⚠️ ⚠️
*/
if (nfds == 0)
return 0;
r = ppoll(fds, nfds, timeout == USEC_INFINITY ? NULL : TIMESPEC_STORE(timeout), NULL);
if (r < 0)
return -errno;
if (r == 0)
return 0;
for (size_t i = 0, n = r; i < nfds && n > 0; i++) {
if (fds[i].revents == 0)
continue;
if (fds[i].revents & POLLNVAL)
return -EBADF;
n--;
}
return r;
}
int fd_wait_for_event(int fd, int event, usec_t timeout) {
struct pollfd pollfd = {
.fd = fd,
.events = event,
};
int r;
/* ⚠️ ⚠️ ⚠️ Keep in mind you almost certainly want to handle -EINTR gracefully in the caller, see
* ppoll_usec() above! ⚠️ ⚠️ ⚠️ */
r = ppoll_usec(&pollfd, 1, timeout);
if (r <= 0)
return r;
return pollfd.revents;
}
static size_t nul_length(const uint8_t *p, size_t sz) {
size_t n = 0;
while (sz > 0) {
if (*p != 0)
break;
n++;
p++;
sz--;
}
return n;
}
ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length) {
const uint8_t *q, *w, *e;
ssize_t l;
q = w = p;
e = q + sz;
while (q < e) {
size_t n;
n = nul_length(q, e - q);
/* If there are more than the specified run length of
* NUL bytes, or if this is the beginning or the end
* of the buffer, then seek instead of write */
if ((n > run_length) ||
(n > 0 && q == p) ||
(n > 0 && q + n >= e)) {
if (q > w) {
l = write(fd, w, q - w);
if (l < 0)
return -errno;
if (l != q -w)
return -EIO;
}
if (lseek(fd, n, SEEK_CUR) == (off_t) -1)
return -errno;
q += n;
w = q;
} else if (n > 0)
q += n;
else
q++;
}
if (q > w) {
l = write(fd, w, q - w);
if (l < 0)
return -errno;
if (l != q - w)
return -EIO;
}
return q - (const uint8_t*) p;
}
char* set_iovec_string_field(struct iovec *iovec, size_t *n_iovec, const char *field, const char *value) {
char *x;
x = strjoin(field, value);
if (x)
iovec[(*n_iovec)++] = IOVEC_MAKE_STRING(x);
return x;
}
char* set_iovec_string_field_free(struct iovec *iovec, size_t *n_iovec, const char *field, char *value) {
char *x;
x = set_iovec_string_field(iovec, n_iovec, field, value);
free(value);
return x;
}
struct iovec_wrapper *iovw_new(void) {
return malloc0(sizeof(struct iovec_wrapper));
}
void iovw_free_contents(struct iovec_wrapper *iovw, bool free_vectors) {
if (free_vectors)
for (size_t i = 0; i < iovw->count; i++)
free(iovw->iovec[i].iov_base);
iovw->iovec = mfree(iovw->iovec);
iovw->count = 0;
}
struct iovec_wrapper *iovw_free_free(struct iovec_wrapper *iovw) {
iovw_free_contents(iovw, true);
return mfree(iovw);
}
struct iovec_wrapper *iovw_free(struct iovec_wrapper *iovw) {
iovw_free_contents(iovw, false);
return mfree(iovw);
}
int iovw_put(struct iovec_wrapper *iovw, void *data, size_t len) {
if (iovw->count >= IOV_MAX)
return -E2BIG;
if (!GREEDY_REALLOC(iovw->iovec, iovw->count + 1))
return -ENOMEM;
iovw->iovec[iovw->count++] = IOVEC_MAKE(data, len);
return 0;
}
int iovw_put_string_field(struct iovec_wrapper *iovw, const char *field, const char *value) {
_cleanup_free_ char *x = NULL;
int r;
x = strjoin(field, value);
if (!x)
return -ENOMEM;
r = iovw_put(iovw, x, strlen(x));
if (r >= 0)
TAKE_PTR(x);
return r;
}
int iovw_put_string_field_free(struct iovec_wrapper *iovw, const char *field, char *value) {
_cleanup_free_ _unused_ char *free_ptr = value;
return iovw_put_string_field(iovw, field, value);
}
void iovw_rebase(struct iovec_wrapper *iovw, char *old, char *new) {
for (size_t i = 0; i < iovw->count; i++)
iovw->iovec[i].iov_base = (char *)iovw->iovec[i].iov_base - old + new;
}
size_t iovw_size(struct iovec_wrapper *iovw) {
size_t n = 0;
for (size_t i = 0; i < iovw->count; i++)
n += iovw->iovec[i].iov_len;
return n;
}
void iovec_array_free(struct iovec *iov, size_t n) {
if (!iov)
return;
for (size_t i = 0; i < n; i++)
free(iov[i].iov_base);
free(iov);
}
| 11,080 | 27.707254 | 119 | c |
null | systemd-main/src/basic/io-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <poll.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
#include <sys/uio.h>
#include "macro.h"
#include "time-util.h"
int flush_fd(int fd);
ssize_t loop_read(int fd, void *buf, size_t nbytes, bool do_poll);
int loop_read_exact(int fd, void *buf, size_t nbytes, bool do_poll);
int loop_write(int fd, const void *buf, size_t nbytes, bool do_poll);
int pipe_eof(int fd);
int ppoll_usec(struct pollfd *fds, size_t nfds, usec_t timeout);
int fd_wait_for_event(int fd, int event, usec_t timeout);
ssize_t sparse_write(int fd, const void *p, size_t sz, size_t run_length);
static inline size_t IOVEC_TOTAL_SIZE(const struct iovec *i, size_t n) {
size_t r = 0;
for (size_t j = 0; j < n; j++)
r += i[j].iov_len;
return r;
}
static inline bool IOVEC_INCREMENT(struct iovec *i, size_t n, size_t k) {
/* Returns true if there is nothing else to send (bytes written cover all of the iovec),
* false if there's still work to do. */
for (size_t j = 0; j < n; j++) {
size_t sub;
if (i[j].iov_len == 0)
continue;
if (k == 0)
return false;
sub = MIN(i[j].iov_len, k);
i[j].iov_len -= sub;
i[j].iov_base = (uint8_t*) i[j].iov_base + sub;
k -= sub;
}
assert(k == 0); /* Anything else would mean that we wrote more bytes than available,
* or the kernel reported writing more bytes than sent. */
return true;
}
static inline bool FILE_SIZE_VALID(uint64_t l) {
/* ftruncate() and friends take an unsigned file size, but actually cannot deal with file sizes larger than
* 2^63 since the kernel internally handles it as signed value. This call allows checking for this early. */
return (l >> 63) == 0;
}
static inline bool FILE_SIZE_VALID_OR_INFINITY(uint64_t l) {
/* Same as above, but allows one extra value: -1 as indication for infinity. */
if (l == UINT64_MAX)
return true;
return FILE_SIZE_VALID(l);
}
#define IOVEC_NULL (struct iovec) {}
#define IOVEC_MAKE(base, len) (struct iovec) { .iov_base = (base), .iov_len = (len) }
#define IOVEC_MAKE_STRING(string) \
({ \
char *_s = (char*) (string); \
IOVEC_MAKE(_s, strlen(_s)); \
})
char* set_iovec_string_field(struct iovec *iovec, size_t *n_iovec, const char *field, const char *value);
char* set_iovec_string_field_free(struct iovec *iovec, size_t *n_iovec, const char *field, char *value);
struct iovec_wrapper {
struct iovec *iovec;
size_t count;
};
struct iovec_wrapper *iovw_new(void);
struct iovec_wrapper *iovw_free(struct iovec_wrapper *iovw);
struct iovec_wrapper *iovw_free_free(struct iovec_wrapper *iovw);
void iovw_free_contents(struct iovec_wrapper *iovw, bool free_vectors);
int iovw_put(struct iovec_wrapper *iovw, void *data, size_t len);
static inline int iovw_consume(struct iovec_wrapper *iovw, void *data, size_t len) {
/* Move data into iovw or free on error */
int r = iovw_put(iovw, data, len);
if (r < 0)
free(data);
return r;
}
int iovw_put_string_field(struct iovec_wrapper *iovw, const char *field, const char *value);
int iovw_put_string_field_free(struct iovec_wrapper *iovw, const char *field, char *value);
void iovw_rebase(struct iovec_wrapper *iovw, char *old, char *new);
size_t iovw_size(struct iovec_wrapper *iovw);
void iovec_array_free(struct iovec *iov, size_t n);
| 3,782 | 32.477876 | 116 | h |
null | systemd-main/src/basic/ioprio-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "ioprio-util.h"
#include "parse-util.h"
#include "string-table.h"
int ioprio_parse_priority(const char *s, int *ret) {
int i, r;
assert(s);
assert(ret);
r = safe_atoi(s, &i);
if (r < 0)
return r;
if (!ioprio_priority_is_valid(i))
return -EINVAL;
*ret = i;
return 0;
}
static const char *const ioprio_class_table[] = {
[IOPRIO_CLASS_NONE] = "none",
[IOPRIO_CLASS_RT] = "realtime",
[IOPRIO_CLASS_BE] = "best-effort",
[IOPRIO_CLASS_IDLE] = "idle",
};
DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(ioprio_class, int, IOPRIO_N_CLASSES);
| 721 | 21.5625 | 78 | c |
null | systemd-main/src/basic/ioprio-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "macro.h"
#include "missing_ioprio.h"
int ioprio_class_to_string_alloc(int i, char **s);
int ioprio_class_from_string(const char *s);
static inline bool ioprio_class_is_valid(int i) {
return IN_SET(i, IOPRIO_CLASS_NONE, IOPRIO_CLASS_RT, IOPRIO_CLASS_BE, IOPRIO_CLASS_IDLE);
}
static inline bool ioprio_priority_is_valid(int i) {
return i >= 0 && i < IOPRIO_BE_NR;
}
int ioprio_parse_priority(const char *s, int *ret);
/* IOPRIO_CLASS_NONE with any prio value is another way to say IOPRIO_CLASS_BE with level 4. Encode that in a
* proper macro. */
#define IOPRIO_DEFAULT_CLASS_AND_PRIO ioprio_prio_value(IOPRIO_CLASS_BE, 4)
static inline int ioprio_normalize(int v) {
/* Converts IOPRIO_CLASS_NONE to what it actually means */
return ioprio_prio_class(v) == IOPRIO_CLASS_NONE ? IOPRIO_DEFAULT_CLASS_AND_PRIO : v;
}
| 925 | 32.071429 | 109 | h |
null | systemd-main/src/basic/label.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stddef.h>
#include "label.h"
static const LabelOps *label_ops = NULL;
int label_ops_set(const LabelOps *ops) {
if (label_ops)
return -EBUSY;
label_ops = ops;
return 0;
}
int label_ops_pre(int dir_fd, const char *path, mode_t mode) {
if (!label_ops || !label_ops->pre)
return 0;
return label_ops->pre(dir_fd, path, mode);
}
int label_ops_post(int dir_fd, const char *path) {
if (!label_ops || !label_ops->post)
return 0;
return label_ops->post(dir_fd, path);
}
| 651 | 20.032258 | 62 | c |
null | systemd-main/src/basic/limits-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <unistd.h>
#include "alloc-util.h"
#include "cgroup-util.h"
#include "limits-util.h"
#include "memory-util.h"
#include "parse-util.h"
#include "process-util.h"
#include "procfs-util.h"
#include "string-util.h"
uint64_t physical_memory(void) {
_cleanup_free_ char *root = NULL, *value = NULL;
uint64_t mem, lim;
size_t ps;
long sc;
int r;
/* We return this as uint64_t in case we are running as 32-bit process on a 64-bit kernel with huge amounts of
* memory.
*
* In order to support containers nicely that have a configured memory limit we'll take the minimum of the
* physically reported amount of memory and the limit configured for the root cgroup, if there is any. */
sc = sysconf(_SC_PHYS_PAGES);
assert(sc > 0);
ps = page_size();
mem = (uint64_t) sc * (uint64_t) ps;
r = cg_get_root_path(&root);
if (r < 0) {
log_debug_errno(r, "Failed to determine root cgroup, ignoring cgroup memory limit: %m");
return mem;
}
r = cg_all_unified();
if (r < 0) {
log_debug_errno(r, "Failed to determine root unified mode, ignoring cgroup memory limit: %m");
return mem;
}
if (r > 0) {
r = cg_get_attribute("memory", root, "memory.max", &value);
if (r == -ENOENT) /* Field does not exist on the system's top-level cgroup, hence don't
* complain. (Note that it might exist on our own root though, if we live
* in a cgroup namespace, hence check anyway instead of not even
* trying.) */
return mem;
if (r < 0) {
log_debug_errno(r, "Failed to read memory.max cgroup attribute, ignoring cgroup memory limit: %m");
return mem;
}
if (streq(value, "max"))
return mem;
} else {
r = cg_get_attribute("memory", root, "memory.limit_in_bytes", &value);
if (r < 0) {
log_debug_errno(r, "Failed to read memory.limit_in_bytes cgroup attribute, ignoring cgroup memory limit: %m");
return mem;
}
}
r = safe_atou64(value, &lim);
if (r < 0) {
log_debug_errno(r, "Failed to parse cgroup memory limit '%s', ignoring: %m", value);
return mem;
}
if (lim == UINT64_MAX)
return mem;
/* Make sure the limit is a multiple of our own page size */
lim /= ps;
lim *= ps;
return MIN(mem, lim);
}
uint64_t physical_memory_scale(uint64_t v, uint64_t max) {
uint64_t p, m, ps;
/* Shortcut two special cases */
if (v == 0)
return 0;
if (v == max)
return physical_memory();
assert(max > 0);
/* Returns the physical memory size, multiplied by v divided by max. Returns UINT64_MAX on overflow. On success
* the result is a multiple of the page size (rounds down). */
ps = page_size();
assert(ps > 0);
p = physical_memory() / ps;
assert(p > 0);
if (v > UINT64_MAX / p)
return UINT64_MAX;
m = p * v;
m /= max;
if (m > UINT64_MAX / ps)
return UINT64_MAX;
return m * ps;
}
uint64_t system_tasks_max(void) {
uint64_t a = TASKS_MAX, b = TASKS_MAX, c = TASKS_MAX;
_cleanup_free_ char *root = NULL;
int r;
/* Determine the maximum number of tasks that may run on this system. We check three sources to
* determine this limit:
*
* a) kernel.threads-max sysctl: the maximum number of tasks (threads) the kernel allows.
*
* This puts a direct limit on the number of concurrent tasks.
*
* b) kernel.pid_max sysctl: the maximum PID value.
*
* This limits the numeric range PIDs can take, and thus indirectly also limits the number of
* concurrent threads. It's primarily a compatibility concept: some crappy old code used a signed
* 16-bit type for PIDs, hence the kernel provides a way to ensure the PIDs never go beyond
* INT16_MAX by default.
*
* Also note the weird definition: PIDs assigned will be kept below this value, which means
* the number of tasks that can be created is one lower, as PID 0 is not a valid process ID.
*
* c) pids.max on the root cgroup: the kernel's configured maximum number of tasks.
*
* and then pick the smallest of the three.
*
* By default pid_max is set to much lower values than threads-max, hence the limit people come into
* contact with first, as it's the lowest boundary they need to bump when they want higher number of
* processes.
*/
r = procfs_get_threads_max(&a);
if (r < 0)
log_debug_errno(r, "Failed to read kernel.threads-max, ignoring: %m");
r = procfs_get_pid_max(&b);
if (r < 0)
log_debug_errno(r, "Failed to read kernel.pid_max, ignoring: %m");
else if (b > 0)
/* Subtract one from pid_max, since PID 0 is not a valid PID */
b--;
r = cg_get_root_path(&root);
if (r < 0)
log_debug_errno(r, "Failed to determine cgroup root path, ignoring: %m");
else {
r = cg_get_attribute_as_uint64("pids", root, "pids.max", &c);
if (r < 0)
log_debug_errno(r, "Failed to read pids.max attribute of root cgroup, ignoring: %m");
}
return MIN3(a, b, c);
}
uint64_t system_tasks_max_scale(uint64_t v, uint64_t max) {
uint64_t t, m;
/* Shortcut two special cases */
if (v == 0)
return 0;
if (v == max)
return system_tasks_max();
assert(max > 0);
/* Multiply the system's task value by the fraction v/max. Hence, if max==100 this calculates percentages
* relative to the system's maximum number of tasks. Returns UINT64_MAX on overflow. */
t = system_tasks_max();
assert(t > 0);
if (v > UINT64_MAX / t) /* overflow? */
return UINT64_MAX;
m = t * v;
return m / max;
}
| 6,693 | 34.231579 | 134 | c |
null | systemd-main/src/basic/list.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/* The head of the linked list. Use this in the structure that shall
* contain the head of the linked list */
#define LIST_HEAD(t,name) \
t *name
/* The pointers in the linked list's items. Use this in the item structure */
#define LIST_FIELDS(t,name) \
t *name##_next, *name##_prev
/* Initialize the list's head */
#define LIST_HEAD_INIT(head) \
do { \
(head) = NULL; \
} while (false)
/* Initialize a list item */
#define LIST_INIT(name,item) \
do { \
typeof(*(item)) *_item = (item); \
assert(_item); \
_item->name##_prev = _item->name##_next = NULL; \
} while (false)
/* Prepend an item to the list */
#define LIST_PREPEND(name,head,item) \
({ \
typeof(*(head)) **_head = &(head), *_item = (item); \
assert(_item); \
if ((_item->name##_next = *_head)) \
_item->name##_next->name##_prev = _item; \
_item->name##_prev = NULL; \
*_head = _item; \
_item; \
})
/* Append an item to the list */
#define LIST_APPEND(name,head,item) \
({ \
typeof(*(head)) **_hhead = &(head), *_tail; \
_tail = LIST_FIND_TAIL(name, *_hhead); \
LIST_INSERT_AFTER(name, *_hhead, _tail, item); \
})
/* Remove an item from the list */
#define LIST_REMOVE(name,head,item) \
({ \
typeof(*(head)) **_head = &(head), *_item = (item); \
assert(_item); \
if (_item->name##_next) \
_item->name##_next->name##_prev = _item->name##_prev; \
if (_item->name##_prev) \
_item->name##_prev->name##_next = _item->name##_next; \
else { \
assert(*_head == _item); \
*_head = _item->name##_next; \
} \
_item->name##_next = _item->name##_prev = NULL; \
_item; \
})
/* Find the head of the list */
#define LIST_FIND_HEAD(name,item) \
({ \
typeof(*(item)) *_item = (item); \
while (_item && _item->name##_prev) \
_item = _item->name##_prev; \
_item; \
})
/* Find the tail of the list */
#define LIST_FIND_TAIL(name,item) \
({ \
typeof(*(item)) *_item = (item); \
while (_item && _item->name##_next) \
_item = _item->name##_next; \
_item; \
})
/* Insert an item after another one (a = where, b = what) */
#define LIST_INSERT_AFTER(name,head,a,b) \
({ \
typeof(*(head)) **_head = &(head), *_a = (a), *_b = (b); \
assert(_b); \
if (!_a) { \
if ((_b->name##_next = *_head)) \
_b->name##_next->name##_prev = _b; \
_b->name##_prev = NULL; \
*_head = _b; \
} else { \
if ((_b->name##_next = _a->name##_next)) \
_b->name##_next->name##_prev = _b; \
_b->name##_prev = _a; \
_a->name##_next = _b; \
} \
_b; \
})
/* Insert an item before another one (a = where, b = what) */
#define LIST_INSERT_BEFORE(name,head,a,b) \
({ \
typeof(*(head)) **_head = &(head), *_a = (a), *_b = (b); \
assert(_b); \
if (!_a) { \
if (!*_head) { \
_b->name##_next = NULL; \
_b->name##_prev = NULL; \
*_head = _b; \
} else { \
typeof(*(head)) *_tail = (head); \
while (_tail->name##_next) \
_tail = _tail->name##_next; \
_b->name##_next = NULL; \
_b->name##_prev = _tail; \
_tail->name##_next = _b; \
} \
} else { \
if ((_b->name##_prev = _a->name##_prev)) \
_b->name##_prev->name##_next = _b; \
else \
*_head = _b; \
_b->name##_next = _a; \
_a->name##_prev = _b; \
} \
_b; \
})
#define LIST_JUST_US(name, item) \
({ \
typeof(*(item)) *_item = (item); \
!(_item)->name##_prev && !(_item)->name##_next; \
})
/* The type of the iterator 'i' is automatically determined by the type of 'head', and declared in the
* loop. Hence, do not declare the same variable in the outer scope. Sometimes, we set 'head' through
* hashmap_get(). In that case, you need to explicitly cast the result. */
#define LIST_FOREACH_WITH_NEXT(name,i,n,head) \
for (typeof(*(head)) *n, *i = (head); i && (n = i->name##_next, true); i = n)
#define LIST_FOREACH(name,i,head) \
LIST_FOREACH_WITH_NEXT(name, i, UNIQ_T(n, UNIQ), head)
#define _LIST_FOREACH_WITH_PREV(name,i,p,start) \
for (typeof(*(start)) *p, *i = (start); i && (p = i->name##_prev, true); i = p)
#define LIST_FOREACH_BACKWARDS(name,i,start) \
_LIST_FOREACH_WITH_PREV(name, i, UNIQ_T(p, UNIQ), start)
/* Iterate through all the members of the list p is included in, but skip over p */
#define LIST_FOREACH_OTHERS(name,i,p) \
for (typeof(*(p)) *_p = (p), *i = ({ \
typeof(*_p) *_j = _p; \
while (_j && _j->name##_prev) \
_j = _j->name##_prev; \
if (_j == _p) \
_j = _p->name##_next; \
_j; \
}); \
i; \
i = i->name##_next == _p ? _p->name##_next : i->name##_next)
/* Loop starting from p->next until p->prev. p can be adjusted meanwhile. */
#define LIST_LOOP_BUT_ONE(name,i,head,p) \
for (typeof(*(p)) *i = (p)->name##_next ? (p)->name##_next : (head); \
i != (p); \
i = i->name##_next ? i->name##_next : (head))
/* Join two lists tail to head: a->b, c->d to a->b->c->d and de-initialise second list */
#define LIST_JOIN(name,a,b) \
({ \
assert(b); \
if (!(a)) \
(a) = (b); \
else { \
typeof(*(a)) *_head = (b), *_tail; \
_tail = LIST_FIND_TAIL(name, (a)); \
_tail->name##_next = _head; \
_head->name##_prev = _tail; \
} \
(b) = NULL; \
a; \
})
#define LIST_POP(name, a) \
({ \
typeof(a)* _a = &(a); \
typeof(a) _p = *_a; \
if (_p) \
LIST_REMOVE(name, *_a, _p); \
_p; \
})
/* Now include "macro.h", because we want our definition of assert() which the macros above use. We include
* it down here instead of up top, since macro.h pulls in log.h which in turn needs our own definitions. */
#include "macro.h"
| 11,896 | 59.085859 | 107 | h |
null | systemd-main/src/basic/locale-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <langinfo.h>
#include <libintl.h>
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <sys/mman.h>
#include <sys/stat.h>
#include "constants.h"
#include "dirent-util.h"
#include "env-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "hashmap.h"
#include "locale-util.h"
#include "path-util.h"
#include "set.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "utf8.h"
static char *normalize_locale(const char *name) {
const char *e;
/* Locale names are weird: glibc has some magic rules when looking for the charset name on disk: it
* lowercases everything, and removes most special chars. This means the official .UTF-8 suffix
* becomes .utf8 when looking things up on disk. When enumerating locales, let's do the reverse
* operation, and go back to ".UTF-8" which appears to be the more commonly accepted name. We only do
* that for UTF-8 however, since it's kinda the only charset that matters. */
e = endswith(name, ".utf8");
if (e) {
_cleanup_free_ char *prefix = NULL;
prefix = strndup(name, e - name);
if (!prefix)
return NULL;
return strjoin(prefix, ".UTF-8");
}
e = strstr(name, ".utf8@");
if (e) {
_cleanup_free_ char *prefix = NULL;
prefix = strndup(name, e - name);
if (!prefix)
return NULL;
return strjoin(prefix, ".UTF-8@", e + 6);
}
return strdup(name);
}
static int add_locales_from_archive(Set *locales) {
/* Stolen from glibc... */
struct locarhead {
uint32_t magic;
/* Serial number. */
uint32_t serial;
/* Name hash table. */
uint32_t namehash_offset;
uint32_t namehash_used;
uint32_t namehash_size;
/* String table. */
uint32_t string_offset;
uint32_t string_used;
uint32_t string_size;
/* Table with locale records. */
uint32_t locrectab_offset;
uint32_t locrectab_used;
uint32_t locrectab_size;
/* MD5 sum hash table. */
uint32_t sumhash_offset;
uint32_t sumhash_used;
uint32_t sumhash_size;
};
struct namehashent {
/* Hash value of the name. */
uint32_t hashval;
/* Offset of the name in the string table. */
uint32_t name_offset;
/* Offset of the locale record. */
uint32_t locrec_offset;
};
const struct locarhead *h;
const struct namehashent *e;
const void *p = MAP_FAILED;
_cleanup_close_ int fd = -EBADF;
size_t sz = 0;
struct stat st;
int r;
fd = open("/usr/lib/locale/locale-archive", O_RDONLY|O_NOCTTY|O_CLOEXEC);
if (fd < 0)
return errno == ENOENT ? 0 : -errno;
if (fstat(fd, &st) < 0)
return -errno;
if (!S_ISREG(st.st_mode))
return -EBADMSG;
if (st.st_size < (off_t) sizeof(struct locarhead))
return -EBADMSG;
if (file_offset_beyond_memory_size(st.st_size))
return -EFBIG;
p = mmap(NULL, st.st_size, PROT_READ, MAP_SHARED, fd, 0);
if (p == MAP_FAILED)
return -errno;
h = (const struct locarhead *) p;
if (h->magic != 0xde020109 ||
h->namehash_offset + h->namehash_size > st.st_size ||
h->string_offset + h->string_size > st.st_size ||
h->locrectab_offset + h->locrectab_size > st.st_size ||
h->sumhash_offset + h->sumhash_size > st.st_size) {
r = -EBADMSG;
goto finish;
}
e = (const struct namehashent*) ((const uint8_t*) p + h->namehash_offset);
for (size_t i = 0; i < h->namehash_size; i++) {
char *z;
if (e[i].locrec_offset == 0)
continue;
if (!utf8_is_valid((char*) p + e[i].name_offset))
continue;
z = normalize_locale((char*) p + e[i].name_offset);
if (!z) {
r = -ENOMEM;
goto finish;
}
r = set_consume(locales, z);
if (r < 0)
goto finish;
}
r = 0;
finish:
if (p != MAP_FAILED)
munmap((void*) p, sz);
return r;
}
static int add_locales_from_libdir(Set *locales) {
_cleanup_closedir_ DIR *dir = NULL;
int r;
dir = opendir("/usr/lib/locale");
if (!dir)
return errno == ENOENT ? 0 : -errno;
FOREACH_DIRENT(de, dir, return -errno) {
char *z;
if (de->d_type != DT_DIR)
continue;
z = normalize_locale(de->d_name);
if (!z)
return -ENOMEM;
r = set_consume(locales, z);
if (r < 0 && r != -EEXIST)
return r;
}
return 0;
}
int get_locales(char ***ret) {
_cleanup_set_free_free_ Set *locales = NULL;
_cleanup_strv_free_ char **l = NULL;
int r;
locales = set_new(&string_hash_ops);
if (!locales)
return -ENOMEM;
r = add_locales_from_archive(locales);
if (r < 0 && r != -ENOENT)
return r;
r = add_locales_from_libdir(locales);
if (r < 0)
return r;
char *locale;
SET_FOREACH(locale, locales) {
r = locale_is_installed(locale);
if (r < 0)
return r;
if (r == 0)
free(set_remove(locales, locale));
}
l = set_get_strv(locales);
if (!l)
return -ENOMEM;
/* Now, all elements are owned by strv 'l'. Hence, do not call set_free_free(). */
locales = set_free(locales);
r = getenv_bool("SYSTEMD_LIST_NON_UTF8_LOCALES");
if (r == -ENXIO || r == 0) {
char **a, **b;
/* Filter out non-UTF-8 locales, because it's 2019, by default */
for (a = b = l; *a; a++) {
if (endswith(*a, "UTF-8") ||
strstr(*a, ".UTF-8@"))
*(b++) = *a;
else
free(*a);
}
*b = NULL;
} else if (r < 0)
log_debug_errno(r, "Failed to parse $SYSTEMD_LIST_NON_UTF8_LOCALES as boolean");
strv_sort(l);
*ret = TAKE_PTR(l);
return 0;
}
bool locale_is_valid(const char *name) {
if (isempty(name))
return false;
if (strlen(name) >= 128)
return false;
if (!utf8_is_valid(name))
return false;
if (!filename_is_valid(name))
return false;
if (!string_is_safe(name))
return false;
return true;
}
int locale_is_installed(const char *name) {
if (!locale_is_valid(name))
return false;
if (STR_IN_SET(name, "C", "POSIX")) /* These ones are always OK */
return true;
_cleanup_(freelocalep) locale_t loc =
newlocale(LC_ALL_MASK, name, 0);
if (loc == (locale_t) 0)
return errno == ENOMEM ? -ENOMEM : false;
return true;
}
void init_gettext(void) {
setlocale(LC_ALL, "");
textdomain(GETTEXT_PACKAGE);
}
bool is_locale_utf8(void) {
static int cached_answer = -1;
const char *set;
int r;
/* Note that we default to 'true' here, since today UTF8 is
* pretty much supported everywhere. */
if (cached_answer >= 0)
goto out;
r = getenv_bool_secure("SYSTEMD_UTF8");
if (r >= 0) {
cached_answer = r;
goto out;
} else if (r != -ENXIO)
log_debug_errno(r, "Failed to parse $SYSTEMD_UTF8, ignoring: %m");
if (!setlocale(LC_ALL, "")) {
cached_answer = true;
goto out;
}
set = nl_langinfo(CODESET);
if (!set) {
cached_answer = true;
goto out;
}
if (streq(set, "UTF-8")) {
cached_answer = true;
goto out;
}
/* For LC_CTYPE=="C" return true, because CTYPE is effectively
* unset and everything can do to UTF-8 nowadays. */
set = setlocale(LC_CTYPE, NULL);
if (!set) {
cached_answer = true;
goto out;
}
/* Check result, but ignore the result if C was set
* explicitly. */
cached_answer =
STR_IN_SET(set, "C", "POSIX") &&
!getenv("LC_ALL") &&
!getenv("LC_CTYPE") &&
!getenv("LANG");
out:
return (bool) cached_answer;
}
void locale_variables_free(char *l[_VARIABLE_LC_MAX]) {
if (!l)
return;
for (LocaleVariable i = 0; i < _VARIABLE_LC_MAX; i++)
l[i] = mfree(l[i]);
}
void locale_variables_simplify(char *l[_VARIABLE_LC_MAX]) {
assert(l);
for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++) {
if (p == VARIABLE_LANG)
continue;
if (isempty(l[p]) || streq_ptr(l[VARIABLE_LANG], l[p]))
l[p] = mfree(l[p]);
}
}
static const char * const locale_variable_table[_VARIABLE_LC_MAX] = {
[VARIABLE_LANG] = "LANG",
[VARIABLE_LANGUAGE] = "LANGUAGE",
[VARIABLE_LC_CTYPE] = "LC_CTYPE",
[VARIABLE_LC_NUMERIC] = "LC_NUMERIC",
[VARIABLE_LC_TIME] = "LC_TIME",
[VARIABLE_LC_COLLATE] = "LC_COLLATE",
[VARIABLE_LC_MONETARY] = "LC_MONETARY",
[VARIABLE_LC_MESSAGES] = "LC_MESSAGES",
[VARIABLE_LC_PAPER] = "LC_PAPER",
[VARIABLE_LC_NAME] = "LC_NAME",
[VARIABLE_LC_ADDRESS] = "LC_ADDRESS",
[VARIABLE_LC_TELEPHONE] = "LC_TELEPHONE",
[VARIABLE_LC_MEASUREMENT] = "LC_MEASUREMENT",
[VARIABLE_LC_IDENTIFICATION] = "LC_IDENTIFICATION"
};
DEFINE_STRING_TABLE_LOOKUP(locale_variable, LocaleVariable);
| 10,988 | 27.994723 | 109 | c |
null | systemd-main/src/basic/locale-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <libintl.h>
#include <locale.h>
#include <stdbool.h>
#include "macro.h"
typedef enum LocaleVariable {
/* We don't list LC_ALL here on purpose. People should be
* using LANG instead. */
VARIABLE_LANG,
VARIABLE_LANGUAGE,
VARIABLE_LC_CTYPE,
VARIABLE_LC_NUMERIC,
VARIABLE_LC_TIME,
VARIABLE_LC_COLLATE,
VARIABLE_LC_MONETARY,
VARIABLE_LC_MESSAGES,
VARIABLE_LC_PAPER,
VARIABLE_LC_NAME,
VARIABLE_LC_ADDRESS,
VARIABLE_LC_TELEPHONE,
VARIABLE_LC_MEASUREMENT,
VARIABLE_LC_IDENTIFICATION,
_VARIABLE_LC_MAX,
_VARIABLE_LC_INVALID = -EINVAL,
} LocaleVariable;
int get_locales(char ***l);
bool locale_is_valid(const char *name);
int locale_is_installed(const char *name);
#define _(String) gettext(String)
#define N_(String) String
void init_gettext(void);
bool is_locale_utf8(void);
const char* locale_variable_to_string(LocaleVariable i) _const_;
LocaleVariable locale_variable_from_string(const char *s) _pure_;
static inline void freelocalep(locale_t *p) {
if (*p == (locale_t) 0)
return;
freelocale(*p);
}
void locale_variables_free(char* l[_VARIABLE_LC_MAX]);
static inline void locale_variables_freep(char*(*l)[_VARIABLE_LC_MAX]) {
locale_variables_free(*l);
}
void locale_variables_simplify(char *l[_VARIABLE_LC_MAX]);
| 1,477 | 24.929825 | 72 | h |
null | systemd-main/src/basic/lock-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <sys/file.h>
#include <sys/stat.h>
#include "alloc-util.h"
#include "fd-util.h"
#include "fs-util.h"
#include "lock-util.h"
#include "macro.h"
#include "missing_fcntl.h"
#include "path-util.h"
int make_lock_file_at(int dir_fd, const char *p, int operation, LockFile *ret) {
_cleanup_close_ int fd = -EBADF, dfd = -EBADF;
_cleanup_free_ char *t = NULL;
assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
assert(p);
assert(IN_SET(operation & ~LOCK_NB, LOCK_EX, LOCK_SH));
assert(ret);
if (isempty(p))
return -EINVAL;
/* We use UNPOSIX locks as they have nice semantics, and are mostly compatible with NFS. */
dfd = fd_reopen(dir_fd, O_CLOEXEC|O_PATH|O_DIRECTORY);
if (dfd < 0)
return dfd;
t = strdup(p);
if (!t)
return -ENOMEM;
fd = xopenat_lock(dfd,
p,
O_CREAT|O_RDWR|O_NOFOLLOW|O_CLOEXEC|O_NOCTTY,
/* xopen_flags = */ 0,
0600,
LOCK_UNPOSIX,
operation);
if (fd < 0)
return fd == -EAGAIN ? -EBUSY : fd;
*ret = (LockFile) {
.dir_fd = TAKE_FD(dfd),
.path = TAKE_PTR(t),
.fd = TAKE_FD(fd),
.operation = operation,
};
return 0;
}
int make_lock_file_for(const char *p, int operation, LockFile *ret) {
_cleanup_free_ char *fn = NULL, *dn = NULL, *t = NULL;
int r;
assert(p);
assert(ret);
r = path_extract_filename(p, &fn);
if (r < 0)
return r;
r = path_extract_directory(p, &dn);
if (r < 0)
return r;
t = strjoin(dn, "/.#", fn, ".lck");
if (!t)
return -ENOMEM;
return make_lock_file(t, operation, ret);
}
void release_lock_file(LockFile *f) {
if (!f)
return;
if (f->path) {
/* If we are the exclusive owner we can safely delete
* the lock file itself. If we are not the exclusive
* owner, we can try becoming it. */
if (f->fd >= 0 &&
(f->operation & ~LOCK_NB) == LOCK_SH &&
unposix_lock(f->fd, LOCK_EX|LOCK_NB) >= 0)
f->operation = LOCK_EX|LOCK_NB;
if ((f->operation & ~LOCK_NB) == LOCK_EX)
(void) unlinkat(f->dir_fd, f->path, 0);
f->path = mfree(f->path);
}
f->dir_fd = safe_close(f->dir_fd);
f->fd = safe_close(f->fd);
f->operation = 0;
}
static int fcntl_lock(int fd, int operation, bool ofd) {
int cmd, type, r;
assert(fd >= 0);
if (ofd)
cmd = (operation & LOCK_NB) ? F_OFD_SETLK : F_OFD_SETLKW;
else
cmd = (operation & LOCK_NB) ? F_SETLK : F_SETLKW;
switch (operation & ~LOCK_NB) {
case LOCK_EX:
type = F_WRLCK;
break;
case LOCK_SH:
type = F_RDLCK;
break;
case LOCK_UN:
type = F_UNLCK;
break;
default:
assert_not_reached();
}
r = RET_NERRNO(fcntl(fd, cmd, &(struct flock) {
.l_type = type,
.l_whence = SEEK_SET,
.l_start = 0,
.l_len = 0,
}));
if (r == -EACCES) /* Treat EACCESS/EAGAIN the same as per man page. */
r = -EAGAIN;
return r;
}
int posix_lock(int fd, int operation) {
return fcntl_lock(fd, operation, /*ofd=*/ false);
}
int unposix_lock(int fd, int operation) {
return fcntl_lock(fd, operation, /*ofd=*/ true);
}
void posix_unlockpp(int **fd) {
assert(fd);
if (!*fd || **fd < 0)
return;
(void) fcntl_lock(**fd, LOCK_UN, /*ofd=*/ false);
*fd = NULL;
}
void unposix_unlockpp(int **fd) {
assert(fd);
if (!*fd || **fd < 0)
return;
(void) fcntl_lock(**fd, LOCK_UN, /*ofd=*/ true);
*fd = NULL;
}
int lock_generic(int fd, LockType type, int operation) {
assert(fd >= 0);
switch (type) {
case LOCK_NONE:
return 0;
case LOCK_BSD:
return RET_NERRNO(flock(fd, operation));
case LOCK_POSIX:
return posix_lock(fd, operation);
case LOCK_UNPOSIX:
return unposix_lock(fd, operation);
default:
assert_not_reached();
}
}
| 4,965 | 25.275132 | 99 | c |
null | systemd-main/src/basic/lock-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <fcntl.h>
typedef struct LockFile {
int dir_fd;
char *path;
int fd;
int operation;
} LockFile;
int make_lock_file_at(int dir_fd, const char *p, int operation, LockFile *ret);
static inline int make_lock_file(const char *p, int operation, LockFile *ret) {
return make_lock_file_at(AT_FDCWD, p, operation, ret);
}
int make_lock_file_for(const char *p, int operation, LockFile *ret);
void release_lock_file(LockFile *f);
#define LOCK_FILE_INIT { .dir_fd = -EBADF, .fd = -EBADF }
/* POSIX locks with the same interface as flock(). */
int posix_lock(int fd, int operation);
void posix_unlockpp(int **fd);
#define CLEANUP_POSIX_UNLOCK(fd) \
_cleanup_(posix_unlockpp) _unused_ int *CONCATENATE(_cleanup_posix_unlock_, UNIQ) = &(fd)
/* Open File Description locks with the same interface as flock(). */
int unposix_lock(int fd, int operation);
void unposix_unlockpp(int **fd);
#define CLEANUP_UNPOSIX_UNLOCK(fd) \
_cleanup_(unposix_unlockpp) _unused_ int *CONCATENATE(_cleanup_unposix_unlock_, UNIQ) = &(fd)
typedef enum LockType {
LOCK_NONE, /* Don't lock the file descriptor. Useful if you need to conditionally lock a file. */
LOCK_BSD,
LOCK_POSIX,
LOCK_UNPOSIX,
} LockType;
int lock_generic(int fd, LockType type, int operation);
| 1,463 | 32.272727 | 105 | h |
null | systemd-main/src/basic/login-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <unistd.h>
#define SD_LOGIND_ROOT_CHECK_INHIBITORS (UINT64_C(1) << 0)
#define SD_LOGIND_REBOOT_VIA_KEXEC (UINT64_C(1) << 1)
#define SD_LOGIND_SOFT_REBOOT (UINT64_C(1) << 2)
/* For internal use only */
#define SD_LOGIND_INTERACTIVE (UINT64_C(1) << 63)
#define SD_LOGIND_SHUTDOWN_AND_SLEEP_FLAGS_PUBLIC (SD_LOGIND_ROOT_CHECK_INHIBITORS|SD_LOGIND_REBOOT_VIA_KEXEC|SD_LOGIND_SOFT_REBOOT)
#define SD_LOGIND_SHUTDOWN_AND_SLEEP_FLAGS_ALL (SD_LOGIND_SHUTDOWN_AND_SLEEP_FLAGS_PUBLIC|SD_LOGIND_INTERACTIVE)
bool session_id_valid(const char *id);
static inline bool logind_running(void) {
return access("/run/systemd/seats/", F_OK) >= 0;
}
| 803 | 35.545455 | 132 | h |
null | systemd-main/src/basic/macro.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <assert.h>
#include <errno.h>
#include <inttypes.h>
#include <stdbool.h>
#include <sys/param.h>
#include <sys/sysmacros.h>
#include <sys/types.h>
#include "constants.h"
#include "macro-fundamental.h"
/* Note: on GCC "no_sanitize_address" is a function attribute only, on llvm it may also be applied to global
* variables. We define a specific macro which knows this. Note that on GCC we don't need this decorator so much, since
* our primary usecase for this attribute is registration structures placed in named ELF sections which shall not be
* padded, but GCC doesn't pad those anyway if AddressSanitizer is enabled. */
#if HAS_FEATURE_ADDRESS_SANITIZER && defined(__clang__)
#define _variable_no_sanitize_address_ __attribute__((__no_sanitize_address__))
#else
#define _variable_no_sanitize_address_
#endif
/* Apparently there's no has_feature() call defined to check for ubsan, hence let's define this
* unconditionally on llvm */
#if defined(__clang__)
#define _function_no_sanitize_float_cast_overflow_ __attribute__((no_sanitize("float-cast-overflow")))
#else
#define _function_no_sanitize_float_cast_overflow_
#endif
/* Temporarily disable some warnings */
#define DISABLE_WARNING_DEPRECATED_DECLARATIONS \
_Pragma("GCC diagnostic push"); \
_Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
#define DISABLE_WARNING_FORMAT_NONLITERAL \
_Pragma("GCC diagnostic push"); \
_Pragma("GCC diagnostic ignored \"-Wformat-nonliteral\"")
#define DISABLE_WARNING_MISSING_PROTOTYPES \
_Pragma("GCC diagnostic push"); \
_Pragma("GCC diagnostic ignored \"-Wmissing-prototypes\"")
#define DISABLE_WARNING_NONNULL \
_Pragma("GCC diagnostic push"); \
_Pragma("GCC diagnostic ignored \"-Wnonnull\"")
#define DISABLE_WARNING_SHADOW \
_Pragma("GCC diagnostic push"); \
_Pragma("GCC diagnostic ignored \"-Wshadow\"")
#define DISABLE_WARNING_INCOMPATIBLE_POINTER_TYPES \
_Pragma("GCC diagnostic push"); \
_Pragma("GCC diagnostic ignored \"-Wincompatible-pointer-types\"")
#if HAVE_WSTRINGOP_TRUNCATION
# define DISABLE_WARNING_STRINGOP_TRUNCATION \
_Pragma("GCC diagnostic push"); \
_Pragma("GCC diagnostic ignored \"-Wstringop-truncation\"")
#else
# define DISABLE_WARNING_STRINGOP_TRUNCATION \
_Pragma("GCC diagnostic push")
#endif
#define DISABLE_WARNING_TYPE_LIMITS \
_Pragma("GCC diagnostic push"); \
_Pragma("GCC diagnostic ignored \"-Wtype-limits\"")
#define DISABLE_WARNING_ADDRESS \
_Pragma("GCC diagnostic push"); \
_Pragma("GCC diagnostic ignored \"-Waddress\"")
#define REENABLE_WARNING \
_Pragma("GCC diagnostic pop")
/* automake test harness */
#define EXIT_TEST_SKIP 77
/* builtins */
#if __SIZEOF_INT__ == 4
#define BUILTIN_FFS_U32(x) __builtin_ffs(x);
#elif __SIZEOF_LONG__ == 4
#define BUILTIN_FFS_U32(x) __builtin_ffsl(x);
#else
#error "neither int nor long are four bytes long?!?"
#endif
/* align to next higher power-of-2 (except for: 0 => 0, overflow => 0) */
static inline unsigned long ALIGN_POWER2(unsigned long u) {
/* Avoid subtraction overflow */
if (u == 0)
return 0;
/* clz(0) is undefined */
if (u == 1)
return 1;
/* left-shift overflow is undefined */
if (__builtin_clzl(u - 1UL) < 1)
return 0;
return 1UL << (sizeof(u) * 8 - __builtin_clzl(u - 1UL));
}
static inline size_t GREEDY_ALLOC_ROUND_UP(size_t l) {
size_t m;
/* Round up allocation sizes a bit to some reasonable, likely larger value. This is supposed to be
* used for cases which are likely called in an allocation loop of some form, i.e. that repetitively
* grow stuff, for example strv_extend() and suchlike.
*
* Note the difference to GREEDY_REALLOC() here, as this helper operates on a single size value only,
* and rounds up to next multiple of 2, needing no further counter.
*
* Note the benefits of direct ALIGN_POWER2() usage: type-safety for size_t, sane handling for very
* small (i.e. <= 2) and safe handling for very large (i.e. > SSIZE_MAX) values. */
if (l <= 2)
return 2; /* Never allocate less than 2 of something. */
m = ALIGN_POWER2(l);
if (m == 0) /* overflow? */
return l;
return m;
}
/*
* container_of - cast a member of a structure out to the containing structure
* @ptr: the pointer to the member.
* @type: the type of the container struct this is embedded in.
* @member: the name of the member within the struct.
*/
#define container_of(ptr, type, member) __container_of(UNIQ, (ptr), type, member)
#define __container_of(uniq, ptr, type, member) \
({ \
const typeof( ((type*)0)->member ) *UNIQ_T(A, uniq) = (ptr); \
(type*)( (char *)UNIQ_T(A, uniq) - offsetof(type, member) ); \
})
#ifdef __COVERITY__
/* Use special definitions of assertion macros in order to prevent
* false positives of ASSERT_SIDE_EFFECT on Coverity static analyzer
* for uses of assert_se() and assert_return().
*
* These definitions make expression go through a (trivial) function
* call to ensure they are not discarded. Also use ! or !! to ensure
* the boolean expressions are seen as such.
*
* This technique has been described and recommended in:
* https://community.synopsys.com/s/question/0D534000046Yuzb/suppressing-assertsideeffect-for-functions-that-allow-for-sideeffects
*/
extern void __coverity_panic__(void);
static inline void __coverity_check__(int condition) {
if (!condition)
__coverity_panic__();
}
static inline int __coverity_check_and_return__(int condition) {
return condition;
}
#define assert_message_se(expr, message) __coverity_check__(!!(expr))
#define assert_log(expr, message) __coverity_check_and_return__(!!(expr))
#else /* ! __COVERITY__ */
#define assert_message_se(expr, message) \
do { \
if (_unlikely_(!(expr))) \
log_assert_failed(message, PROJECT_FILE, __LINE__, __func__); \
} while (false)
#define assert_log(expr, message) ((_likely_(expr)) \
? (true) \
: (log_assert_failed_return(message, PROJECT_FILE, __LINE__, __func__), false))
#endif /* __COVERITY__ */
#define assert_se(expr) assert_message_se(expr, #expr)
/* We override the glibc assert() here. */
#undef assert
#ifdef NDEBUG
#define assert(expr) do {} while (false)
#else
#define assert(expr) assert_message_se(expr, #expr)
#endif
#define assert_not_reached() \
log_assert_failed_unreachable(PROJECT_FILE, __LINE__, __func__)
#define assert_return(expr, r) \
do { \
if (!assert_log(expr, #expr)) \
return (r); \
} while (false)
#define assert_return_errno(expr, r, err) \
do { \
if (!assert_log(expr, #expr)) { \
errno = err; \
return (r); \
} \
} while (false)
#define return_with_errno(r, err) \
do { \
errno = abs(err); \
return r; \
} while (false)
#define PTR_TO_INT(p) ((int) ((intptr_t) (p)))
#define INT_TO_PTR(u) ((void *) ((intptr_t) (u)))
#define PTR_TO_UINT(p) ((unsigned) ((uintptr_t) (p)))
#define UINT_TO_PTR(u) ((void *) ((uintptr_t) (u)))
#define PTR_TO_LONG(p) ((long) ((intptr_t) (p)))
#define LONG_TO_PTR(u) ((void *) ((intptr_t) (u)))
#define PTR_TO_ULONG(p) ((unsigned long) ((uintptr_t) (p)))
#define ULONG_TO_PTR(u) ((void *) ((uintptr_t) (u)))
#define PTR_TO_UINT8(p) ((uint8_t) ((uintptr_t) (p)))
#define UINT8_TO_PTR(u) ((void *) ((uintptr_t) (u)))
#define PTR_TO_INT32(p) ((int32_t) ((intptr_t) (p)))
#define INT32_TO_PTR(u) ((void *) ((intptr_t) (u)))
#define PTR_TO_UINT32(p) ((uint32_t) ((uintptr_t) (p)))
#define UINT32_TO_PTR(u) ((void *) ((uintptr_t) (u)))
#define PTR_TO_INT64(p) ((int64_t) ((intptr_t) (p)))
#define INT64_TO_PTR(u) ((void *) ((intptr_t) (u)))
#define PTR_TO_UINT64(p) ((uint64_t) ((uintptr_t) (p)))
#define UINT64_TO_PTR(u) ((void *) ((uintptr_t) (u)))
#define PTR_TO_SIZE(p) ((size_t) ((uintptr_t) (p)))
#define SIZE_TO_PTR(u) ((void *) ((uintptr_t) (u)))
#define CHAR_TO_STR(x) ((char[2]) { x, 0 })
#define char_array_0(x) x[sizeof(x)-1] = 0;
#define sizeof_field(struct_type, member) sizeof(((struct_type *) 0)->member)
#define endoffsetof_field(struct_type, member) (offsetof(struct_type, member) + sizeof_field(struct_type, member))
/* Maximum buffer size needed for formatting an unsigned integer type as hex, including space for '0x'
* prefix and trailing NUL suffix. */
#define HEXADECIMAL_STR_MAX(type) (2 + sizeof(type) * 2 + 1)
/* Returns the number of chars needed to format variables of the specified type as a decimal string. Adds in
* extra space for a negative '-' prefix for signed types. Includes space for the trailing NUL. */
#define DECIMAL_STR_MAX(type) \
((size_t) IS_SIGNED_INTEGER_TYPE(type) + 1U + \
(sizeof(type) <= 1 ? 3U : \
sizeof(type) <= 2 ? 5U : \
sizeof(type) <= 4 ? 10U : \
sizeof(type) <= 8 ? (IS_SIGNED_INTEGER_TYPE(type) ? 19U : 20U) : sizeof(int[-2*(sizeof(type) > 8)])))
/* Returns the number of chars needed to format the specified integer value. It's hence more specific than
* DECIMAL_STR_MAX() which answers the same question for all possible values of the specified type. Does
* *not* include space for a trailing NUL. (If you wonder why we special case _x_ == 0 here: it's to trick
* out gcc's -Wtype-limits, which would complain on comparing an unsigned type with < 0, otherwise. By
* special-casing == 0 here first, we can use <= 0 instead of < 0 to trick out gcc.) */
#define DECIMAL_STR_WIDTH(x) \
({ \
typeof(x) _x_ = (x); \
size_t ans; \
if (_x_ == 0) \
ans = 1; \
else { \
ans = _x_ <= 0 ? 2 : 1; \
while ((_x_ /= 10) != 0) \
ans++; \
} \
ans; \
})
#define SWAP_TWO(x, y) do { \
typeof(x) _t = (x); \
(x) = (y); \
(y) = (_t); \
} while (false)
#define STRV_MAKE(...) ((char**) ((const char*[]) { __VA_ARGS__, NULL }))
#define STRV_MAKE_EMPTY ((char*[1]) { NULL })
#define STRV_MAKE_CONST(...) ((const char* const*) ((const char*[]) { __VA_ARGS__, NULL }))
/* Pointers range from NULL to POINTER_MAX */
#define POINTER_MAX ((void*) UINTPTR_MAX)
/* Iterates through a specified list of pointers. Accepts NULL pointers, but uses POINTER_MAX as internal marker for EOL. */
#define FOREACH_POINTER(p, x, ...) \
for (typeof(p) *_l = (typeof(p)[]) { ({ p = x; }), ##__VA_ARGS__, POINTER_MAX }; \
p != (typeof(p)) POINTER_MAX; \
p = *(++_l))
#define _FOREACH_ARRAY(i, array, num, m, end) \
for (typeof(array[0]) *i = (array), *end = ({ \
typeof(num) m = (num); \
(i && m > 0) ? i + m : NULL; \
}); end && i < end; i++)
#define FOREACH_ARRAY(i, array, num) \
_FOREACH_ARRAY(i, array, num, UNIQ_T(m, UNIQ), UNIQ_T(end, UNIQ))
#define DEFINE_TRIVIAL_DESTRUCTOR(name, type, func) \
static inline void name(type *p) { \
func(p); \
}
/* When func() returns the void value (NULL, -1, …) of the appropriate type */
#define DEFINE_TRIVIAL_CLEANUP_FUNC(type, func) \
static inline void func##p(type *p) { \
if (*p) \
*p = func(*p); \
}
/* When func() doesn't return the appropriate type, set variable to empty afterwards.
* The func() may be provided by a dynamically loaded shared library, hence add an assertion. */
#define DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(type, func, empty) \
static inline void func##p(type *p) { \
if (*p != (empty)) { \
DISABLE_WARNING_ADDRESS; \
assert(func); \
REENABLE_WARNING; \
func(*p); \
*p = (empty); \
} \
}
#define _DEFINE_TRIVIAL_REF_FUNC(type, name, scope) \
scope type *name##_ref(type *p) { \
if (!p) \
return NULL; \
\
/* For type check. */ \
unsigned *q = &p->n_ref; \
assert(*q > 0); \
assert_se(*q < UINT_MAX); \
\
(*q)++; \
return p; \
}
#define _DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func, scope) \
scope type *name##_unref(type *p) { \
if (!p) \
return NULL; \
\
assert(p->n_ref > 0); \
p->n_ref--; \
if (p->n_ref > 0) \
return NULL; \
\
return free_func(p); \
}
#define DEFINE_TRIVIAL_REF_FUNC(type, name) \
_DEFINE_TRIVIAL_REF_FUNC(type, name,)
#define DEFINE_PRIVATE_TRIVIAL_REF_FUNC(type, name) \
_DEFINE_TRIVIAL_REF_FUNC(type, name, static)
#define DEFINE_PUBLIC_TRIVIAL_REF_FUNC(type, name) \
_DEFINE_TRIVIAL_REF_FUNC(type, name, _public_)
#define DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func) \
_DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func,)
#define DEFINE_PRIVATE_TRIVIAL_UNREF_FUNC(type, name, free_func) \
_DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func, static)
#define DEFINE_PUBLIC_TRIVIAL_UNREF_FUNC(type, name, free_func) \
_DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func, _public_)
#define DEFINE_TRIVIAL_REF_UNREF_FUNC(type, name, free_func) \
DEFINE_TRIVIAL_REF_FUNC(type, name); \
DEFINE_TRIVIAL_UNREF_FUNC(type, name, free_func);
#define DEFINE_PRIVATE_TRIVIAL_REF_UNREF_FUNC(type, name, free_func) \
DEFINE_PRIVATE_TRIVIAL_REF_FUNC(type, name); \
DEFINE_PRIVATE_TRIVIAL_UNREF_FUNC(type, name, free_func);
#define DEFINE_PUBLIC_TRIVIAL_REF_UNREF_FUNC(type, name, free_func) \
DEFINE_PUBLIC_TRIVIAL_REF_FUNC(type, name); \
DEFINE_PUBLIC_TRIVIAL_UNREF_FUNC(type, name, free_func);
/* A macro to force copying of a variable from memory. This is useful whenever we want to read something from
* memory and want to make sure the compiler won't optimize away the destination variable for us. It's not
* supposed to be a full CPU memory barrier, i.e. CPU is still allowed to reorder the reads, but it is not
* allowed to remove our local copies of the variables. We want this to work for unaligned memory, hence
* memcpy() is great for our purposes. */
#define READ_NOW(x) \
({ \
typeof(x) _copy; \
memcpy(&_copy, &(x), sizeof(_copy)); \
asm volatile ("" : : : "memory"); \
_copy; \
})
#define saturate_add(x, y, limit) \
({ \
typeof(limit) _x = (x); \
typeof(limit) _y = (y); \
_x > (limit) || _y >= (limit) - _x ? (limit) : _x + _y; \
})
static inline size_t size_add(size_t x, size_t y) {
return saturate_add(x, y, SIZE_MAX);
}
typedef struct {
int _empty[0];
} dummy_t;
assert_cc(sizeof(dummy_t) == 0);
/* A little helper for subtracting 1 off a pointer in a safe UB-free way. This is intended to be used for
* loops that count down from a high pointer until some base. A naive loop would implement this like this:
*
* for (p = end-1; p >= base; p--) …
*
* But this is not safe because p before the base is UB in C. With this macro the loop becomes this instead:
*
* for (p = PTR_SUB1(end, base); p; p = PTR_SUB1(p, base)) …
*
* And is free from UB! */
#define PTR_SUB1(p, base) \
({ \
typeof(p) _q = (p); \
_q && _q > (base) ? &_q[-1] : NULL; \
})
/* Iterate through each variadic arg. All must be the same type as 'entry' or must be implicitly
* convertible. The iteration variable 'entry' must already be defined. */
#define VA_ARGS_FOREACH(entry, ...) \
_VA_ARGS_FOREACH(entry, UNIQ_T(_entries_, UNIQ), UNIQ_T(_current_, UNIQ), ##__VA_ARGS__)
#define _VA_ARGS_FOREACH(entry, _entries_, _current_, ...) \
for (typeof(entry) _entries_[] = { __VA_ARGS__ }, *_current_ = _entries_; \
((long)(_current_ - _entries_) < (long)ELEMENTSOF(_entries_)) && ({ entry = *_current_; true; }); \
_current_++)
#include "log.h"
| 20,986 | 45.950783 | 130 | h |
null | systemd-main/src/basic/mallinfo-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <malloc.h>
#if HAVE_MALLINFO2
# define HAVE_GENERIC_MALLINFO 1
typedef struct mallinfo2 generic_mallinfo;
static inline generic_mallinfo generic_mallinfo_get(void) {
return mallinfo2();
}
#elif HAVE_MALLINFO
# define HAVE_GENERIC_MALLINFO 1
typedef struct mallinfo generic_mallinfo;
static inline generic_mallinfo generic_mallinfo_get(void) {
/* glibc has deprecated mallinfo(), let's suppress the deprecation warning if mallinfo2() doesn't
* exist yet. */
DISABLE_WARNING_DEPRECATED_DECLARATIONS
return mallinfo();
REENABLE_WARNING
}
#else
# define HAVE_GENERIC_MALLINFO 0
#endif
| 690 | 26.64 | 105 | h |
null | systemd-main/src/basic/math-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <math.h>
#include "macro.h"
/* On some optimization level, iszero(x) is converted to (x == 0.0), and emits warning -Wfloat-equal.
* The argument must be a floating point, i.e. one of float, double, or long double. */
#define iszero_safe(x) (fpclassify(x) == FP_ZERO)
/* To avoid x == y and triggering compile warning -Wfloat-equal. This returns false if one of the argument is
* NaN or infinity. One of the argument must be a floating point. */
#define fp_equal(x, y) iszero_safe((x) - (y))
| 568 | 36.933333 | 109 | h |
null | systemd-main/src/basic/memfd-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <sys/stat.h>
#include <unistd.h>
#if HAVE_LINUX_MEMFD_H
#include <linux/memfd.h>
#endif
#include <stdio.h>
#include <sys/prctl.h>
#include "alloc-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "macro.h"
#include "memfd-util.h"
#include "missing_fcntl.h"
#include "missing_mman.h"
#include "missing_syscall.h"
#include "string-util.h"
#include "utf8.h"
int memfd_create_wrapper(const char *name, unsigned mode) {
unsigned mode_compat;
int mfd;
mfd = RET_NERRNO(memfd_create(name, mode));
if (mfd != -EINVAL)
return mfd;
mode_compat = mode & ~(MFD_EXEC | MFD_NOEXEC_SEAL);
if (mode == mode_compat)
return mfd;
return RET_NERRNO(memfd_create(name, mode_compat));
}
int memfd_new(const char *name) {
_cleanup_free_ char *g = NULL;
if (!name) {
char pr[17] = {};
/* If no name is specified we generate one. We include
* a hint indicating our library implementation, and
* add the thread name to it */
assert_se(prctl(PR_GET_NAME, (unsigned long) pr) >= 0);
if (isempty(pr))
name = "sd";
else {
_cleanup_free_ char *e = NULL;
e = utf8_escape_invalid(pr);
if (!e)
return -ENOMEM;
g = strjoin("sd-", e);
if (!g)
return -ENOMEM;
name = g;
}
}
return memfd_create_wrapper(name, MFD_ALLOW_SEALING | MFD_CLOEXEC | MFD_NOEXEC_SEAL);
}
int memfd_map(int fd, uint64_t offset, size_t size, void **p) {
void *q;
int sealed;
assert(fd >= 0);
assert(size > 0);
assert(p);
sealed = memfd_get_sealed(fd);
if (sealed < 0)
return sealed;
if (sealed)
q = mmap(NULL, size, PROT_READ, MAP_PRIVATE, fd, offset);
else
q = mmap(NULL, size, PROT_READ | PROT_WRITE, MAP_SHARED, fd, offset);
if (q == MAP_FAILED)
return -errno;
*p = q;
return 0;
}
int memfd_set_sealed(int fd) {
int r;
assert(fd >= 0);
r = RET_NERRNO(fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_EXEC | F_SEAL_SEAL));
if (r == -EINVAL) /* old kernel ? */
r = RET_NERRNO(fcntl(fd, F_ADD_SEALS, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL));
return r;
}
int memfd_get_sealed(int fd) {
int r;
assert(fd >= 0);
r = fcntl(fd, F_GET_SEALS);
if (r < 0)
return -errno;
/* We ignore F_SEAL_EXEC here to support older kernels. */
return FLAGS_SET(r, F_SEAL_SHRINK | F_SEAL_GROW | F_SEAL_WRITE | F_SEAL_SEAL);
}
int memfd_get_size(int fd, uint64_t *sz) {
struct stat stat;
assert(fd >= 0);
assert(sz);
if (fstat(fd, &stat) < 0)
return -errno;
*sz = stat.st_size;
return 0;
}
int memfd_set_size(int fd, uint64_t sz) {
assert(fd >= 0);
return RET_NERRNO(ftruncate(fd, sz));
}
int memfd_new_and_map(const char *name, size_t sz, void **p) {
_cleanup_close_ int fd = -EBADF;
int r;
assert(sz > 0);
assert(p);
fd = memfd_new(name);
if (fd < 0)
return fd;
r = memfd_set_size(fd, sz);
if (r < 0)
return r;
r = memfd_map(fd, 0, sz, p);
if (r < 0)
return r;
return TAKE_FD(fd);
}
int memfd_new_and_seal(const char *name, const void *data, size_t sz) {
_cleanup_close_ int fd = -EBADF;
ssize_t n;
off_t f;
int r;
assert(data || sz == 0);
fd = memfd_new(name);
if (fd < 0)
return fd;
if (sz > 0) {
n = write(fd, data, sz);
if (n < 0)
return -errno;
if ((size_t) n != sz)
return -EIO;
f = lseek(fd, 0, SEEK_SET);
if (f != 0)
return -errno;
}
r = memfd_set_sealed(fd);
if (r < 0)
return r;
return TAKE_FD(fd);
}
| 4,563 | 23.021053 | 119 | c |
null | systemd-main/src/basic/memfd-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
int memfd_create_wrapper(const char *name, unsigned mode);
int memfd_new(const char *name);
int memfd_new_and_map(const char *name, size_t sz, void **p);
int memfd_new_and_seal(const char *name, const void *data, size_t sz);
int memfd_map(int fd, uint64_t offset, size_t size, void **p);
int memfd_set_sealed(int fd);
int memfd_get_sealed(int fd);
int memfd_get_size(int fd, uint64_t *sz);
int memfd_set_size(int fd, uint64_t sz);
| 584 | 25.590909 | 70 | h |
null | systemd-main/src/basic/memory-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <unistd.h>
#include "memory-util.h"
#include "missing_threads.h"
size_t page_size(void) {
static thread_local size_t pgsz = 0;
long r;
if (_likely_(pgsz > 0))
return pgsz;
r = sysconf(_SC_PAGESIZE);
assert(r > 0);
pgsz = (size_t) r;
return pgsz;
}
bool memeqbyte(uint8_t byte, const void *data, size_t length) {
/* Does the buffer consist entirely of the same specific byte value?
* Copied from https://github.com/systemd/casync/, copied in turn from
* https://github.com/rustyrussell/ccan/blob/master/ccan/mem/mem.c#L92,
* which is licensed CC-0.
*/
const uint8_t *p = data;
/* Check first 16 bytes manually */
for (size_t i = 0; i < 16; i++, length--) {
if (length == 0)
return true;
if (p[i] != byte)
return false;
}
/* Now we know first 16 bytes match, memcmp() with self. */
return memcmp(data, p + 16, length) == 0;
}
| 1,137 | 26.095238 | 79 | c |
null | systemd-main/src/basic/memory-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include <malloc.h>
#include <stdbool.h>
#include <string.h>
#include <sys/types.h>
#include "alloc-util.h"
#include "macro.h"
#include "memory-util-fundamental.h"
size_t page_size(void) _pure_;
#define PAGE_ALIGN(l) ALIGN_TO((l), page_size())
#define PAGE_ALIGN_DOWN(l) ((l) & ~(page_size() - 1))
#define PAGE_OFFSET(l) ((l) & (page_size() - 1))
/* Normal memcpy() requires src to be nonnull. We do nothing if n is 0. */
static inline void *memcpy_safe(void *dst, const void *src, size_t n) {
if (n == 0)
return dst;
assert(src);
return memcpy(dst, src, n);
}
/* Normal mempcpy() requires src to be nonnull. We do nothing if n is 0. */
static inline void *mempcpy_safe(void *dst, const void *src, size_t n) {
if (n == 0)
return dst;
assert(src);
return mempcpy(dst, src, n);
}
/* Normal memcmp() requires s1 and s2 to be nonnull. We do nothing if n is 0. */
static inline int memcmp_safe(const void *s1, const void *s2, size_t n) {
if (n == 0)
return 0;
assert(s1);
assert(s2);
return memcmp(s1, s2, n);
}
/* Compare s1 (length n1) with s2 (length n2) in lexicographic order. */
static inline int memcmp_nn(const void *s1, size_t n1, const void *s2, size_t n2) {
return memcmp_safe(s1, s2, MIN(n1, n2))
?: CMP(n1, n2);
}
#define memzero(x,l) \
({ \
size_t _l_ = (l); \
if (_l_ > 0) \
memset(x, 0, _l_); \
})
#define zero(x) (memzero(&(x), sizeof(x)))
bool memeqbyte(uint8_t byte, const void *data, size_t length);
#define memeqzero(data, length) memeqbyte(0x00, data, length)
#define eqzero(x) memeqzero(x, sizeof(x))
static inline void *mempset(void *s, int c, size_t n) {
memset(s, c, n);
return (uint8_t*)s + n;
}
/* Normal memmem() requires haystack to be nonnull, which is annoying for zero-length buffers */
static inline void *memmem_safe(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen) {
if (needlelen <= 0)
return (void*) haystack;
if (haystacklen < needlelen)
return NULL;
assert(haystack);
assert(needle);
return memmem(haystack, haystacklen, needle, needlelen);
}
static inline void *mempmem_safe(const void *haystack, size_t haystacklen, const void *needle, size_t needlelen) {
const uint8_t *p;
p = memmem_safe(haystack, haystacklen, needle, needlelen);
if (!p)
return NULL;
return (uint8_t*) p + needlelen;
}
static inline void* erase_and_free(void *p) {
size_t l;
if (!p)
return NULL;
l = MALLOC_SIZEOF_SAFE(p);
explicit_bzero_safe(p, l);
return mfree(p);
}
static inline void erase_and_freep(void *p) {
erase_and_free(*(void**) p);
}
/* Use with _cleanup_ to erase a single 'char' when leaving scope */
static inline void erase_char(char *p) {
explicit_bzero_safe(p, sizeof(char));
}
/* An automatic _cleanup_-like logic for destroy arrays (i.e. pointers + size) when leaving scope */
typedef struct ArrayCleanup {
void **parray;
size_t *pn;
free_array_func_t pfunc;
} ArrayCleanup;
static inline void array_cleanup(const ArrayCleanup *c) {
assert(c);
assert(!c->parray == !c->pn);
if (!c->parray)
return;
if (*c->parray) {
assert(c->pfunc);
c->pfunc(*c->parray, *c->pn);
*c->parray = NULL;
}
*c->pn = 0;
}
#define CLEANUP_ARRAY(array, n, func) \
_cleanup_(array_cleanup) _unused_ const ArrayCleanup CONCATENATE(_cleanup_array_, UNIQ) = { \
.parray = (void**) &(array), \
.pn = &(n), \
.pfunc = (free_array_func_t) ({ \
void (*_f)(typeof(array[0]) *a, size_t b) = func; \
_f; \
}), \
}
| 4,560 | 29.817568 | 114 | h |
null | systemd-main/src/basic/mempool.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdint.h>
#include <stdlib.h>
#include "format-util.h"
#include "macro.h"
#include "memory-util.h"
#include "mempool.h"
struct pool {
struct pool *next;
size_t n_tiles;
size_t n_used;
};
static void* pool_ptr(struct pool *p) {
return ((uint8_t*) ASSERT_PTR(p)) + ALIGN(sizeof(struct pool));
}
void* mempool_alloc_tile(struct mempool *mp) {
size_t i;
/* When a tile is released we add it to the list and simply
* place the next pointer at its offset 0. */
assert(mp);
assert(mp->tile_size >= sizeof(void*));
assert(mp->at_least > 0);
if (mp->freelist) {
void *t;
t = mp->freelist;
mp->freelist = *(void**) mp->freelist;
return t;
}
if (_unlikely_(!mp->first_pool) ||
_unlikely_(mp->first_pool->n_used >= mp->first_pool->n_tiles)) {
size_t size, n;
struct pool *p;
n = mp->first_pool ? mp->first_pool->n_tiles : 0;
n = MAX(mp->at_least, n * 2);
size = PAGE_ALIGN(ALIGN(sizeof(struct pool)) + n*mp->tile_size);
n = (size - ALIGN(sizeof(struct pool))) / mp->tile_size;
p = malloc(size);
if (!p)
return NULL;
p->next = mp->first_pool;
p->n_tiles = n;
p->n_used = 0;
mp->first_pool = p;
}
i = mp->first_pool->n_used++;
return (uint8_t*) pool_ptr(mp->first_pool) + i*mp->tile_size;
}
void* mempool_alloc0_tile(struct mempool *mp) {
void *p;
p = mempool_alloc_tile(mp);
if (p)
memzero(p, mp->tile_size);
return p;
}
void* mempool_free_tile(struct mempool *mp, void *p) {
assert(mp);
if (!p)
return NULL;
*(void**) p = mp->freelist;
mp->freelist = p;
return NULL;
}
static bool pool_contains(struct mempool *mp, struct pool *p, void *ptr) {
size_t off;
void *a;
assert(mp);
assert(p);
if (!ptr)
return false;
a = pool_ptr(p);
if ((uint8_t*) ptr < (uint8_t*) a)
return false;
off = (uint8_t*) ptr - (uint8_t*) a;
if (off >= mp->tile_size * p->n_tiles)
return false;
assert(off % mp->tile_size == 0);
return true;
}
static bool pool_is_unused(struct mempool *mp, struct pool *p) {
assert(mp);
assert(p);
if (p->n_used == 0)
return true;
/* Check if all tiles in this specific pool are in the freelist. */
size_t n = 0;
void *i = mp->freelist;
while (i) {
if (pool_contains(mp, p, i))
n++;
i = *(void**) i;
}
assert(n <= p->n_used);
return n == p->n_used;
}
static void pool_unlink(struct mempool *mp, struct pool *p) {
size_t m = 0;
assert(mp);
assert(p);
if (p->n_used == 0)
return;
void **i = &mp->freelist;
while (*i) {
void *d = *i;
if (pool_contains(mp, p, d)) {
*i = *(void**) d;
m++;
if (m == p->n_used)
break;
} else
i = (void**) d;
}
}
void mempool_trim(struct mempool *mp) {
size_t trimmed = 0, left = 0;
assert(mp);
struct pool **p = &mp->first_pool;
while (*p) {
struct pool *d = *p;
if (pool_is_unused(mp, d)) {
trimmed += d->n_tiles * mp->tile_size;
pool_unlink(mp, d);
*p = d->next;
free(d);
} else {
left += d->n_tiles * mp->tile_size;
p = &d->next;
}
}
log_debug("Trimmed %s from memory pool %p. (%s left)", FORMAT_BYTES(trimmed), mp, FORMAT_BYTES(left));
}
| 4,285 | 23.352273 | 110 | c |
null | systemd-main/src/basic/mempool.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stddef.h>
struct pool;
struct mempool {
struct pool *first_pool;
void *freelist;
size_t tile_size;
size_t at_least;
};
void* mempool_alloc_tile(struct mempool *mp);
void* mempool_alloc0_tile(struct mempool *mp);
void* mempool_free_tile(struct mempool *mp, void *p);
#define DEFINE_MEMPOOL(pool_name, tile_type, alloc_at_least) \
static struct mempool pool_name = { \
.tile_size = sizeof(tile_type), \
.at_least = alloc_at_least, \
}
__attribute__((weak)) bool mempool_enabled(void);
void mempool_trim(struct mempool *mp);
| 670 | 22.137931 | 62 | h |
null | systemd-main/src/basic/memstream-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "log.h"
#include "memstream-util.h"
void memstream_done(MemStream *m) {
assert(m);
/* First, close file stream, as the buffer may be reallocated on close. */
safe_fclose(m->f);
/* Then, free buffer. */
free(m->buf);
}
FILE* memstream_init(MemStream *m) {
assert(m);
assert(!m->f);
m->f = open_memstream_unlocked(&m->buf, &m->sz);
return m->f;
}
int memstream_finalize(MemStream *m, char **ret_buf, size_t *ret_size) {
int r;
assert(m);
assert(m->f);
assert(ret_buf);
/* Add terminating NUL, so that the output buffer is a valid string. */
fputc('\0', m->f);
r = fflush_and_check(m->f);
if (r < 0)
return r;
m->f = safe_fclose(m->f);
/* On fclose(), the buffer may be reallocated, and may trigger OOM. */
if (!m->buf)
return -ENOMEM;
assert(m->sz > 0);
*ret_buf = TAKE_PTR(m->buf);
if (ret_size)
*ret_size = m->sz - 1;
m->sz = 0; /* For safety when the MemStream object will be reused later. */
return 0;
}
int memstream_dump_internal(
int level,
int error,
const char *file,
int line,
const char *func,
MemStream *m) {
_cleanup_free_ char *buf = NULL;
int r;
assert(m);
r = memstream_finalize(m, &buf, NULL);
if (r < 0)
return log_full_errno(level, r, "Failed to flush memstream: %m: %m");
return log_dump_internal(level, error, file, line, func, buf);
}
| 1,806 | 22.776316 | 85 | c |
null | systemd-main/src/basic/memstream-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdio.h>
#include "macro.h"
typedef struct MemStream {
FILE *f;
char *buf;
size_t sz;
} MemStream;
void memstream_done(MemStream *m);
FILE* memstream_init(MemStream *m);
int memstream_finalize(MemStream *m, char **ret_buf, size_t *ret_size);
/* This finalizes the passed memstream. */
int memstream_dump_internal(
int level,
int error,
const char *file,
int line,
const char *func,
MemStream *m);
#define memstream_dump(level, m) \
memstream_dump_internal(level, 0, PROJECT_FILE, __LINE__, __func__, m)
| 747 | 25.714286 | 78 | h |
null | systemd-main/src/basic/missing_capability.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/capability.h>
/* 3a101b8de0d39403b2c7e5c23fd0b005668acf48 (3.16) */
#ifndef CAP_AUDIT_READ
# define CAP_AUDIT_READ 37
#endif
/* 980737282232b752bb14dab96d77665c15889c36 (5.8) */
#ifndef CAP_PERFMON
# define CAP_PERFMON 38
#endif
/* a17b53c4a4b55ec322c132b6670743612229ee9c (5.8) */
#ifndef CAP_BPF
# define CAP_BPF 39
#endif
/* 124ea650d3072b005457faed69909221c2905a1f (5.9) */
#ifndef CAP_CHECKPOINT_RESTORE
# define CAP_CHECKPOINT_RESTORE 40
#endif
#define SYSTEMD_CAP_LAST_CAP CAP_CHECKPOINT_RESTORE
#ifdef CAP_LAST_CAP
# if CAP_LAST_CAP > SYSTEMD_CAP_LAST_CAP
# if BUILD_MODE_DEVELOPER && defined(TEST_CAPABILITY_C)
# warning "The capability list here is outdated"
# endif
# else
# undef CAP_LAST_CAP
# endif
#endif
#ifndef CAP_LAST_CAP
# define CAP_LAST_CAP SYSTEMD_CAP_LAST_CAP
#endif
| 898 | 21.475 | 58 | h |
null | systemd-main/src/basic/missing_fcntl.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <fcntl.h>
#ifndef F_LINUX_SPECIFIC_BASE
#define F_LINUX_SPECIFIC_BASE 1024
#endif
#ifndef F_SETPIPE_SZ
#define F_SETPIPE_SZ (F_LINUX_SPECIFIC_BASE + 7)
#endif
#ifndef F_GETPIPE_SZ
#define F_GETPIPE_SZ (F_LINUX_SPECIFIC_BASE + 8)
#endif
#ifndef F_ADD_SEALS
#define F_ADD_SEALS (F_LINUX_SPECIFIC_BASE + 9)
#define F_GET_SEALS (F_LINUX_SPECIFIC_BASE + 10)
#define F_SEAL_SEAL 0x0001 /* prevent further seals from being set */
#define F_SEAL_SHRINK 0x0002 /* prevent file from shrinking */
#define F_SEAL_GROW 0x0004 /* prevent file from growing */
#define F_SEAL_WRITE 0x0008 /* prevent writes */
#endif
#ifndef F_SEAL_FUTURE_WRITE
#define F_SEAL_FUTURE_WRITE 0x0010 /* prevent future writes while mapped */
#endif
#ifndef F_SEAL_EXEC
#define F_SEAL_EXEC 0x0020 /* prevent chmod modifying exec bits */
#endif
#ifndef F_OFD_GETLK
#define F_OFD_GETLK 36
#define F_OFD_SETLK 37
#define F_OFD_SETLKW 38
#endif
#ifndef MAX_HANDLE_SZ
#define MAX_HANDLE_SZ 128
#endif
/* The precise definition of __O_TMPFILE is arch specific; use the
* values defined by the kernel (note: some are hexa, some are octal,
* duplicated as-is from the kernel definitions):
* - alpha, parisc, sparc: each has a specific value;
* - others: they use the "generic" value.
*/
#ifndef __O_TMPFILE
#if defined(__alpha__)
#define __O_TMPFILE 0100000000
#elif defined(__parisc__) || defined(__hppa__)
#define __O_TMPFILE 0400000000
#elif defined(__sparc__) || defined(__sparc64__)
#define __O_TMPFILE 0x2000000
#else
#define __O_TMPFILE 020000000
#endif
#endif
/* a horrid kludge trying to make sure that this will fail on old kernels */
#ifndef O_TMPFILE
#define O_TMPFILE (__O_TMPFILE | O_DIRECTORY)
#endif
/* So O_LARGEFILE is generally implied by glibc, and defined to zero hence, because we only build in LFS
* mode. However, when invoking fcntl(F_GETFL) the flag is ORed into the result anyway — glibc does not mask
* it away. Which sucks. Let's define the actual value here, so that we can mask it ourselves. */
#if O_LARGEFILE != 0
#define RAW_O_LARGEFILE O_LARGEFILE
#else
#define RAW_O_LARGEFILE 0100000
#endif
| 2,223 | 27.512821 | 108 | h |
null | systemd-main/src/basic/missing_input.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/input.h>
#include <linux/types.h>
/* linux@c7dc65737c9a607d3e6f8478659876074ad129b8 (3.12) */
#ifndef EVIOCREVOKE
#define EVIOCREVOKE _IOW('E', 0x91, int)
#endif
/* linux@06a16293f71927f756dcf37558a79c0b05a91641 (4.4) */
#ifndef EVIOCSMASK
struct input_mask {
__u32 type;
__u32 codes_size;
__u64 codes_ptr;
};
#define EVIOCGMASK _IOR('E', 0x92, struct input_mask)
#define EVIOCSMASK _IOW('E', 0x93, struct input_mask)
#endif
/* linux@7611392fe8ff95ecae528b01a815ae3d72ca6b95 (3.17) */
#ifndef INPUT_PROP_POINTING_STICK
#define INPUT_PROP_POINTING_STICK 0x05
#endif
/* linux@500d4160abe9a2e88b12e319c13ae3ebd1e18108 (4.0) */
#ifndef INPUT_PROP_ACCELEROMETER
#define INPUT_PROP_ACCELEROMETER 0x06
#endif
/* linux@d09bbfd2a8408a995419dff0d2ba906013cf4cc9 (3.11) */
#ifndef BTN_DPAD_UP
#define BTN_DPAD_UP 0x220
#define BTN_DPAD_DOWN 0x221
#define BTN_DPAD_LEFT 0x222
#define BTN_DPAD_RIGHT 0x223
#endif
/* linux@358f24704f2f016af7d504b357cdf32606091d07 (3.13) */
#ifndef KEY_ALS_TOGGLE
#define KEY_ALS_TOGGLE 0x230
#endif
| 1,135 | 23.695652 | 59 | h |
null | systemd-main/src/basic/missing_keyctl.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include <linux/keyctl.h>
#ifndef KEYCTL_JOIN_SESSION_KEYRING
#define KEYCTL_JOIN_SESSION_KEYRING 1
#endif
#ifndef KEYCTL_CHOWN
#define KEYCTL_CHOWN 4
#endif
#ifndef KEYCTL_SETPERM
#define KEYCTL_SETPERM 5
#endif
#ifndef KEYCTL_DESCRIBE
#define KEYCTL_DESCRIBE 6
#endif
#ifndef KEYCTL_LINK
#define KEYCTL_LINK 8
#endif
#ifndef KEYCTL_READ
#define KEYCTL_READ 11
#endif
#ifndef KEYCTL_SET_TIMEOUT
#define KEYCTL_SET_TIMEOUT 15
#endif
#ifndef KEY_SPEC_USER_KEYRING
#define KEY_SPEC_USER_KEYRING -4
#endif
#ifndef KEY_SPEC_SESSION_KEYRING
#define KEY_SPEC_SESSION_KEYRING -3
#endif
/* From linux/key.h */
#ifndef KEY_POS_VIEW
typedef int32_t key_serial_t;
#define KEY_POS_VIEW 0x01000000
#define KEY_POS_READ 0x02000000
#define KEY_POS_WRITE 0x04000000
#define KEY_POS_SEARCH 0x08000000
#define KEY_POS_LINK 0x10000000
#define KEY_POS_SETATTR 0x20000000
#define KEY_POS_ALL 0x3f000000
#define KEY_USR_VIEW 0x00010000
#define KEY_USR_READ 0x00020000
#define KEY_USR_WRITE 0x00040000
#define KEY_USR_SEARCH 0x00080000
#define KEY_USR_LINK 0x00100000
#define KEY_USR_SETATTR 0x00200000
#define KEY_USR_ALL 0x003f0000
#define KEY_GRP_VIEW 0x00000100
#define KEY_GRP_READ 0x00000200
#define KEY_GRP_WRITE 0x00000400
#define KEY_GRP_SEARCH 0x00000800
#define KEY_GRP_LINK 0x00001000
#define KEY_GRP_SETATTR 0x00002000
#define KEY_GRP_ALL 0x00003f00
#define KEY_OTH_VIEW 0x00000001
#define KEY_OTH_READ 0x00000002
#define KEY_OTH_WRITE 0x00000004
#define KEY_OTH_SEARCH 0x00000008
#define KEY_OTH_LINK 0x00000010
#define KEY_OTH_SETATTR 0x00000020
#define KEY_OTH_ALL 0x0000003f
#endif
| 1,740 | 20.7625 | 48 | h |
null | systemd-main/src/basic/missing_loop.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/loop.h>
#ifndef LOOP_CONFIGURE
struct loop_config {
__u32 fd;
__u32 block_size;
struct loop_info64 info;
__u64 __reserved[8];
};
#define LOOP_CONFIGURE 0x4C0A
#endif
#ifndef LO_FLAGS_DIRECT_IO
#define LO_FLAGS_DIRECT_IO 16
#define LOOP_SET_DIRECT_IO 0x4C08
#endif
#ifndef LOOP_SET_STATUS_SETTABLE_FLAGS
#define LOOP_SET_STATUS_SETTABLE_FLAGS (LO_FLAGS_AUTOCLEAR | LO_FLAGS_PARTSCAN | LO_FLAGS_DIRECT_IO)
#endif
| 526 | 20.08 | 100 | h |
null | systemd-main/src/basic/missing_magic.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/magic.h>
/* 62aa81d7c4c24b90fdb61da70ac0dbbc414f9939 (4.13) */
#ifndef OCFS2_SUPER_MAGIC
#define OCFS2_SUPER_MAGIC 0x7461636f
#endif
/* 67e9c74b8a873408c27ac9a8e4c1d1c8d72c93ff (4.5) */
#ifndef CGROUP2_SUPER_MAGIC
#define CGROUP2_SUPER_MAGIC 0x63677270
#endif
/* 4282d60689d4f21b40692029080440cc58e8a17d (4.1) */
#ifndef TRACEFS_MAGIC
#define TRACEFS_MAGIC 0x74726163
#endif
/* e149ed2b805fefdccf7ccdfc19eca22fdd4514ac (3.19) */
#ifndef NSFS_MAGIC
#define NSFS_MAGIC 0x6e736673
#endif
/* b2197755b2633e164a439682fb05a9b5ea48f706 (4.4) */
#ifndef BPF_FS_MAGIC
#define BPF_FS_MAGIC 0xcafe4a11
#endif
/* Not exposed yet (4.20). Defined at ipc/mqueue.c */
#ifndef MQUEUE_MAGIC
#define MQUEUE_MAGIC 0x19800202
#endif
/* Not exposed yet (as of Linux 5.4). Defined in fs/xfs/libxfs/xfs_format.h */
#ifndef XFS_SB_MAGIC
#define XFS_SB_MAGIC 0x58465342
#endif
/* dea2903719283c156b53741126228c4a1b40440f (5.17) */
#ifndef CIFS_SUPER_MAGIC
#define CIFS_SUPER_MAGIC 0xFF534D42
#endif
/* dea2903719283c156b53741126228c4a1b40440f (5.17) */
#ifndef SMB2_SUPER_MAGIC
#define SMB2_SUPER_MAGIC 0xFE534D42
#endif
/* 257f871993474e2bde6c497b54022c362cf398e1 (4.5) */
#ifndef OVERLAYFS_SUPER_MAGIC
#define OVERLAYFS_SUPER_MAGIC 0x794c7630
#endif
/* 2a28900be20640fcd1e548b1e3bad79e8221fcf9 (4.7) */
#ifndef UDF_SUPER_MAGIC
#define UDF_SUPER_MAGIC 0x15013346
#endif
/* b1123ea6d3b3da25af5c8a9d843bd07ab63213f4 (4.8) */
#ifndef BALLOON_KVM_MAGIC
#define BALLOON_KVM_MAGIC 0x13661366
#endif
/* 48b4800a1c6af2cdda344ea4e2c843dcc1f6afc9 (4.8) */
#ifndef ZSMALLOC_MAGIC
#define ZSMALLOC_MAGIC 0x58295829
#endif
/* 3bc52c45bac26bf7ed1dc8d287ad1aeaed1250b6 (4.9) */
#ifndef DAXFS_MAGIC
#define DAXFS_MAGIC 0x64646178
#endif
/* 5ff193fbde20df5d80fec367cea3e7856c057320 (4.10) */
#ifndef RDTGROUP_SUPER_MAGIC
#define RDTGROUP_SUPER_MAGIC 0x7655821
#endif
/* a481f4d917835cad86701fc0d1e620c74bb5cd5f (4.13) */
#ifndef AAFS_MAGIC
#define AAFS_MAGIC 0x5a3c69f0
#endif
/* f044c8847bb61eff5e1e95b6f6bb950e7f4a73a4 (4.15) */
#ifndef AFS_FS_MAGIC
#define AFS_FS_MAGIC 0x6b414653
#endif
/* dddde68b8f06dd83486124b8d245e7bfb15c185d (4.20) */
#ifndef XFS_SUPER_MAGIC
#define XFS_SUPER_MAGIC 0x58465342
#endif
/* 3ad20fe393b31025bebfc2d76964561f65df48aa (5.0) */
#ifndef BINDERFS_SUPER_MAGIC
#define BINDERFS_SUPER_MAGIC 0x6c6f6f70
#endif
/* ed63bb1d1f8469586006a9ca63c42344401aa2ab (5.3) */
#ifndef DMA_BUF_MAGIC
#define DMA_BUF_MAGIC 0x444d4142
#endif
/* ea8157ab2ae5e914dd427e5cfab533b6da3819cd (5.3) */
#ifndef Z3FOLD_MAGIC
#define Z3FOLD_MAGIC 0x33
#endif
/* 47e4937a4a7ca4184fd282791dfee76c6799966a (5.4) */
#ifndef EROFS_SUPER_MAGIC_V1
#define EROFS_SUPER_MAGIC_V1 0xe0f5e1e2
#endif
/* fe030c9b85e6783bc52fe86449c0a4b8aa16c753 (5.5) */
#ifndef PPC_CMM_MAGIC
#define PPC_CMM_MAGIC 0xc7571590
#endif
/* 8dcc1a9d90c10fa4143e5c17821082e5e60e46a1 (5.6) */
#ifndef ZONEFS_MAGIC
#define ZONEFS_MAGIC 0x5a4f4653
#endif
/* 3234ac664a870e6ea69ae3a57d824cd7edbeacc5 (5.8) */
#ifndef DEVMEM_MAGIC
#define DEVMEM_MAGIC 0x454d444d
#endif
/* Not in mainline but included in Ubuntu */
#ifndef SHIFTFS_MAGIC
#define SHIFTFS_MAGIC 0x6a656a62
#endif
/* 1507f51255c9ff07d75909a84e7c0d7f3c4b2f49 (5.14) */
#ifndef SECRETMEM_MAGIC
#define SECRETMEM_MAGIC 0x5345434d
#endif
/* Not exposed yet. Defined at fs/fuse/inode.c */
#ifndef FUSE_SUPER_MAGIC
#define FUSE_SUPER_MAGIC 0x65735546
#endif
/* Not exposed yet. Defined at fs/fuse/control.c */
#ifndef FUSE_CTL_SUPER_MAGIC
#define FUSE_CTL_SUPER_MAGIC 0x65735543
#endif
/* Not exposed yet. Defined at fs/ceph/super.h */
#ifndef CEPH_SUPER_MAGIC
#define CEPH_SUPER_MAGIC 0x00c36400
#endif
/* Not exposed yet. Defined at fs/orangefs/orangefs-kernel.h */
#ifndef ORANGEFS_DEVREQ_MAGIC
#define ORANGEFS_DEVREQ_MAGIC 0x20030529
#endif
/* linux/gfs2_ondisk.h */
#ifndef GFS2_MAGIC
#define GFS2_MAGIC 0x01161970
#endif
/* Not exposed yet. Defined at fs/configfs/mount.c */
#ifndef CONFIGFS_MAGIC
#define CONFIGFS_MAGIC 0x62656570
#endif
/* Not exposed yet. Defined at fs/vboxsf/super.c */
#ifndef VBOXSF_SUPER_MAGIC
#define VBOXSF_SUPER_MAGIC 0x786f4256
#endif
/* Not exposed yet. Defined at fs/exfat/exfat_fs.h */
#ifndef EXFAT_SUPER_MAGIC
#define EXFAT_SUPER_MAGIC 0x2011BAB0UL
#endif
/* Not exposed yet, internally actually called RPCAUTH_GSSMAGIC. Defined in net/sunrpc/rpc_pipe.c */
#ifndef RPC_PIPEFS_SUPER_MAGIC
#define RPC_PIPEFS_SUPER_MAGIC 0x67596969
#endif
/* Not exposed yet, defined at fs/ntfs/ntfs.h */
#ifndef NTFS_SB_MAGIC
#define NTFS_SB_MAGIC 0x5346544e
#endif
/* Not exposed yet, encoded literally in fs/ntfs3/super.c. */
#ifndef NTFS3_SUPER_MAGIC
#define NTFS3_SUPER_MAGIC 0x7366746e
#endif
| 4,714 | 23.179487 | 100 | h |
null | systemd-main/src/basic/missing_network.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/* linux/in6.h or netinet/in.h */
#ifndef IPV6_UNICAST_IF
#define IPV6_UNICAST_IF 76
#endif
/* linux/in6.h or netinet/in.h */
#ifndef IPV6_TRANSPARENT
#define IPV6_TRANSPARENT 75
#endif
/* Not exposed but defined at include/net/ip.h */
#ifndef IPV4_MIN_MTU
#define IPV4_MIN_MTU 68
#endif
/* linux/ipv6.h */
#ifndef IPV6_MIN_MTU
#define IPV6_MIN_MTU 1280
#endif
/* Note that LOOPBACK_IFINDEX is currently not exposed by the
* kernel/glibc, but hardcoded internally by the kernel. However, as
* it is exported to userspace indirectly via rtnetlink and the
* ioctls, and made use of widely we define it here too, in a way that
* is compatible with the kernel's internal definition. */
#ifndef LOOPBACK_IFINDEX
#define LOOPBACK_IFINDEX 1
#endif
/* Not exposed yet. Similar values are defined in net/ethernet.h */
#ifndef ETHERTYPE_LLDP
#define ETHERTYPE_LLDP 0x88cc
#endif
/* Not exposed but defined in linux/netdevice.h */
#ifndef MAX_PHYS_ITEM_ID_LEN
#define MAX_PHYS_ITEM_ID_LEN 32
#endif
/* Not exposed but defined in include/net/bonding.h */
#ifndef BOND_MAX_ARP_TARGETS
#define BOND_MAX_ARP_TARGETS 16
#endif
/* Not exposed but defined in include/linux/ieee80211.h */
#ifndef IEEE80211_MAX_SSID_LEN
#define IEEE80211_MAX_SSID_LEN 32
#endif
/* Not exposed but defined in include/net/netlabel.h */
#ifndef NETLBL_NLTYPE_UNLABELED_NAME
#define NETLBL_NLTYPE_UNLABELED_NAME "NLBL_UNLBL"
#endif
/* Not exposed but defined in net/netlabel/netlabel_unlabeled.h */
enum {
NLBL_UNLABEL_C_UNSPEC,
NLBL_UNLABEL_C_ACCEPT,
NLBL_UNLABEL_C_LIST,
NLBL_UNLABEL_C_STATICADD,
NLBL_UNLABEL_C_STATICREMOVE,
NLBL_UNLABEL_C_STATICLIST,
NLBL_UNLABEL_C_STATICADDDEF,
NLBL_UNLABEL_C_STATICREMOVEDEF,
NLBL_UNLABEL_C_STATICLISTDEF,
__NLBL_UNLABEL_C_MAX,
};
/* Not exposed but defined in net/netlabel/netlabel_unlabeled.h */
enum {
NLBL_UNLABEL_A_UNSPEC,
NLBL_UNLABEL_A_ACPTFLG,
NLBL_UNLABEL_A_IPV6ADDR,
NLBL_UNLABEL_A_IPV6MASK,
NLBL_UNLABEL_A_IPV4ADDR,
NLBL_UNLABEL_A_IPV4MASK,
NLBL_UNLABEL_A_IFACE,
NLBL_UNLABEL_A_SECCTX,
__NLBL_UNLABEL_A_MAX,
};
| 2,253 | 25.833333 | 70 | h |
null | systemd-main/src/basic/missing_prctl.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/prctl.h>
/* 58319057b7847667f0c9585b9de0e8932b0fdb08 (4.3) */
#ifndef PR_CAP_AMBIENT
#define PR_CAP_AMBIENT 47
#define PR_CAP_AMBIENT_IS_SET 1
#define PR_CAP_AMBIENT_RAISE 2
#define PR_CAP_AMBIENT_LOWER 3
#define PR_CAP_AMBIENT_CLEAR_ALL 4
#endif
/* b507808ebce23561d4ff8c2aa1fb949fe402bc61 (6.3) */
#ifndef PR_SET_MDWE
#define PR_SET_MDWE 65
#endif
#ifndef PR_MDWE_REFUSE_EXEC_GAIN
#define PR_MDWE_REFUSE_EXEC_GAIN 1
#endif
#ifndef PR_SET_MEMORY_MERGE
#define PR_SET_MEMORY_MERGE 67
#endif
| 585 | 20.703704 | 52 | h |
null | systemd-main/src/basic/missing_sched.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sched.h>
#ifndef CLONE_NEWCGROUP
#define CLONE_NEWCGROUP 0x02000000
#endif
/* 769071ac9f20b6a447410c7eaa55d1a5233ef40c (5.8) */
#ifndef CLONE_NEWTIME
#define CLONE_NEWTIME 0x00000080
#endif
/* Not exposed yet. Defined at include/linux/sched.h */
#ifndef PF_KTHREAD
#define PF_KTHREAD 0x00200000
#endif
/* The maximum thread/process name length including trailing NUL byte. This mimics the kernel definition of the same
* name, which we need in userspace at various places but is not defined in userspace currently, neither under this
* name nor any other. */
/* Not exposed yet. Defined at include/linux/sched.h */
#ifndef TASK_COMM_LEN
#define TASK_COMM_LEN 16
#endif
| 748 | 26.740741 | 116 | h |
null | systemd-main/src/basic/missing_securebits.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/securebits.h>
/* 746bf6d64275be0c65b0631d8a72b16f1454cfa1 (4.3) */
#ifndef SECURE_NO_CAP_AMBIENT_RAISE
#define SECURE_NO_CAP_AMBIENT_RAISE 6
#define SECURE_NO_CAP_AMBIENT_RAISE_LOCKED 7 /* make bit-6 immutable */
#define SECBIT_NO_CAP_AMBIENT_RAISE (issecure_mask(SECURE_NO_CAP_AMBIENT_RAISE))
#define SECBIT_NO_CAP_AMBIENT_RAISE_LOCKED (issecure_mask(SECURE_NO_CAP_AMBIENT_RAISE_LOCKED))
#undef SECURE_ALL_BITS
#define SECURE_ALL_BITS (issecure_mask(SECURE_NOROOT) | \
issecure_mask(SECURE_NO_SETUID_FIXUP) | \
issecure_mask(SECURE_KEEP_CAPS) | \
issecure_mask(SECURE_NO_CAP_AMBIENT_RAISE))
#endif
| 807 | 41.526316 | 94 | h |
null | systemd-main/src/basic/missing_stat.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/types.h>
#include <sys/stat.h>
#if WANT_LINUX_STAT_H
#include <linux/stat.h>
#endif
/* Thew newest definition we are aware of (fa2fcf4f1df1559a0a4ee0f46915b496cc2ebf60; 5.8) */
#define STATX_DEFINITION { \
__u32 stx_mask; \
__u32 stx_blksize; \
__u64 stx_attributes; \
__u32 stx_nlink; \
__u32 stx_uid; \
__u32 stx_gid; \
__u16 stx_mode; \
__u16 __spare0[1]; \
__u64 stx_ino; \
__u64 stx_size; \
__u64 stx_blocks; \
__u64 stx_attributes_mask; \
struct statx_timestamp stx_atime; \
struct statx_timestamp stx_btime; \
struct statx_timestamp stx_ctime; \
struct statx_timestamp stx_mtime; \
__u32 stx_rdev_major; \
__u32 stx_rdev_minor; \
__u32 stx_dev_major; \
__u32 stx_dev_minor; \
__u64 stx_mnt_id; \
__u64 __spare2; \
__u64 __spare3[12]; \
}
#if !HAVE_STRUCT_STATX
struct statx_timestamp {
__s64 tv_sec;
__u32 tv_nsec;
__s32 __reserved;
};
struct statx STATX_DEFINITION;
#endif
/* Always define the newest version we are aware of as a distinct type, so that we can use it even if glibc
* defines an older definition */
struct new_statx STATX_DEFINITION;
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef AT_STATX_SYNC_AS_STAT
#define AT_STATX_SYNC_AS_STAT 0x0000
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef AT_STATX_FORCE_SYNC
#define AT_STATX_FORCE_SYNC 0x2000
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef AT_STATX_DONT_SYNC
#define AT_STATX_DONT_SYNC 0x4000
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_TYPE
#define STATX_TYPE 0x00000001U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_MODE
#define STATX_MODE 0x00000002U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_NLINK
#define STATX_NLINK 0x00000004U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_UID
#define STATX_UID 0x00000008U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_GID
#define STATX_GID 0x00000010U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_ATIME
#define STATX_ATIME 0x00000020U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_MTIME
#define STATX_MTIME 0x00000040U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_CTIME
#define STATX_CTIME 0x00000080U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_INO
#define STATX_INO 0x00000100U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_SIZE
#define STATX_SIZE 0x00000200U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_BLOCKS
#define STATX_BLOCKS 0x00000400U
#endif
/* a528d35e8bfcc521d7cb70aaf03e1bd296c8493f (4.11) */
#ifndef STATX_BTIME
#define STATX_BTIME 0x00000800U
#endif
/* fa2fcf4f1df1559a0a4ee0f46915b496cc2ebf60 (5.8) */
#ifndef STATX_MNT_ID
#define STATX_MNT_ID 0x00001000U
#endif
/* 80340fe3605c0e78cfe496c3b3878be828cfdbfe (5.8) */
#ifndef STATX_ATTR_MOUNT_ROOT
#define STATX_ATTR_MOUNT_ROOT 0x00002000 /* Root of a mount */
#endif
| 3,798 | 26.933824 | 107 | h |
null | systemd-main/src/basic/missing_xfs.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/* This is currently not exported in the public kernel headers, but the libxfs library code part of xfsprogs
* defines it as public header */
#ifndef XFS_IOC_FSGEOMETRY
#define XFS_IOC_FSGEOMETRY _IOR ('X', 124, struct xfs_fsop_geom)
typedef struct xfs_fsop_geom {
uint32_t blocksize;
uint32_t rtextsize;
uint32_t agblocks;
uint32_t agcount;
uint32_t logblocks;
uint32_t sectsize;
uint32_t inodesize;
uint32_t imaxpct;
uint64_t datablocks;
uint64_t rtblocks;
uint64_t rtextents;
uint64_t logstart;
unsigned char uuid[16];
uint32_t sunit;
uint32_t swidth;
int32_t version;
uint32_t flags;
uint32_t logsectsize;
uint32_t rtsectsize;
uint32_t dirblocksize;
uint32_t logsunit;
} xfs_fsop_geom_t;
#endif
#ifndef XFS_IOC_FSGROWFSDATA
#define XFS_IOC_FSGROWFSDATA _IOW ('X', 110, struct xfs_growfs_data)
typedef struct xfs_growfs_data {
uint64_t newblocks;
uint32_t imaxpct;
} xfs_growfs_data_t;
#endif
| 1,148 | 25.72093 | 108 | h |
null | systemd-main/src/basic/mountpoint-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <fcntl.h>
#include <stdbool.h>
#include <sys/types.h>
/* The limit used for /dev itself. 4MB should be enough since device nodes and symlinks don't
* consume any space and udev isn't supposed to create regular file either. There's no limit on the
* max number of inodes since such limit is hard to guess especially on large storage array
* systems. */
#define TMPFS_LIMITS_DEV ",size=4m"
/* The limit used for /dev in private namespaces. 4MB for contents of regular files. The number of
* inodes should be relatively low in private namespaces but for now use a 64k limit. */
#define TMPFS_LIMITS_PRIVATE_DEV ",size=4m,nr_inodes=64k"
/* Very little, if any use expected */
#define TMPFS_LIMITS_EMPTY_OR_ALMOST ",size=4m,nr_inodes=1k"
#define TMPFS_LIMITS_SYS TMPFS_LIMITS_EMPTY_OR_ALMOST
#define TMPFS_LIMITS_SYS_FS_CGROUP TMPFS_LIMITS_EMPTY_OR_ALMOST
/* On an extremely small device with only 256MB of RAM, 20% of RAM should be enough for the re-execution of
* PID1 because 16MB of free space is required. */
#define TMPFS_LIMITS_RUN ",size=20%,nr_inodes=800k"
/* The limit used for various nested tmpfs mounts, in particular for guests started by systemd-nspawn.
* 10% of RAM (using 16GB of RAM as a baseline) translates to 400k inodes (assuming 4k each) and 25%
* translates to 1M inodes.
* (On the host, /tmp is configured through a .mount unit file.) */
#define NESTED_TMPFS_LIMITS ",size=10%,nr_inodes=400k"
/* More space for volatile root and /var */
#define TMPFS_LIMITS_VAR ",size=25%,nr_inodes=1m"
#define TMPFS_LIMITS_ROOTFS TMPFS_LIMITS_VAR
#define TMPFS_LIMITS_VOLATILE_STATE TMPFS_LIMITS_VAR
int name_to_handle_at_loop(int fd, const char *path, struct file_handle **ret_handle, int *ret_mnt_id, int flags);
int path_get_mnt_id_at(int dir_fd, const char *path, int *ret);
static inline int path_get_mnt_id(const char *path, int *ret) {
return path_get_mnt_id_at(AT_FDCWD, path, ret);
}
int fd_is_mount_point(int fd, const char *filename, int flags);
int path_is_mount_point(const char *path, const char *root, int flags);
bool fstype_is_network(const char *fstype);
bool fstype_needs_quota(const char *fstype);
bool fstype_is_api_vfs(const char *fstype);
bool fstype_is_blockdev_backed(const char *fstype);
bool fstype_is_ro(const char *fsype);
bool fstype_can_discard(const char *fstype);
bool fstype_can_uid_gid(const char *fstype);
bool fstype_can_norecovery(const char *fstype);
bool fstype_can_umask(const char *fstype);
int dev_is_devtmpfs(void);
int mount_fd(const char *source, int target_fd, const char *filesystemtype, unsigned long mountflags, const void *data);
int mount_nofollow(const char *source, const char *target, const char *filesystemtype, unsigned long mountflags, const void *data);
const char *mount_propagation_flag_to_string(unsigned long flags);
int mount_propagation_flag_from_string(const char *name, unsigned long *ret);
bool mount_propagation_flag_is_valid(unsigned long flag);
unsigned long ms_nosymfollow_supported(void);
int mount_option_supported(const char *fstype, const char *key, const char *value);
| 3,227 | 45.114286 | 131 | h |
null | systemd-main/src/basic/namespace-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <sys/ioctl.h>
#include <sys/mount.h>
#include "errno-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "missing_fs.h"
#include "missing_magic.h"
#include "missing_sched.h"
#include "namespace-util.h"
#include "process-util.h"
#include "stat-util.h"
#include "stdio-util.h"
#include "user-util.h"
const struct namespace_info namespace_info[] = {
[NAMESPACE_CGROUP] = { "cgroup", "ns/cgroup", CLONE_NEWCGROUP, },
[NAMESPACE_IPC] = { "ipc", "ns/ipc", CLONE_NEWIPC, },
[NAMESPACE_NET] = { "net", "ns/net", CLONE_NEWNET, },
/* So, the mount namespace flag is called CLONE_NEWNS for historical
* reasons. Let's expose it here under a more explanatory name: "mnt".
* This is in-line with how the kernel exposes namespaces in /proc/$PID/ns. */
[NAMESPACE_MOUNT] = { "mnt", "ns/mnt", CLONE_NEWNS, },
[NAMESPACE_PID] = { "pid", "ns/pid", CLONE_NEWPID, },
[NAMESPACE_USER] = { "user", "ns/user", CLONE_NEWUSER, },
[NAMESPACE_UTS] = { "uts", "ns/uts", CLONE_NEWUTS, },
[NAMESPACE_TIME] = { "time", "ns/time", CLONE_NEWTIME, },
{ /* Allow callers to iterate over the array without using _NAMESPACE_TYPE_MAX. */ },
};
#define pid_namespace_path(pid, type) procfs_file_alloca(pid, namespace_info[type].proc_path)
int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *userns_fd, int *root_fd) {
_cleanup_close_ int pidnsfd = -EBADF, mntnsfd = -EBADF, netnsfd = -EBADF, usernsfd = -EBADF;
int rfd = -EBADF;
assert(pid >= 0);
if (mntns_fd) {
const char *mntns;
mntns = pid_namespace_path(pid, NAMESPACE_MOUNT);
mntnsfd = open(mntns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
if (mntnsfd < 0)
return -errno;
}
if (pidns_fd) {
const char *pidns;
pidns = pid_namespace_path(pid, NAMESPACE_PID);
pidnsfd = open(pidns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
if (pidnsfd < 0)
return -errno;
}
if (netns_fd) {
const char *netns;
netns = pid_namespace_path(pid, NAMESPACE_NET);
netnsfd = open(netns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
if (netnsfd < 0)
return -errno;
}
if (userns_fd) {
const char *userns;
userns = pid_namespace_path(pid, NAMESPACE_USER);
usernsfd = open(userns, O_RDONLY|O_NOCTTY|O_CLOEXEC);
if (usernsfd < 0 && errno != ENOENT)
return -errno;
}
if (root_fd) {
const char *root;
root = procfs_file_alloca(pid, "root");
rfd = open(root, O_RDONLY|O_NOCTTY|O_CLOEXEC|O_DIRECTORY);
if (rfd < 0)
return -errno;
}
if (pidns_fd)
*pidns_fd = TAKE_FD(pidnsfd);
if (mntns_fd)
*mntns_fd = TAKE_FD(mntnsfd);
if (netns_fd)
*netns_fd = TAKE_FD(netnsfd);
if (userns_fd)
*userns_fd = TAKE_FD(usernsfd);
if (root_fd)
*root_fd = TAKE_FD(rfd);
return 0;
}
int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd) {
int r;
if (userns_fd >= 0) {
/* Can't setns to your own userns, since then you could escalate from non-root to root in
* your own namespace, so check if namespaces are equal before attempting to enter. */
r = inode_same_at(userns_fd, "", AT_FDCWD, "/proc/self/ns/user", AT_EMPTY_PATH);
if (r < 0)
return r;
if (r)
userns_fd = -EBADF;
}
if (pidns_fd >= 0)
if (setns(pidns_fd, CLONE_NEWPID) < 0)
return -errno;
if (mntns_fd >= 0)
if (setns(mntns_fd, CLONE_NEWNS) < 0)
return -errno;
if (netns_fd >= 0)
if (setns(netns_fd, CLONE_NEWNET) < 0)
return -errno;
if (userns_fd >= 0)
if (setns(userns_fd, CLONE_NEWUSER) < 0)
return -errno;
if (root_fd >= 0) {
if (fchdir(root_fd) < 0)
return -errno;
if (chroot(".") < 0)
return -errno;
}
return reset_uid_gid();
}
int fd_is_ns(int fd, unsigned long nsflag) {
struct statfs s;
int r;
/* Checks whether the specified file descriptor refers to a namespace created by specifying nsflag in clone().
* On old kernels there's no nice way to detect that, hence on those we'll return a recognizable error (EUCLEAN),
* so that callers can handle this somewhat nicely.
*
* This function returns > 0 if the fd definitely refers to a network namespace, 0 if it definitely does not
* refer to a network namespace, -EUCLEAN if we can't determine, and other negative error codes on error. */
if (fstatfs(fd, &s) < 0)
return -errno;
if (!is_fs_type(&s, NSFS_MAGIC)) {
/* On really old kernels, there was no "nsfs", and network namespace sockets belonged to procfs
* instead. Handle that in a somewhat smart way. */
if (is_fs_type(&s, PROC_SUPER_MAGIC)) {
struct statfs t;
/* OK, so it is procfs. Let's see if our own network namespace is procfs, too. If so, then the
* passed fd might refer to a network namespace, but we can't know for sure. In that case,
* return a recognizable error. */
if (statfs("/proc/self/ns/net", &t) < 0)
return -errno;
if (s.f_type == t.f_type)
return -EUCLEAN; /* It's possible, we simply don't know */
}
return 0; /* No! */
}
r = ioctl(fd, NS_GET_NSTYPE);
if (r < 0) {
if (errno == ENOTTY) /* Old kernels didn't know this ioctl, let's also return a recognizable error in that case */
return -EUCLEAN;
return -errno;
}
return (unsigned long) r == nsflag;
}
int detach_mount_namespace(void) {
/* Detaches the mount namespace, disabling propagation from our namespace to the host. Sets
* propagation first to MS_SLAVE for all mounts (disabling propagation), and then back to MS_SHARED
* (so that we create a new peer group). */
if (unshare(CLONE_NEWNS) < 0)
return log_debug_errno(errno, "Failed to acquire mount namespace: %m");
if (mount(NULL, "/", NULL, MS_SLAVE | MS_REC, NULL) < 0)
return log_debug_errno(errno, "Failed to set mount propagation to MS_SLAVE for all mounts: %m");
if (mount(NULL, "/", NULL, MS_SHARED | MS_REC, NULL) < 0)
return log_debug_errno(errno, "Failed to set mount propagation back to MS_SHARED for all mounts: %m");
return 0;
}
int userns_acquire(const char *uid_map, const char *gid_map) {
char path[STRLEN("/proc//uid_map") + DECIMAL_STR_MAX(pid_t) + 1];
_cleanup_(sigkill_waitp) pid_t pid = 0;
_cleanup_close_ int userns_fd = -EBADF;
int r;
assert(uid_map);
assert(gid_map);
/* Forks off a process in a new userns, configures the specified uidmap/gidmap, acquires an fd to it,
* and then kills the process again. This way we have a userns fd that is not bound to any
* process. We can use that for file system mounts and similar. */
r = safe_fork("(sd-mkuserns)", FORK_CLOSE_ALL_FDS|FORK_DEATHSIG|FORK_NEW_USERNS, &pid);
if (r < 0)
return r;
if (r == 0)
/* Child. We do nothing here, just freeze until somebody kills us. */
freeze();
xsprintf(path, "/proc/" PID_FMT "/uid_map", pid);
r = write_string_file(path, uid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
if (r < 0)
return log_error_errno(r, "Failed to write UID map: %m");
xsprintf(path, "/proc/" PID_FMT "/gid_map", pid);
r = write_string_file(path, gid_map, WRITE_STRING_FILE_DISABLE_BUFFER);
if (r < 0)
return log_error_errno(r, "Failed to write GID map: %m");
r = namespace_open(pid, NULL, NULL, NULL, &userns_fd, NULL);
if (r < 0)
return log_error_errno(r, "Failed to open userns fd: %m");
return TAKE_FD(userns_fd);
}
int in_same_namespace(pid_t pid1, pid_t pid2, NamespaceType type) {
const char *ns_path;
struct stat ns_st1, ns_st2;
if (pid1 == 0)
pid1 = getpid_cached();
if (pid2 == 0)
pid2 = getpid_cached();
if (pid1 == pid2)
return 1;
ns_path = pid_namespace_path(pid1, type);
if (stat(ns_path, &ns_st1) < 0)
return -errno;
ns_path = pid_namespace_path(pid2, type);
if (stat(ns_path, &ns_st2) < 0)
return -errno;
return stat_inode_same(&ns_st1, &ns_st2);
}
| 9,903 | 35.681481 | 130 | c |
null | systemd-main/src/basic/namespace-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/types.h>
typedef enum NamespaceType {
NAMESPACE_CGROUP,
NAMESPACE_IPC,
NAMESPACE_NET,
NAMESPACE_MOUNT,
NAMESPACE_PID,
NAMESPACE_USER,
NAMESPACE_UTS,
NAMESPACE_TIME,
_NAMESPACE_TYPE_MAX,
_NAMESPACE_TYPE_INVALID = -EINVAL,
} NamespaceType;
extern const struct namespace_info {
const char *proc_name;
const char *proc_path;
unsigned int clone_flag;
} namespace_info[_NAMESPACE_TYPE_MAX + 1];
int namespace_open(pid_t pid, int *pidns_fd, int *mntns_fd, int *netns_fd, int *userns_fd, int *root_fd);
int namespace_enter(int pidns_fd, int mntns_fd, int netns_fd, int userns_fd, int root_fd);
int fd_is_ns(int fd, unsigned long nsflag);
int detach_mount_namespace(void);
static inline bool userns_shift_range_valid(uid_t shift, uid_t range) {
/* Checks that the specified userns range makes sense, i.e. contains at least one UID, and the end
* doesn't overflow uid_t. */
assert_cc((uid_t) -1 > 0); /* verify that uid_t is unsigned */
if (range <= 0)
return false;
if (shift > (uid_t) -1 - range)
return false;
return true;
}
int userns_acquire(const char *uid_map, const char *gid_map);
int in_same_namespace(pid_t pid1, pid_t pid2, NamespaceType type);
| 1,420 | 28 | 106 | h |
null | systemd-main/src/basic/nss-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <grp.h>
#include <netdb.h>
#include <nss.h>
#include <pwd.h>
#include <resolv.h>
#define NSS_SIGNALS_BLOCK SIGALRM,SIGVTALRM,SIGPIPE,SIGCHLD,SIGTSTP,SIGIO,SIGHUP,SIGUSR1,SIGUSR2,SIGPROF,SIGURG,SIGWINCH
#ifndef DEPRECATED_RES_USE_INET6
# define DEPRECATED_RES_USE_INET6 0x00002000
#endif
#define NSS_GETHOSTBYNAME_PROTOTYPES(module) \
enum nss_status _nss_##module##_gethostbyname4_r( \
const char *name, \
struct gaih_addrtuple **pat, \
char *buffer, size_t buflen, \
int *errnop, int *h_errnop, \
int32_t *ttlp) _public_; \
enum nss_status _nss_##module##_gethostbyname3_r( \
const char *name, \
int af, \
struct hostent *host, \
char *buffer, size_t buflen, \
int *errnop, int *h_errnop, \
int32_t *ttlp, \
char **canonp) _public_; \
enum nss_status _nss_##module##_gethostbyname2_r( \
const char *name, \
int af, \
struct hostent *host, \
char *buffer, size_t buflen, \
int *errnop, int *h_errnop) _public_; \
enum nss_status _nss_##module##_gethostbyname_r( \
const char *name, \
struct hostent *host, \
char *buffer, size_t buflen, \
int *errnop, int *h_errnop) _public_
#define NSS_GETHOSTBYADDR_PROTOTYPES(module) \
enum nss_status _nss_##module##_gethostbyaddr2_r( \
const void* addr, socklen_t len, \
int af, \
struct hostent *host, \
char *buffer, size_t buflen, \
int *errnop, int *h_errnop, \
int32_t *ttlp) _public_; \
enum nss_status _nss_##module##_gethostbyaddr_r( \
const void* addr, socklen_t len, \
int af, \
struct hostent *host, \
char *buffer, size_t buflen, \
int *errnop, int *h_errnop) _public_
#define NSS_GETHOSTBYNAME_FALLBACKS(module) \
enum nss_status _nss_##module##_gethostbyname2_r( \
const char *name, \
int af, \
struct hostent *host, \
char *buffer, size_t buflen, \
int *errnop, int *h_errnop) { \
return _nss_##module##_gethostbyname3_r( \
name, \
af, \
host, \
buffer, buflen, \
errnop, h_errnop, \
NULL, \
NULL); \
} \
enum nss_status _nss_##module##_gethostbyname_r( \
const char *name, \
struct hostent *host, \
char *buffer, size_t buflen, \
int *errnop, int *h_errnop) { \
enum nss_status ret = NSS_STATUS_NOTFOUND; \
\
if (_res.options & DEPRECATED_RES_USE_INET6) \
ret = _nss_##module##_gethostbyname3_r( \
name, \
AF_INET6, \
host, \
buffer, buflen, \
errnop, h_errnop, \
NULL, \
NULL); \
if (ret == NSS_STATUS_NOTFOUND) \
ret = _nss_##module##_gethostbyname3_r( \
name, \
AF_INET, \
host, \
buffer, buflen, \
errnop, h_errnop, \
NULL, \
NULL); \
return ret; \
}
#define NSS_GETHOSTBYADDR_FALLBACKS(module) \
enum nss_status _nss_##module##_gethostbyaddr_r( \
const void* addr, socklen_t len, \
int af, \
struct hostent *host, \
char *buffer, size_t buflen, \
int *errnop, int *h_errnop) { \
return _nss_##module##_gethostbyaddr2_r( \
addr, len, \
af, \
host, \
buffer, buflen, \
errnop, h_errnop, \
NULL); \
}
#define NSS_GETPW_PROTOTYPES(module) \
enum nss_status _nss_##module##_getpwnam_r( \
const char *name, \
struct passwd *pwd, \
char *buffer, size_t buflen, \
int *errnop) _public_; \
enum nss_status _nss_##module##_getpwuid_r( \
uid_t uid, \
struct passwd *pwd, \
char *buffer, size_t buflen, \
int *errnop) _public_
#define NSS_GETSP_PROTOTYPES(module) \
enum nss_status _nss_##module##_getspnam_r( \
const char *name, \
struct spwd *spwd, \
char *buffer, size_t buflen, \
int *errnop) _public_
#define NSS_GETSG_PROTOTYPES(module) \
enum nss_status _nss_##module##_getsgnam_r( \
const char *name, \
struct sgrp *sgrp, \
char *buffer, size_t buflen, \
int *errnop) _public_
#define NSS_GETGR_PROTOTYPES(module) \
enum nss_status _nss_##module##_getgrnam_r( \
const char *name, \
struct group *gr, \
char *buffer, size_t buflen, \
int *errnop) _public_; \
enum nss_status _nss_##module##_getgrgid_r( \
gid_t gid, \
struct group *gr, \
char *buffer, size_t buflen, \
int *errnop) _public_
#define NSS_PWENT_PROTOTYPES(module) \
enum nss_status _nss_##module##_endpwent( \
void) _public_; \
enum nss_status _nss_##module##_setpwent( \
int stayopen) _public_; \
enum nss_status _nss_##module##_getpwent_r( \
struct passwd *result, \
char *buffer, \
size_t buflen, \
int *errnop) _public_;
#define NSS_SPENT_PROTOTYPES(module) \
enum nss_status _nss_##module##_endspent( \
void) _public_; \
enum nss_status _nss_##module##_setspent( \
int stayopen) _public_; \
enum nss_status _nss_##module##_getspent_r( \
struct spwd *spwd, \
char *buffer, \
size_t buflen, \
int *errnop) _public_;
#define NSS_GRENT_PROTOTYPES(module) \
enum nss_status _nss_##module##_endgrent( \
void) _public_; \
enum nss_status _nss_##module##_setgrent( \
int stayopen) _public_; \
enum nss_status _nss_##module##_getgrent_r( \
struct group *result, \
char *buffer, \
size_t buflen, \
int *errnop) _public_;
#define NSS_SGENT_PROTOTYPES(module) \
enum nss_status _nss_##module##_endsgent( \
void) _public_; \
enum nss_status _nss_##module##_setsgent( \
int stayopen) _public_; \
enum nss_status _nss_##module##_getsgent_r( \
struct sgrp *sgrp, \
char *buffer, \
size_t buflen, \
int *errnop) _public_;
#define NSS_INITGROUPS_PROTOTYPE(module) \
enum nss_status _nss_##module##_initgroups_dyn( \
const char *user, \
gid_t group, \
long int *start, \
long int *size, \
gid_t **groupsp, \
long int limit, \
int *errnop) _public_;
typedef enum nss_status (*_nss_gethostbyname4_r_t)(
const char *name,
struct gaih_addrtuple **pat,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp);
typedef enum nss_status (*_nss_gethostbyname3_r_t)(
const char *name,
int af,
struct hostent *result,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp,
char **canonp);
typedef enum nss_status (*_nss_gethostbyname2_r_t)(
const char *name,
int af,
struct hostent *result,
char *buffer, size_t buflen,
int *errnop, int *h_errnop);
typedef enum nss_status (*_nss_gethostbyname_r_t)(
const char *name,
struct hostent *result,
char *buffer, size_t buflen,
int *errnop, int *h_errnop);
typedef enum nss_status (*_nss_gethostbyaddr2_r_t)(
const void* addr, socklen_t len,
int af,
struct hostent *result,
char *buffer, size_t buflen,
int *errnop, int *h_errnop,
int32_t *ttlp);
typedef enum nss_status (*_nss_gethostbyaddr_r_t)(
const void* addr, socklen_t len,
int af,
struct hostent *host,
char *buffer, size_t buflen,
int *errnop, int *h_errnop);
typedef enum nss_status (*_nss_getpwnam_r_t)(
const char *name,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop);
typedef enum nss_status (*_nss_getpwuid_r_t)(
uid_t uid,
struct passwd *pwd,
char *buffer, size_t buflen,
int *errnop);
typedef enum nss_status (*_nss_getgrnam_r_t)(
const char *name,
struct group *gr,
char *buffer, size_t buflen,
int *errnop);
typedef enum nss_status (*_nss_getgrgid_r_t)(
gid_t gid,
struct group *gr,
char *buffer, size_t buflen,
int *errnop);
| 12,876 | 45.99635 | 120 | h |
null | systemd-main/src/basic/nulstr-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "nulstr-util.h"
#include "string-util.h"
#include "strv.h"
char** strv_parse_nulstr_full(const char *s, size_t l, bool drop_trailing_nuls) {
/* l is the length of the input data, which will be split at NULs into elements of the resulting
* strv. Hence, the number of items in the resulting strv will be equal to one plus the number of NUL
* bytes in the l bytes starting at s, unless s[l-1] is NUL, in which case the final empty string is
* not stored in the resulting strv, and length is equal to the number of NUL bytes.
*
* Note that contrary to a normal nulstr which cannot contain empty strings, because the input data
* is terminated by any two consequent NUL bytes, this parser accepts empty strings in s. */
_cleanup_strv_free_ char **v = NULL;
size_t c = 0, i = 0;
assert(s || l <= 0);
if (drop_trailing_nuls)
while (l > 0 && s[l-1] == '\0')
l--;
if (l <= 0)
return new0(char*, 1);
for (const char *p = s; p < s + l; p++)
if (*p == 0)
c++;
if (s[l-1] != 0)
c++;
v = new0(char*, c+1);
if (!v)
return NULL;
for (const char *p = s; p < s + l; ) {
const char *e;
e = memchr(p, 0, s + l - p);
v[i] = memdup_suffix0(p, e ? e - p : s + l - p);
if (!v[i])
return NULL;
i++;
if (!e)
break;
p = e + 1;
}
assert(i == c);
return TAKE_PTR(v);
}
char** strv_split_nulstr(const char *s) {
_cleanup_strv_free_ char **l = NULL;
/* This parses a nulstr, without specification of size, and stops at an empty string. This cannot
* parse nulstrs with embedded empty strings hence, as an empty string is an end marker. Use
* strv_parse_nulstr() above to parse a nulstr with embedded empty strings (which however requires a
* size to be specified) */
NULSTR_FOREACH(i, s)
if (strv_extend(&l, i) < 0)
return NULL;
return l ? TAKE_PTR(l) : strv_new(NULL);
}
int strv_make_nulstr(char * const *l, char **ret, size_t *ret_size) {
/* Builds a nulstr and returns it together with the size. An extra NUL byte will be appended (⚠️ but
* not included in the size! ⚠️). This is done so that the nulstr can be used both in
* strv_parse_nulstr() and in NULSTR_FOREACH()/strv_split_nulstr() contexts, i.e. with and without a
* size parameter. In the former case we can include empty strings, in the latter case we cannot (as
* that is the end marker).
*
* When NULSTR_FOREACH()/strv_split_nulstr() is used it is often assumed that the nulstr ends in two
* NUL bytes (which it will, if not empty). To ensure that this assumption *always* holds, we'll
* return a buffer with two NUL bytes in that case, but return a size of zero. */
_cleanup_free_ char *m = NULL;
size_t n = 0;
assert(ret);
STRV_FOREACH(i, l) {
size_t z;
z = strlen(*i);
if (!GREEDY_REALLOC(m, n + z + 2))
return -ENOMEM;
memcpy(m + n, *i, z + 1);
n += z + 1;
}
if (!m) {
/* return a buffer with an extra NUL, so that the assumption that we always have two trailing NULs holds */
m = new0(char, 2);
if (!m)
return -ENOMEM;
n = 0;
} else
/* Make sure there is a second extra NUL at the end of resulting nulstr (not counted in return size) */
m[n] = '\0';
*ret = TAKE_PTR(m);
if (ret_size)
*ret_size = n;
return 0;
}
int set_make_nulstr(Set *s, char **ret, size_t *ret_size) {
/* Use _cleanup_free_ instead of _cleanup_strv_free_ because we need to clean the strv only, not
* the strings owned by the set. */
_cleanup_free_ char **strv = NULL;
assert(ret);
strv = set_get_strv(s);
if (!strv)
return -ENOMEM;
return strv_make_nulstr(strv, ret, ret_size);
}
const char* nulstr_get(const char *nulstr, const char *needle) {
if (!nulstr)
return NULL;
NULSTR_FOREACH(i, nulstr)
if (streq(i, needle))
return i;
return NULL;
}
| 4,759 | 31.60274 | 123 | c |
null | systemd-main/src/basic/ordered-set.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "fileio.h"
#include "ordered-set.h"
#include "strv.h"
int _ordered_set_ensure_allocated(OrderedSet **s, const struct hash_ops *ops HASHMAP_DEBUG_PARAMS) {
if (*s)
return 0;
*s = _ordered_set_new(ops HASHMAP_DEBUG_PASS_ARGS);
if (!*s)
return -ENOMEM;
return 0;
}
int _ordered_set_ensure_put(OrderedSet **s, const struct hash_ops *ops, void *p HASHMAP_DEBUG_PARAMS) {
int r;
r = _ordered_set_ensure_allocated(s, ops HASHMAP_DEBUG_PASS_ARGS);
if (r < 0)
return r;
return ordered_set_put(*s, p);
}
int ordered_set_consume(OrderedSet *s, void *p) {
int r;
r = ordered_set_put(s, p);
if (r <= 0)
free(p);
return r;
}
int _ordered_set_put_strdup(OrderedSet **s, const char *p HASHMAP_DEBUG_PARAMS) {
char *c;
int r;
assert(s);
assert(p);
r = _ordered_set_ensure_allocated(s, &string_hash_ops_free HASHMAP_DEBUG_PASS_ARGS);
if (r < 0)
return r;
if (ordered_set_contains(*s, p))
return 0;
c = strdup(p);
if (!c)
return -ENOMEM;
return ordered_set_consume(*s, c);
}
int _ordered_set_put_strdupv(OrderedSet **s, char **l HASHMAP_DEBUG_PARAMS) {
int n = 0, r;
STRV_FOREACH(i, l) {
r = _ordered_set_put_strdup(s, *i HASHMAP_DEBUG_PASS_ARGS);
if (r < 0)
return r;
n += r;
}
return n;
}
int ordered_set_put_string_set(OrderedSet **s, OrderedSet *l) {
int n = 0, r;
char *p;
/* Like ordered_set_put_strv, but for an OrderedSet of strings */
ORDERED_SET_FOREACH(p, l) {
r = ordered_set_put_strdup(s, p);
if (r < 0)
return r;
n += r;
}
return n;
}
void ordered_set_print(FILE *f, const char *field, OrderedSet *s) {
bool space = false;
char *p;
if (ordered_set_isempty(s))
return;
fputs(field, f);
ORDERED_SET_FOREACH(p, s)
fputs_with_space(f, p, NULL, &space);
fputc('\n', f);
}
| 2,350 | 21.605769 | 104 | c |
null | systemd-main/src/basic/ordered-set.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdio.h>
#include "hashmap.h"
typedef struct OrderedSet OrderedSet;
static inline OrderedSet* _ordered_set_new(const struct hash_ops *ops HASHMAP_DEBUG_PARAMS) {
return (OrderedSet*) _ordered_hashmap_new(ops HASHMAP_DEBUG_PASS_ARGS);
}
#define ordered_set_new(ops) _ordered_set_new(ops HASHMAP_DEBUG_SRC_ARGS)
int _ordered_set_ensure_allocated(OrderedSet **s, const struct hash_ops *ops HASHMAP_DEBUG_PARAMS);
#define ordered_set_ensure_allocated(s, ops) _ordered_set_ensure_allocated(s, ops HASHMAP_DEBUG_SRC_ARGS)
int _ordered_set_ensure_put(OrderedSet **s, const struct hash_ops *ops, void *p HASHMAP_DEBUG_PARAMS);
#define ordered_set_ensure_put(s, hash_ops, key) _ordered_set_ensure_put(s, hash_ops, key HASHMAP_DEBUG_SRC_ARGS)
static inline void ordered_set_clear(OrderedSet *s) {
return ordered_hashmap_clear((OrderedHashmap*) s);
}
static inline void ordered_set_clear_free(OrderedSet *s) {
return ordered_hashmap_clear_free((OrderedHashmap*) s);
}
static inline OrderedSet* ordered_set_free(OrderedSet *s) {
return (OrderedSet*) ordered_hashmap_free((OrderedHashmap*) s);
}
static inline OrderedSet* ordered_set_free_free(OrderedSet *s) {
return (OrderedSet*) ordered_hashmap_free_free((OrderedHashmap*) s);
}
static inline int ordered_set_contains(OrderedSet *s, const void *p) {
return ordered_hashmap_contains((OrderedHashmap*) s, p);
}
static inline int ordered_set_put(OrderedSet *s, void *p) {
return ordered_hashmap_put((OrderedHashmap*) s, p, p);
}
static inline void *ordered_set_get(OrderedSet *s, const void *p) {
return ordered_hashmap_get((OrderedHashmap*) s, p);
}
static inline unsigned ordered_set_size(OrderedSet *s) {
return ordered_hashmap_size((OrderedHashmap*) s);
}
static inline bool ordered_set_isempty(OrderedSet *s) {
return ordered_hashmap_isempty((OrderedHashmap*) s);
}
static inline bool ordered_set_iterate(OrderedSet *s, Iterator *i, void **value) {
return ordered_hashmap_iterate((OrderedHashmap*) s, i, value, NULL);
}
static inline void* ordered_set_remove(OrderedSet *s, void *p) {
return ordered_hashmap_remove((OrderedHashmap*) s, p);
}
static inline void* ordered_set_first(OrderedSet *s) {
return ordered_hashmap_first((OrderedHashmap*) s);
}
static inline void* ordered_set_steal_first(OrderedSet *s) {
return ordered_hashmap_steal_first((OrderedHashmap*) s);
}
static inline char** ordered_set_get_strv(OrderedSet *s) {
return _hashmap_get_strv(HASHMAP_BASE((OrderedHashmap*) s));
}
static inline int ordered_set_reserve(OrderedSet *s, unsigned entries_add) {
return ordered_hashmap_reserve((OrderedHashmap*) s, entries_add);
}
int ordered_set_consume(OrderedSet *s, void *p);
int _ordered_set_put_strdup(OrderedSet **s, const char *p HASHMAP_DEBUG_PARAMS);
#define ordered_set_put_strdup(s, p) _ordered_set_put_strdup(s, p HASHMAP_DEBUG_SRC_ARGS)
int _ordered_set_put_strdupv(OrderedSet **s, char **l HASHMAP_DEBUG_PARAMS);
#define ordered_set_put_strdupv(s, l) _ordered_set_put_strdupv(s, l HASHMAP_DEBUG_SRC_ARGS)
int ordered_set_put_string_set(OrderedSet **s, OrderedSet *l);
void ordered_set_print(FILE *f, const char *field, OrderedSet *s);
#define _ORDERED_SET_FOREACH(e, s, i) \
for (Iterator i = ITERATOR_FIRST; ordered_set_iterate((s), &i, (void**)&(e)); )
#define ORDERED_SET_FOREACH(e, s) \
_ORDERED_SET_FOREACH(e, s, UNIQ_T(i, UNIQ))
#define ordered_set_clear_with_destructor(s, f) \
({ \
OrderedSet *_s = (s); \
void *_item; \
while ((_item = ordered_set_steal_first(_s))) \
f(_item); \
_s; \
})
#define ordered_set_free_with_destructor(s, f) \
ordered_set_free(ordered_set_clear_with_destructor(s, f))
DEFINE_TRIVIAL_CLEANUP_FUNC(OrderedSet*, ordered_set_free);
DEFINE_TRIVIAL_CLEANUP_FUNC(OrderedSet*, ordered_set_free_free);
#define _cleanup_ordered_set_free_ _cleanup_(ordered_set_freep)
#define _cleanup_ordered_set_free_free_ _cleanup_(ordered_set_free_freep)
| 4,419 | 39.181818 | 114 | h |
null | systemd-main/src/basic/origin-id.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <pthread.h>
#include "random-util.h"
/* This pattern needs to be repeated exactly in multiple modules, so macro it.
* To ensure an object is not passed into a different module (e.g.: when two shared objects statically
* linked to libsystemd get loaded in the same process, and the object created by one is passed to the
* other, see https://github.com/systemd/systemd/issues/27216), create a random static global random
* (mixed with PID, so that we can also check for reuse after fork) that is stored in the object and
* checked by public API on use. */
#define _DEFINE_ORIGIN_ID_HELPERS(type, name, scope) \
static uint64_t origin_id; \
\
static void origin_id_initialize(void) { \
origin_id = random_u64(); \
} \
\
static uint64_t origin_id_query(void) { \
static pthread_once_t once = PTHREAD_ONCE_INIT; \
assert_se(pthread_once(&once, origin_id_initialize) == 0); \
return origin_id ^ getpid_cached(); \
} \
\
scope bool name##_origin_changed(type *p) { \
assert(p); \
return p->origin_id != origin_id_query(); \
}
#define DEFINE_ORIGIN_ID_HELPERS(type, name) \
_DEFINE_ORIGIN_ID_HELPERS(type, name,);
#define DEFINE_PRIVATE_ORIGIN_ID_HELPERS(type, name) \
_DEFINE_ORIGIN_ID_HELPERS(type, name, static);
| 2,037 | 54.081081 | 102 | h |
null | systemd-main/src/basic/parse-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <inttypes.h>
#include <net/if.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/socket.h>
#include "alloc-util.h"
#include "errno-list.h"
#include "extract-word.h"
#include "locale-util.h"
#include "macro.h"
#include "missing_network.h"
#include "parse-util.h"
#include "process-util.h"
#include "stat-util.h"
#include "string-util.h"
#include "strv.h"
int parse_boolean(const char *v) {
if (!v)
return -EINVAL;
if (STRCASE_IN_SET(v,
"1",
"yes",
"y",
"true",
"t",
"on"))
return 1;
if (STRCASE_IN_SET(v,
"0",
"no",
"n",
"false",
"f",
"off"))
return 0;
return -EINVAL;
}
int parse_pid(const char *s, pid_t* ret_pid) {
unsigned long ul = 0;
pid_t pid;
int r;
assert(s);
r = safe_atolu(s, &ul);
if (r < 0)
return r;
pid = (pid_t) ul;
if ((unsigned long) pid != ul)
return -ERANGE;
if (!pid_is_valid(pid))
return -ERANGE;
if (ret_pid)
*ret_pid = pid;
return 0;
}
int parse_mode(const char *s, mode_t *ret) {
unsigned m;
int r;
assert(s);
r = safe_atou_full(s, 8 |
SAFE_ATO_REFUSE_PLUS_MINUS, /* Leading '+' or even '-' char? that's just weird,
* refuse. User might have wanted to add mode flags or
* so, but this parser doesn't allow that, so let's
* better be safe. */
&m);
if (r < 0)
return r;
if (m > 07777)
return -ERANGE;
if (ret)
*ret = m;
return 0;
}
int parse_ifindex(const char *s) {
int ifi, r;
assert(s);
r = safe_atoi(s, &ifi);
if (r < 0)
return r;
if (ifi <= 0)
return -EINVAL;
return ifi;
}
int parse_mtu(int family, const char *s, uint32_t *ret) {
uint64_t u;
size_t m;
int r;
r = parse_size(s, 1024, &u);
if (r < 0)
return r;
if (u > UINT32_MAX)
return -ERANGE;
if (family == AF_INET6)
m = IPV6_MIN_MTU; /* This is 1280 */
else
m = IPV4_MIN_MTU; /* For all other protocols, including 'unspecified' we assume the IPv4 minimal MTU */
if (u < m)
return -ERANGE;
*ret = (uint32_t) u;
return 0;
}
int parse_size(const char *t, uint64_t base, uint64_t *size) {
/* Soo, sometimes we want to parse IEC binary suffixes, and
* sometimes SI decimal suffixes. This function can parse
* both. Which one is the right way depends on the
* context. Wikipedia suggests that SI is customary for
* hardware metrics and network speeds, while IEC is
* customary for most data sizes used by software and volatile
* (RAM) memory. Hence be careful which one you pick!
*
* In either case we use just K, M, G as suffix, and not Ki,
* Mi, Gi or so (as IEC would suggest). That's because that's
* frickin' ugly. But this means you really need to make sure
* to document which base you are parsing when you use this
* call. */
struct table {
const char *suffix;
unsigned long long factor;
};
static const struct table iec[] = {
{ "E", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
{ "P", 1024ULL*1024ULL*1024ULL*1024ULL*1024ULL },
{ "T", 1024ULL*1024ULL*1024ULL*1024ULL },
{ "G", 1024ULL*1024ULL*1024ULL },
{ "M", 1024ULL*1024ULL },
{ "K", 1024ULL },
{ "B", 1ULL },
{ "", 1ULL },
};
static const struct table si[] = {
{ "E", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
{ "P", 1000ULL*1000ULL*1000ULL*1000ULL*1000ULL },
{ "T", 1000ULL*1000ULL*1000ULL*1000ULL },
{ "G", 1000ULL*1000ULL*1000ULL },
{ "M", 1000ULL*1000ULL },
{ "K", 1000ULL },
{ "B", 1ULL },
{ "", 1ULL },
};
const struct table *table;
const char *p;
unsigned long long r = 0;
unsigned n_entries, start_pos = 0;
assert(t);
assert(IN_SET(base, 1000, 1024));
assert(size);
if (base == 1000) {
table = si;
n_entries = ELEMENTSOF(si);
} else {
table = iec;
n_entries = ELEMENTSOF(iec);
}
p = t;
do {
unsigned long long l, tmp;
double frac = 0;
char *e;
unsigned i;
p += strspn(p, WHITESPACE);
errno = 0;
l = strtoull(p, &e, 10);
if (errno > 0)
return -errno;
if (e == p)
return -EINVAL;
if (*p == '-')
return -ERANGE;
if (*e == '.') {
e++;
/* strtoull() itself would accept space/+/- */
if (ascii_isdigit(*e)) {
unsigned long long l2;
char *e2;
l2 = strtoull(e, &e2, 10);
if (errno > 0)
return -errno;
/* Ignore failure. E.g. 10.M is valid */
frac = l2;
for (; e < e2; e++)
frac /= 10;
}
}
e += strspn(e, WHITESPACE);
for (i = start_pos; i < n_entries; i++)
if (startswith(e, table[i].suffix))
break;
if (i >= n_entries)
return -EINVAL;
if (l + (frac > 0) > ULLONG_MAX / table[i].factor)
return -ERANGE;
tmp = l * table[i].factor + (unsigned long long) (frac * table[i].factor);
if (tmp > ULLONG_MAX - r)
return -ERANGE;
r += tmp;
if ((unsigned long long) (uint64_t) r != r)
return -ERANGE;
p = e + strlen(table[i].suffix);
start_pos = i + 1;
} while (*p);
*size = r;
return 0;
}
int parse_sector_size(const char *t, uint64_t *ret) {
int r;
assert(t);
assert(ret);
uint64_t ss;
r = safe_atou64(t, &ss);
if (r < 0)
return log_error_errno(r, "Failed to parse sector size parameter %s", t);
if (ss < 512 || ss > 4096) /* Allow up to 4K due to dm-crypt support and 4K alignment by the homed LUKS backend */
return log_error_errno(SYNTHETIC_ERRNO(ERANGE), "Sector size not between 512 and 4096: %s", t);
if (!ISPOWEROF2(ss))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Sector size not power of 2: %s", t);
*ret = ss;
return 0;
}
int parse_range(const char *t, unsigned *lower, unsigned *upper) {
_cleanup_free_ char *word = NULL;
unsigned l, u;
int r;
assert(lower);
assert(upper);
/* Extract the lower bound. */
r = extract_first_word(&t, &word, "-", EXTRACT_DONT_COALESCE_SEPARATORS);
if (r < 0)
return r;
if (r == 0)
return -EINVAL;
r = safe_atou(word, &l);
if (r < 0)
return r;
/* Check for the upper bound and extract it if needed */
if (!t)
/* Single number with no dashes. */
u = l;
else if (!*t)
/* Trailing dash is an error. */
return -EINVAL;
else {
r = safe_atou(t, &u);
if (r < 0)
return r;
}
*lower = l;
*upper = u;
return 0;
}
int parse_errno(const char *t) {
int r, e;
assert(t);
r = errno_from_name(t);
if (r > 0)
return r;
r = safe_atoi(t, &e);
if (r < 0)
return r;
/* 0 is also allowed here */
if (!errno_is_valid(e) && e != 0)
return -ERANGE;
return e;
}
int parse_fd(const char *t) {
int r, fd;
assert(t);
r = safe_atoi(t, &fd);
if (r < 0)
return r;
if (fd < 0)
return -EBADF;
return fd;
}
static const char *mangle_base(const char *s, unsigned *base) {
const char *k;
assert(s);
assert(base);
/* Base already explicitly specified, then don't do anything. */
if (SAFE_ATO_MASK_FLAGS(*base) != 0)
return s;
/* Support Python 3 style "0b" and 0x" prefixes, because they truly make sense, much more than C's "0" prefix for octal. */
k = STARTSWITH_SET(s, "0b", "0B");
if (k) {
*base = 2 | (*base & SAFE_ATO_ALL_FLAGS);
return k;
}
k = STARTSWITH_SET(s, "0o", "0O");
if (k) {
*base = 8 | (*base & SAFE_ATO_ALL_FLAGS);
return k;
}
return s;
}
int safe_atou_full(const char *s, unsigned base, unsigned *ret_u) {
char *x = NULL;
unsigned long l;
assert(s);
assert(SAFE_ATO_MASK_FLAGS(base) <= 16);
/* strtoul() is happy to parse negative values, and silently converts them to unsigned values without
* generating an error. We want a clean error, hence let's look for the "-" prefix on our own, and
* generate an error. But let's do so only after strtoul() validated that the string is clean
* otherwise, so that we return EINVAL preferably over ERANGE. */
if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_WHITESPACE) &&
strchr(WHITESPACE, s[0]))
return -EINVAL;
s += strspn(s, WHITESPACE);
if (FLAGS_SET(base, SAFE_ATO_REFUSE_PLUS_MINUS) &&
IN_SET(s[0], '+', '-'))
return -EINVAL; /* Note that we check the "-" prefix again a second time below, but return a
* different error. I.e. if the SAFE_ATO_REFUSE_PLUS_MINUS flag is set we
* blanket refuse +/- prefixed integers, while if it is missing we'll just
* return ERANGE, because the string actually parses correctly, but doesn't
* fit in the return type. */
if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_ZERO) &&
s[0] == '0' && !streq(s, "0"))
return -EINVAL; /* This is particularly useful to avoid ambiguities between C's octal
* notation and assumed-to-be-decimal integers with a leading zero. */
s = mangle_base(s, &base);
errno = 0;
l = strtoul(s, &x, SAFE_ATO_MASK_FLAGS(base) /* Let's mask off the flags bits so that only the actual
* base is left */);
if (errno > 0)
return -errno;
if (!x || x == s || *x != 0)
return -EINVAL;
if (l != 0 && s[0] == '-')
return -ERANGE;
if ((unsigned long) (unsigned) l != l)
return -ERANGE;
if (ret_u)
*ret_u = (unsigned) l;
return 0;
}
int safe_atoi(const char *s, int *ret_i) {
unsigned base = 0;
char *x = NULL;
long l;
assert(s);
s += strspn(s, WHITESPACE);
s = mangle_base(s, &base);
errno = 0;
l = strtol(s, &x, base);
if (errno > 0)
return -errno;
if (!x || x == s || *x != 0)
return -EINVAL;
if ((long) (int) l != l)
return -ERANGE;
if (ret_i)
*ret_i = (int) l;
return 0;
}
int safe_atollu_full(const char *s, unsigned base, unsigned long long *ret_llu) {
char *x = NULL;
unsigned long long l;
assert(s);
assert(SAFE_ATO_MASK_FLAGS(base) <= 16);
if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_WHITESPACE) &&
strchr(WHITESPACE, s[0]))
return -EINVAL;
s += strspn(s, WHITESPACE);
if (FLAGS_SET(base, SAFE_ATO_REFUSE_PLUS_MINUS) &&
IN_SET(s[0], '+', '-'))
return -EINVAL;
if (FLAGS_SET(base, SAFE_ATO_REFUSE_LEADING_ZERO) &&
s[0] == '0' && s[1] != 0)
return -EINVAL;
s = mangle_base(s, &base);
errno = 0;
l = strtoull(s, &x, SAFE_ATO_MASK_FLAGS(base));
if (errno > 0)
return -errno;
if (!x || x == s || *x != 0)
return -EINVAL;
if (l != 0 && s[0] == '-')
return -ERANGE;
if (ret_llu)
*ret_llu = l;
return 0;
}
int safe_atolli(const char *s, long long int *ret_lli) {
unsigned base = 0;
char *x = NULL;
long long l;
assert(s);
s += strspn(s, WHITESPACE);
s = mangle_base(s, &base);
errno = 0;
l = strtoll(s, &x, base);
if (errno > 0)
return -errno;
if (!x || x == s || *x != 0)
return -EINVAL;
if (ret_lli)
*ret_lli = l;
return 0;
}
int safe_atou8_full(const char *s, unsigned base, uint8_t *ret) {
unsigned u;
int r;
r = safe_atou_full(s, base, &u);
if (r < 0)
return r;
if (u > UINT8_MAX)
return -ERANGE;
*ret = (uint8_t) u;
return 0;
}
int safe_atou16_full(const char *s, unsigned base, uint16_t *ret) {
unsigned u;
int r;
r = safe_atou_full(s, base, &u);
if (r < 0)
return r;
if (u > UINT16_MAX)
return -ERANGE;
*ret = (uint16_t) u;
return 0;
}
int safe_atoi16(const char *s, int16_t *ret) {
unsigned base = 0;
char *x = NULL;
long l;
assert(s);
s += strspn(s, WHITESPACE);
s = mangle_base(s, &base);
errno = 0;
l = strtol(s, &x, base);
if (errno > 0)
return -errno;
if (!x || x == s || *x != 0)
return -EINVAL;
if ((long) (int16_t) l != l)
return -ERANGE;
if (ret)
*ret = (int16_t) l;
return 0;
}
int safe_atod(const char *s, double *ret_d) {
_cleanup_(freelocalep) locale_t loc = (locale_t) 0;
char *x = NULL;
double d = 0;
assert(s);
loc = newlocale(LC_NUMERIC_MASK, "C", (locale_t) 0);
if (loc == (locale_t) 0)
return -errno;
errno = 0;
d = strtod_l(s, &x, loc);
if (errno > 0)
return -errno;
if (!x || x == s || *x != 0)
return -EINVAL;
if (ret_d)
*ret_d = (double) d;
return 0;
}
int parse_fractional_part_u(const char **p, size_t digits, unsigned *res) {
unsigned val = 0;
const char *s;
s = *p;
/* accept any number of digits, strtoull is limited to 19 */
for (size_t i = 0; i < digits; i++,s++) {
if (!ascii_isdigit(*s)) {
if (i == 0)
return -EINVAL;
/* too few digits, pad with 0 */
for (; i < digits; i++)
val *= 10;
break;
}
val *= 10;
val += *s - '0';
}
/* maybe round up */
if (*s >= '5' && *s <= '9')
val++;
s += strspn(s, DIGITS);
*p = s;
*res = val;
return 0;
}
int parse_nice(const char *p, int *ret) {
int n, r;
r = safe_atoi(p, &n);
if (r < 0)
return r;
if (!nice_is_valid(n))
return -ERANGE;
*ret = n;
return 0;
}
int parse_ip_port(const char *s, uint16_t *ret) {
uint16_t l;
int r;
r = safe_atou16_full(s, SAFE_ATO_REFUSE_LEADING_WHITESPACE, &l);
if (r < 0)
return r;
if (l == 0)
return -EINVAL;
*ret = (uint16_t) l;
return 0;
}
int parse_ip_port_range(const char *s, uint16_t *low, uint16_t *high) {
unsigned l, h;
int r;
r = parse_range(s, &l, &h);
if (r < 0)
return r;
if (l <= 0 || l > 65535 || h <= 0 || h > 65535)
return -EINVAL;
if (h < l)
return -EINVAL;
*low = l;
*high = h;
return 0;
}
int parse_ip_prefix_length(const char *s, int *ret) {
unsigned l;
int r;
r = safe_atou(s, &l);
if (r < 0)
return r;
if (l > 128)
return -ERANGE;
*ret = (int) l;
return 0;
}
int parse_oom_score_adjust(const char *s, int *ret) {
int r, v;
assert(s);
assert(ret);
r = safe_atoi(s, &v);
if (r < 0)
return r;
if (!oom_score_adjust_is_valid(v))
return -ERANGE;
*ret = v;
return 0;
}
int store_loadavg_fixed_point(unsigned long i, unsigned long f, loadavg_t *ret) {
assert(ret);
if (i >= (~0UL << LOADAVG_PRECISION_BITS))
return -ERANGE;
i = i << LOADAVG_PRECISION_BITS;
f = DIV_ROUND_UP((f << LOADAVG_PRECISION_BITS), 100);
if (f >= LOADAVG_FIXED_POINT_1_0)
return -ERANGE;
*ret = i | f;
return 0;
}
int parse_loadavg_fixed_point(const char *s, loadavg_t *ret) {
const char *d, *f_str, *i_str;
unsigned long i, f;
int r;
assert(s);
assert(ret);
d = strchr(s, '.');
if (!d)
return -EINVAL;
i_str = strndupa_safe(s, d - s);
f_str = d + 1;
r = safe_atolu_full(i_str, 10, &i);
if (r < 0)
return r;
r = safe_atolu_full(f_str, 10, &f);
if (r < 0)
return r;
return store_loadavg_fixed_point(i, f, ret);
}
| 19,514 | 25.02 | 131 | c |
null | systemd-main/src/basic/parse-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include <limits.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
#include "macro.h"
typedef unsigned long loadavg_t;
int parse_boolean(const char *v) _pure_;
int parse_pid(const char *s, pid_t* ret_pid);
int parse_mode(const char *s, mode_t *ret);
int parse_ifindex(const char *s);
int parse_mtu(int family, const char *s, uint32_t *ret);
int parse_size(const char *t, uint64_t base, uint64_t *size);
int parse_sector_size(const char *t, uint64_t *ret);
int parse_range(const char *t, unsigned *lower, unsigned *upper);
int parse_errno(const char *t);
int parse_fd(const char *t);
#define SAFE_ATO_REFUSE_PLUS_MINUS (1U << 30)
#define SAFE_ATO_REFUSE_LEADING_ZERO (1U << 29)
#define SAFE_ATO_REFUSE_LEADING_WHITESPACE (1U << 28)
#define SAFE_ATO_ALL_FLAGS (SAFE_ATO_REFUSE_PLUS_MINUS|SAFE_ATO_REFUSE_LEADING_ZERO|SAFE_ATO_REFUSE_LEADING_WHITESPACE)
#define SAFE_ATO_MASK_FLAGS(base) ((base) & ~SAFE_ATO_ALL_FLAGS)
int safe_atou_full(const char *s, unsigned base, unsigned *ret_u);
static inline int safe_atou(const char *s, unsigned *ret_u) {
return safe_atou_full(s, 0, ret_u);
}
int safe_atoi(const char *s, int *ret_i);
int safe_atolli(const char *s, long long int *ret_i);
int safe_atou8_full(const char *s, unsigned base, uint8_t *ret);
static inline int safe_atou8(const char *s, uint8_t *ret) {
return safe_atou8_full(s, 0, ret);
}
int safe_atou16_full(const char *s, unsigned base, uint16_t *ret);
static inline int safe_atou16(const char *s, uint16_t *ret) {
return safe_atou16_full(s, 0, ret);
}
static inline int safe_atoux16(const char *s, uint16_t *ret) {
return safe_atou16_full(s, 16, ret);
}
int safe_atoi16(const char *s, int16_t *ret);
static inline int safe_atou32_full(const char *s, unsigned base, uint32_t *ret_u) {
assert_cc(sizeof(uint32_t) == sizeof(unsigned));
return safe_atou_full(s, base, (unsigned*) ret_u);
}
static inline int safe_atou32(const char *s, uint32_t *ret_u) {
return safe_atou32_full(s, 0, (unsigned*) ret_u);
}
static inline int safe_atoi32(const char *s, int32_t *ret_i) {
assert_cc(sizeof(int32_t) == sizeof(int));
return safe_atoi(s, (int*) ret_i);
}
int safe_atollu_full(const char *s, unsigned base, unsigned long long *ret_llu);
static inline int safe_atollu(const char *s, unsigned long long *ret_llu) {
return safe_atollu_full(s, 0, ret_llu);
}
static inline int safe_atou64(const char *s, uint64_t *ret_u) {
assert_cc(sizeof(uint64_t) == sizeof(unsigned long long));
return safe_atollu(s, (unsigned long long*) ret_u);
}
static inline int safe_atoi64(const char *s, int64_t *ret_i) {
assert_cc(sizeof(int64_t) == sizeof(long long int));
return safe_atolli(s, (long long int*) ret_i);
}
static inline int safe_atoux64(const char *s, uint64_t *ret) {
assert_cc(sizeof(int64_t) == sizeof(unsigned long long));
return safe_atollu_full(s, 16, (unsigned long long*) ret);
}
#if LONG_MAX == INT_MAX
static inline int safe_atolu_full(const char *s, unsigned base, unsigned long *ret_u) {
assert_cc(sizeof(unsigned long) == sizeof(unsigned));
return safe_atou_full(s, base, (unsigned*) ret_u);
}
static inline int safe_atoli(const char *s, long int *ret_u) {
assert_cc(sizeof(long int) == sizeof(int));
return safe_atoi(s, (int*) ret_u);
}
#else
static inline int safe_atolu_full(const char *s, unsigned base, unsigned long *ret_u) {
assert_cc(sizeof(unsigned long) == sizeof(unsigned long long));
return safe_atollu_full(s, base, (unsigned long long*) ret_u);
}
static inline int safe_atoli(const char *s, long int *ret_u) {
assert_cc(sizeof(long int) == sizeof(long long int));
return safe_atolli(s, (long long int*) ret_u);
}
#endif
static inline int safe_atolu(const char *s, unsigned long *ret_u) {
return safe_atolu_full(s, 0, ret_u);
}
#if SIZE_MAX == UINT_MAX
static inline int safe_atozu(const char *s, size_t *ret_u) {
assert_cc(sizeof(size_t) == sizeof(unsigned));
return safe_atou(s, (unsigned *) ret_u);
}
#else
static inline int safe_atozu(const char *s, size_t *ret_u) {
assert_cc(sizeof(size_t) == sizeof(unsigned long));
return safe_atolu(s, ret_u);
}
#endif
int safe_atod(const char *s, double *ret_d);
int parse_fractional_part_u(const char **s, size_t digits, unsigned *res);
int parse_nice(const char *p, int *ret);
int parse_ip_port(const char *s, uint16_t *ret);
int parse_ip_port_range(const char *s, uint16_t *low, uint16_t *high);
int parse_ip_prefix_length(const char *s, int *ret);
int parse_oom_score_adjust(const char *s, int *ret);
/* Implement floating point using fixed integers, to improve performance when
* calculating load averages. These macros can be used to extract the integer
* and decimal parts of a value. */
#define LOADAVG_PRECISION_BITS 11
#define LOADAVG_FIXED_POINT_1_0 (1 << LOADAVG_PRECISION_BITS)
#define LOADAVG_INT_SIDE(x) ((x) >> LOADAVG_PRECISION_BITS)
#define LOADAVG_DECIMAL_SIDE(x) LOADAVG_INT_SIDE(((x) & (LOADAVG_FIXED_POINT_1_0 - 1)) * 100)
/* Given a Linux load average (e.g. decimal number 34.89 where 34 is passed as i and 89 is passed as f), convert it
* to a loadavg_t. */
int store_loadavg_fixed_point(unsigned long i, unsigned long f, loadavg_t *ret);
int parse_loadavg_fixed_point(const char *s, loadavg_t *ret);
| 5,504 | 34.516129 | 119 | h |
null | systemd-main/src/basic/path-lookup.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "constants.h"
#include "macro.h"
#include "runtime-scope.h"
typedef enum LookupPathsFlags {
LOOKUP_PATHS_EXCLUDE_GENERATED = 1 << 0,
LOOKUP_PATHS_TEMPORARY_GENERATED = 1 << 1,
LOOKUP_PATHS_SPLIT_USR = 1 << 2,
} LookupPathsFlags;
typedef struct LookupPaths {
/* Where we look for unit files. This includes the individual special paths below, but also any vendor
* supplied, static unit file paths. */
char **search_path;
/* Where we shall create or remove our installation symlinks, aka "configuration", and where the user/admin
* shall place their own unit files. */
char *persistent_config;
char *runtime_config;
/* Where units from a portable service image shall be placed. */
char *persistent_attached;
char *runtime_attached;
/* Where to place generated unit files (i.e. those a "generator" tool generated). Note the special semantics of
* this directory: the generators are flushed each time a "systemctl daemon-reload" is issued. The user should
* not alter these directories directly. */
char *generator;
char *generator_early;
char *generator_late;
/* Where to place transient unit files (i.e. those created dynamically via the bus API). Note the special
* semantics of this directory: all units created transiently have their unit files removed as the transient
* unit is unloaded. The user should not alter this directory directly. */
char *transient;
/* Where the snippets created by "systemctl set-property" are placed. Note that for transient units, the
* snippets are placed in the transient directory though (see above). The user should not alter this directory
* directly. */
char *persistent_control;
char *runtime_control;
/* The root directory prepended to all items above, or NULL */
char *root_dir;
/* A temporary directory when running in test mode, to be nuked */
char *temporary_dir;
} LookupPaths;
int lookup_paths_init(LookupPaths *lp, RuntimeScope scope, LookupPathsFlags flags, const char *root_dir);
int lookup_paths_init_or_warn(LookupPaths *lp, RuntimeScope scope, LookupPathsFlags flags, const char *root_dir);
int xdg_user_dirs(char ***ret_config_dirs, char ***ret_data_dirs);
int xdg_user_runtime_dir(char **ret, const char *suffix);
int xdg_user_config_dir(char **ret, const char *suffix);
int xdg_user_data_dir(char **ret, const char *suffix);
bool path_is_user_data_dir(const char *path);
bool path_is_user_config_dir(const char *path);
void lookup_paths_log(LookupPaths *p);
void lookup_paths_free(LookupPaths *p);
char **generator_binary_paths(RuntimeScope scope);
char **env_generator_binary_paths(RuntimeScope scope);
#define NETWORK_DIRS ((const char* const*) CONF_PATHS_STRV("systemd/network"))
#define NETWORK_DIRS_NULSTR CONF_PATHS_NULSTR("systemd/network")
#define PORTABLE_PROFILE_DIRS CONF_PATHS_NULSTR("systemd/portable/profile")
int find_portable_profile(const char *name, const char *unit, char **ret_path);
| 3,245 | 41.155844 | 119 | h |
null | systemd-main/src/basic/pcapng.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/*
* For details about the file format see RFC:
* https://www.ietf.org/id/draft-tuexen-opsawg-pcapng-03.html
* and
* https://github.com/pcapng/pcapng/
*/
enum pcapng_block_types {
PCAPNG_INTERFACE_BLOCK = 1,
PCAPNG_PACKET_BLOCK, /* Obsolete */
PCAPNG_SIMPLE_PACKET_BLOCK,
PCAPNG_NAME_RESOLUTION_BLOCK,
PCAPNG_INTERFACE_STATS_BLOCK,
PCAPNG_ENHANCED_PACKET_BLOCK,
PCAPNG_SECTION_BLOCK = 0x0A0D0D0A,
};
struct pcapng_option {
uint16_t code;
uint16_t length;
uint8_t data[];
};
#define PCAPNG_BYTE_ORDER_MAGIC 0x1A2B3C4D
#define PCAPNG_MAJOR_VERS 1
#define PCAPNG_MINOR_VERS 0
enum pcapng_opt {
PCAPNG_OPT_END = 0,
PCAPNG_OPT_COMMENT = 1,
};
struct pcapng_section {
uint32_t block_type;
uint32_t block_length;
uint32_t byte_order_magic;
uint16_t major_version;
uint16_t minor_version;
uint64_t section_length;
};
enum pcapng_section_opt {
PCAPNG_SHB_HARDWARE = 2,
PCAPNG_SHB_OS = 3,
PCAPNG_SHB_USERAPPL = 4,
};
struct pcapng_interface_block {
uint32_t block_type; /* 1 */
uint32_t block_length;
uint16_t link_type;
uint16_t reserved;
uint32_t snap_len;
};
enum pcapng_interface_options {
PCAPNG_IFB_NAME = 2,
PCAPNG_IFB_DESCRIPTION,
PCAPNG_IFB_IPV4ADDR,
PCAPNG_IFB_IPV6ADDR,
PCAPNG_IFB_MACADDR,
PCAPNG_IFB_EUIADDR,
PCAPNG_IFB_SPEED,
PCAPNG_IFB_TSRESOL,
PCAPNG_IFB_TZONE,
PCAPNG_IFB_FILTER,
PCAPNG_IFB_OS,
PCAPNG_IFB_FCSLEN,
PCAPNG_IFB_TSOFFSET,
PCAPNG_IFB_HARDWARE,
};
struct pcapng_enhance_packet_block {
uint32_t block_type; /* 6 */
uint32_t block_length;
uint32_t interface_id;
uint32_t timestamp_hi;
uint32_t timestamp_lo;
uint32_t capture_length;
uint32_t original_length;
};
/* Flags values */
#define PCAPNG_IFB_INBOUND 0b01
#define PCAPNG_IFB_OUTBOUND 0b10
enum pcapng_epb_options {
PCAPNG_EPB_FLAGS = 2,
PCAPNG_EPB_HASH,
PCAPNG_EPB_DROPCOUNT,
PCAPNG_EPB_PACKETID,
PCAPNG_EPB_QUEUE,
PCAPNG_EPB_VERDICT,
};
struct pcapng_statistics_block {
uint32_t block_type; /* 5 */
uint32_t block_length;
uint32_t interface_id;
uint32_t timestamp_hi;
uint32_t timestamp_lo;
};
enum pcapng_isb_options {
PCAPNG_ISB_STARTTIME = 2,
PCAPNG_ISB_ENDTIME,
PCAPNG_ISB_IFRECV,
PCAPNG_ISB_IFDROP,
PCAPNG_ISB_FILTERACCEPT,
PCAPNG_ISB_OSDROP,
PCAPNG_ISB_USRDELIV,
};
| 2,769 | 22.87931 | 63 | h |
null | systemd-main/src/basic/percent-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "percent-util.h"
#include "string-util.h"
#include "parse-util.h"
static int parse_parts_value_whole(const char *p, const char *symbol) {
const char *pc, *n;
int r, v;
pc = endswith(p, symbol);
if (!pc)
return -EINVAL;
n = strndupa_safe(p, pc - p);
r = safe_atoi(n, &v);
if (r < 0)
return r;
if (v < 0)
return -ERANGE;
return v;
}
static int parse_parts_value_with_tenths_place(const char *p, const char *symbol) {
const char *pc, *dot, *n;
int r, q, v;
pc = endswith(p, symbol);
if (!pc)
return -EINVAL;
dot = memchr(p, '.', pc - p);
if (dot) {
if (dot + 2 != pc)
return -EINVAL;
if (dot[1] < '0' || dot[1] > '9')
return -EINVAL;
q = dot[1] - '0';
n = strndupa_safe(p, dot - p);
} else {
q = 0;
n = strndupa_safe(p, pc - p);
}
r = safe_atoi(n, &v);
if (r < 0)
return r;
if (v < 0)
return -ERANGE;
if (v > (INT_MAX - q) / 10)
return -ERANGE;
v = v * 10 + q;
return v;
}
static int parse_parts_value_with_hundredths_place(const char *p, const char *symbol) {
const char *pc, *dot, *n;
int r, q, v;
pc = endswith(p, symbol);
if (!pc)
return -EINVAL;
dot = memchr(p, '.', pc - p);
if (dot) {
if (dot + 3 == pc) {
/* Support two places after the dot */
if (dot[1] < '0' || dot[1] > '9' || dot[2] < '0' || dot[2] > '9')
return -EINVAL;
q = (dot[1] - '0') * 10 + (dot[2] - '0');
} else if (dot + 2 == pc) {
/* Support one place after the dot */
if (dot[1] < '0' || dot[1] > '9')
return -EINVAL;
q = (dot[1] - '0') * 10;
} else
/* We do not support zero or more than two places */
return -EINVAL;
n = strndupa_safe(p, dot - p);
} else {
q = 0;
n = strndupa_safe(p, pc - p);
}
r = safe_atoi(n, &v);
if (r < 0)
return r;
if (v < 0)
return -ERANGE;
if (v > (INT_MAX - q) / 100)
return -ERANGE;
v = v * 100 + q;
return v;
}
int parse_percent_unbounded(const char *p) {
return parse_parts_value_whole(p, "%");
}
int parse_percent(const char *p) {
int v;
v = parse_percent_unbounded(p);
if (v > 100)
return -ERANGE;
return v;
}
int parse_permille_unbounded(const char *p) {
const char *pm;
pm = endswith(p, "‰");
if (pm)
return parse_parts_value_whole(p, "‰");
return parse_parts_value_with_tenths_place(p, "%");
}
int parse_permille(const char *p) {
int v;
v = parse_permille_unbounded(p);
if (v > 1000)
return -ERANGE;
return v;
}
int parse_permyriad_unbounded(const char *p) {
const char *pm;
pm = endswith(p, "‱");
if (pm)
return parse_parts_value_whole(p, "‱");
pm = endswith(p, "‰");
if (pm)
return parse_parts_value_with_tenths_place(p, "‰");
return parse_parts_value_with_hundredths_place(p, "%");
}
int parse_permyriad(const char *p) {
int v;
v = parse_permyriad_unbounded(p);
if (v > 10000)
return -ERANGE;
return v;
}
| 3,956 | 24.044304 | 89 | c |
null | systemd-main/src/basic/percent-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include <inttypes.h>
#include "macro.h"
int parse_percent_unbounded(const char *p);
int parse_percent(const char *p);
int parse_permille_unbounded(const char *p);
int parse_permille(const char *p);
int parse_permyriad_unbounded(const char *p);
int parse_permyriad(const char *p);
/* Some macro-like helpers that convert a percent/permille/permyriad value (as parsed by parse_percent()) to
* a value relative to 100% == 2^32-1. Rounds to closest. */
static inline uint32_t UINT32_SCALE_FROM_PERCENT(int percent) {
assert_cc(INT_MAX <= UINT32_MAX);
return (uint32_t) (((uint64_t) CLAMP(percent, 0, 100) * UINT32_MAX + 50) / 100U);
}
static inline uint32_t UINT32_SCALE_FROM_PERMILLE(int permille) {
return (uint32_t) (((uint64_t) CLAMP(permille, 0, 1000) * UINT32_MAX + 500) / 1000U);
}
static inline uint32_t UINT32_SCALE_FROM_PERMYRIAD(int permyriad) {
return (uint32_t) (((uint64_t) CLAMP(permyriad, 0, 10000) * UINT32_MAX + 5000) / 10000U);
}
static inline int UINT32_SCALE_TO_PERCENT(uint32_t scale) {
uint32_t u;
u = (uint32_t) ((((uint64_t) scale) * 100U + UINT32_MAX/2) / UINT32_MAX);
if (u > INT_MAX)
return -ERANGE;
return (int) u;
}
static inline int UINT32_SCALE_TO_PERMILLE(uint32_t scale) {
uint32_t u;
u = (uint32_t) ((((uint64_t) scale) * 1000U + UINT32_MAX/2) / UINT32_MAX);
if (u > INT_MAX)
return -ERANGE;
return (int) u;
}
static inline int UINT32_SCALE_TO_PERMYRIAD(uint32_t scale) {
uint32_t u;
u = (uint32_t) ((((uint64_t) scale) * 10000U + UINT32_MAX/2) / UINT32_MAX);
if (u > INT_MAX)
return -ERANGE;
return (int) u;
}
#define PERMYRIAD_AS_PERCENT_FORMAT_STR "%i.%02i%%"
#define PERMYRIAD_AS_PERCENT_FORMAT_VAL(x) ((x)/100), ((x)%100)
| 1,936 | 28.348485 | 108 | h |
null | systemd-main/src/basic/prioq.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
/*
* Priority Queue
* The prioq object implements a priority queue. That is, it orders objects by
* their priority and allows O(1) access to the object with the highest
* priority. Insertion and removal are Θ(log n). Optionally, the caller can
* provide a pointer to an index which will be kept up-to-date by the prioq.
*
* The underlying algorithm used in this implementation is a Heap.
*/
#include <errno.h>
#include <stdlib.h>
#include "alloc-util.h"
#include "hashmap.h"
#include "prioq.h"
struct prioq_item {
void *data;
unsigned *idx;
};
struct Prioq {
compare_func_t compare_func;
unsigned n_items, n_allocated;
struct prioq_item *items;
};
Prioq *prioq_new(compare_func_t compare_func) {
Prioq *q;
q = new(Prioq, 1);
if (!q)
return q;
*q = (Prioq) {
.compare_func = compare_func,
};
return q;
}
Prioq* prioq_free(Prioq *q) {
if (!q)
return NULL;
free(q->items);
return mfree(q);
}
int prioq_ensure_allocated(Prioq **q, compare_func_t compare_func) {
assert(q);
if (*q)
return 0;
*q = prioq_new(compare_func);
if (!*q)
return -ENOMEM;
return 0;
}
static void swap(Prioq *q, unsigned j, unsigned k) {
assert(q);
assert(j < q->n_items);
assert(k < q->n_items);
assert(!q->items[j].idx || *(q->items[j].idx) == j);
assert(!q->items[k].idx || *(q->items[k].idx) == k);
SWAP_TWO(q->items[j].data, q->items[k].data);
SWAP_TWO(q->items[j].idx, q->items[k].idx);
if (q->items[j].idx)
*q->items[j].idx = j;
if (q->items[k].idx)
*q->items[k].idx = k;
}
static unsigned shuffle_up(Prioq *q, unsigned idx) {
assert(q);
assert(idx < q->n_items);
while (idx > 0) {
unsigned k;
k = (idx-1)/2;
if (q->compare_func(q->items[k].data, q->items[idx].data) <= 0)
break;
swap(q, idx, k);
idx = k;
}
return idx;
}
static unsigned shuffle_down(Prioq *q, unsigned idx) {
assert(q);
for (;;) {
unsigned j, k, s;
k = (idx+1)*2; /* right child */
j = k-1; /* left child */
if (j >= q->n_items)
break;
if (q->compare_func(q->items[j].data, q->items[idx].data) < 0)
/* So our left child is smaller than we are, let's
* remember this fact */
s = j;
else
s = idx;
if (k < q->n_items &&
q->compare_func(q->items[k].data, q->items[s].data) < 0)
/* So our right child is smaller than we are, let's
* remember this fact */
s = k;
/* s now points to the smallest of the three items */
if (s == idx)
/* No swap necessary, we're done */
break;
swap(q, idx, s);
idx = s;
}
return idx;
}
int prioq_put(Prioq *q, void *data, unsigned *idx) {
struct prioq_item *i;
unsigned k;
assert(q);
if (q->n_items >= q->n_allocated) {
unsigned n;
struct prioq_item *j;
n = MAX((q->n_items+1) * 2, 16u);
j = reallocarray(q->items, n, sizeof(struct prioq_item));
if (!j)
return -ENOMEM;
q->items = j;
q->n_allocated = n;
}
k = q->n_items++;
i = q->items + k;
i->data = data;
i->idx = idx;
if (idx)
*idx = k;
shuffle_up(q, k);
return 0;
}
int prioq_ensure_put(Prioq **q, compare_func_t compare_func, void *data, unsigned *idx) {
int r;
r = prioq_ensure_allocated(q, compare_func);
if (r < 0)
return r;
return prioq_put(*q, data, idx);
}
static void remove_item(Prioq *q, struct prioq_item *i) {
struct prioq_item *l;
assert(q);
assert(i);
l = q->items + q->n_items - 1;
if (i == l)
/* Last entry, let's just remove it */
q->n_items--;
else {
unsigned k;
/* Not last entry, let's replace the last entry with
* this one, and reshuffle */
k = i - q->items;
i->data = l->data;
i->idx = l->idx;
if (i->idx)
*i->idx = k;
q->n_items--;
k = shuffle_down(q, k);
shuffle_up(q, k);
}
}
_pure_ static struct prioq_item* find_item(Prioq *q, void *data, unsigned *idx) {
struct prioq_item *i;
assert(q);
if (q->n_items <= 0)
return NULL;
if (idx) {
if (*idx == PRIOQ_IDX_NULL ||
*idx >= q->n_items)
return NULL;
i = q->items + *idx;
if (i->data != data)
return NULL;
return i;
} else {
for (i = q->items; i < q->items + q->n_items; i++)
if (i->data == data)
return i;
return NULL;
}
}
int prioq_remove(Prioq *q, void *data, unsigned *idx) {
struct prioq_item *i;
if (!q)
return 0;
i = find_item(q, data, idx);
if (!i)
return 0;
remove_item(q, i);
return 1;
}
void prioq_reshuffle(Prioq *q, void *data, unsigned *idx) {
struct prioq_item *i;
unsigned k;
assert(q);
i = find_item(q, data, idx);
if (!i)
return;
k = i - q->items;
k = shuffle_down(q, k);
shuffle_up(q, k);
}
void *prioq_peek_by_index(Prioq *q, unsigned idx) {
if (!q)
return NULL;
if (idx >= q->n_items)
return NULL;
return q->items[idx].data;
}
void *prioq_pop(Prioq *q) {
void *data;
if (!q)
return NULL;
if (q->n_items <= 0)
return NULL;
data = q->items[0].data;
remove_item(q, q->items);
return data;
}
unsigned prioq_size(Prioq *q) {
if (!q)
return 0;
return q->n_items;
}
bool prioq_isempty(Prioq *q) {
if (!q)
return true;
return q->n_items <= 0;
}
| 6,967 | 21.477419 | 89 | c |
null | systemd-main/src/basic/prioq.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "hashmap.h"
#include "macro.h"
typedef struct Prioq Prioq;
#define PRIOQ_IDX_NULL (UINT_MAX)
Prioq *prioq_new(compare_func_t compare);
Prioq *prioq_free(Prioq *q);
DEFINE_TRIVIAL_CLEANUP_FUNC(Prioq*, prioq_free);
int prioq_ensure_allocated(Prioq **q, compare_func_t compare_func);
int prioq_put(Prioq *q, void *data, unsigned *idx);
int prioq_ensure_put(Prioq **q, compare_func_t compare_func, void *data, unsigned *idx);
int prioq_remove(Prioq *q, void *data, unsigned *idx);
void prioq_reshuffle(Prioq *q, void *data, unsigned *idx);
void *prioq_peek_by_index(Prioq *q, unsigned idx) _pure_;
static inline void *prioq_peek(Prioq *q) {
return prioq_peek_by_index(q, 0);
}
void *prioq_pop(Prioq *q);
#define PRIOQ_FOREACH_ITEM(q, p) \
for (unsigned _i = 0; (p = prioq_peek_by_index(q, _i)); _i++)
unsigned prioq_size(Prioq *q) _pure_;
bool prioq_isempty(Prioq *q) _pure_;
| 1,020 | 29.029412 | 88 | h |
null | systemd-main/src/basic/proc-cmdline.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdbool.h>
#include <stddef.h>
#include "alloc-util.h"
#include "efivars.h"
#include "extract-word.h"
#include "fileio.h"
#include "getopt-defs.h"
#include "initrd-util.h"
#include "macro.h"
#include "parse-util.h"
#include "proc-cmdline.h"
#include "process-util.h"
#include "string-util.h"
#include "strv.h"
#include "virt.h"
int proc_cmdline_filter_pid1_args(char **argv, char ***ret) {
enum {
COMMON_GETOPT_ARGS,
SYSTEMD_GETOPT_ARGS,
SHUTDOWN_GETOPT_ARGS,
};
static const struct option options[] = {
COMMON_GETOPT_OPTIONS,
SYSTEMD_GETOPT_OPTIONS,
SHUTDOWN_GETOPT_OPTIONS,
};
static const char *short_options = SYSTEMD_GETOPT_SHORT_OPTIONS;
_cleanup_strv_free_ char **filtered = NULL;
int state, r;
assert(argv);
assert(ret);
/* Currently, we do not support '-', '+', and ':' at the beginning. */
assert(!IN_SET(short_options[0], '-', '+', ':'));
/* Filter out all known options. */
state = no_argument;
STRV_FOREACH(p, strv_skip(argv, 1)) {
int prev_state = state;
const char *a = *p;
/* Reset the state for the next step. */
state = no_argument;
if (prev_state == required_argument ||
(prev_state == optional_argument && a[0] != '-'))
/* Handled as an argument of the previous option, filtering out the string. */
continue;
if (a[0] != '-') {
/* Not an option, accepting the string. */
r = strv_extend(&filtered, a);
if (r < 0)
return r;
continue;
}
if (a[1] == '-') {
if (a[2] == '\0') {
/* "--" is specified, accepting remaining strings. */
r = strv_extend_strv(&filtered, strv_skip(p, 1), /* filter_duplicates = */ false);
if (r < 0)
return r;
break;
}
/* long option, e.g. --foo */
for (size_t i = 0; i < ELEMENTSOF(options); i++) {
const char *q = startswith(a + 2, options[i].name);
if (!q || !IN_SET(q[0], '=', '\0'))
continue;
/* Found matching option, updating the state if necessary. */
if (q[0] == '\0' && options[i].has_arg == required_argument)
state = required_argument;
break;
}
continue;
}
/* short option(s), e.g. -x or -xyz */
while (a && *++a != '\0')
for (const char *q = short_options; *q != '\0'; q++) {
if (*q != *a)
continue;
/* Found matching short option. */
if (q[1] == ':') {
/* An argument is required or optional, and remaining part
* is handled as argument if exists. */
state = a[1] != '\0' ? no_argument :
q[2] == ':' ? optional_argument : required_argument;
a = NULL; /* Not necessary to parse remaining part. */
}
break;
}
}
*ret = TAKE_PTR(filtered);
return 0;
}
int proc_cmdline(char **ret) {
const char *e;
assert(ret);
/* For testing purposes it is sometimes useful to be able to override what we consider /proc/cmdline to be */
e = secure_getenv("SYSTEMD_PROC_CMDLINE");
if (e) {
char *m;
m = strdup(e);
if (!m)
return -ENOMEM;
*ret = m;
return 0;
}
if (detect_container() > 0)
return get_process_cmdline(1, SIZE_MAX, 0, ret);
else
return read_full_file("/proc/cmdline", ret, NULL);
}
static int proc_cmdline_strv_internal(char ***ret, bool filter_pid1_args) {
const char *e;
int r;
assert(ret);
/* For testing purposes it is sometimes useful to be able to override what we consider /proc/cmdline to be */
e = secure_getenv("SYSTEMD_PROC_CMDLINE");
if (e)
return strv_split_full(ret, e, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX|EXTRACT_RETAIN_ESCAPE);
if (detect_container() > 0) {
_cleanup_strv_free_ char **args = NULL;
r = get_process_cmdline_strv(1, /* flags = */ 0, &args);
if (r < 0)
return r;
if (filter_pid1_args)
return proc_cmdline_filter_pid1_args(args, ret);
*ret = TAKE_PTR(args);
return 0;
} else {
_cleanup_free_ char *s = NULL;
r = read_full_file("/proc/cmdline", &s, NULL);
if (r < 0)
return r;
return strv_split_full(ret, s, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX|EXTRACT_RETAIN_ESCAPE);
}
}
int proc_cmdline_strv(char ***ret) {
return proc_cmdline_strv_internal(ret, /* filter_pid1_args = */ false);
}
static char *mangle_word(const char *word, ProcCmdlineFlags flags) {
char *c;
c = startswith(word, "rd.");
if (c) {
/* Filter out arguments that are intended only for the initrd */
if (!in_initrd())
return NULL;
if (FLAGS_SET(flags, PROC_CMDLINE_STRIP_RD_PREFIX))
return c;
} else if (FLAGS_SET(flags, PROC_CMDLINE_RD_STRICT) && in_initrd())
/* And optionally filter out arguments that are intended only for the host */
return NULL;
return (char*) word;
}
static int proc_cmdline_parse_strv(char **args, proc_cmdline_parse_t parse_item, void *data, ProcCmdlineFlags flags) {
int r;
assert(parse_item);
/* The PROC_CMDLINE_VALUE_OPTIONAL flag doesn't really make sense for proc_cmdline_parse(), let's
* make this clear. */
assert(!FLAGS_SET(flags, PROC_CMDLINE_VALUE_OPTIONAL));
STRV_FOREACH(word, args) {
char *key, *value;
key = mangle_word(*word, flags);
if (!key)
continue;
value = strchr(key, '=');
if (value)
*(value++) = '\0';
r = parse_item(key, value, data);
if (r < 0)
return r;
}
return 0;
}
int proc_cmdline_parse(proc_cmdline_parse_t parse_item, void *data, ProcCmdlineFlags flags) {
_cleanup_strv_free_ char **args = NULL;
int r;
assert(parse_item);
/* We parse the EFI variable first, because later settings have higher priority. */
if (!FLAGS_SET(flags, PROC_CMDLINE_IGNORE_EFI_OPTIONS)) {
_cleanup_free_ char *line = NULL;
r = systemd_efi_options_variable(&line);
if (r < 0) {
if (r != -ENODATA)
log_debug_errno(r, "Failed to get SystemdOptions EFI variable, ignoring: %m");
} else {
r = strv_split_full(&args, line, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX|EXTRACT_RETAIN_ESCAPE);
if (r < 0)
return r;
r = proc_cmdline_parse_strv(args, parse_item, data, flags);
if (r < 0)
return r;
args = strv_free(args);
}
}
r = proc_cmdline_strv_internal(&args, /* filter_pid1_args = */ true);
if (r < 0)
return r;
return proc_cmdline_parse_strv(args, parse_item, data, flags);
}
static bool relaxed_equal_char(char a, char b) {
return a == b ||
(a == '_' && b == '-') ||
(a == '-' && b == '_');
}
char *proc_cmdline_key_startswith(const char *s, const char *prefix) {
assert(s);
assert(prefix);
/* Much like startswith(), but considers "-" and "_" the same */
for (; *prefix != 0; s++, prefix++)
if (!relaxed_equal_char(*s, *prefix))
return NULL;
return (char*) s;
}
bool proc_cmdline_key_streq(const char *x, const char *y) {
assert(x);
assert(y);
/* Much like streq(), but considers "-" and "_" the same */
for (; *x != 0 || *y != 0; x++, y++)
if (!relaxed_equal_char(*x, *y))
return false;
return true;
}
static int cmdline_get_key(char **args, const char *key, ProcCmdlineFlags flags, char **ret_value) {
_cleanup_free_ char *v = NULL;
bool found = false;
int r;
assert(key);
STRV_FOREACH(p, args) {
const char *word;
word = mangle_word(*p, flags);
if (!word)
continue;
if (ret_value) {
const char *e;
e = proc_cmdline_key_startswith(word, key);
if (!e)
continue;
if (*e == '=') {
r = free_and_strdup(&v, e+1);
if (r < 0)
return r;
found = true;
} else if (*e == 0 && FLAGS_SET(flags, PROC_CMDLINE_VALUE_OPTIONAL))
found = true;
} else {
if (proc_cmdline_key_streq(word, key)) {
found = true;
break; /* we found what we were looking for */
}
}
}
if (ret_value)
*ret_value = TAKE_PTR(v);
return found;
}
int proc_cmdline_get_key(const char *key, ProcCmdlineFlags flags, char **ret_value) {
_cleanup_strv_free_ char **args = NULL;
_cleanup_free_ char *line = NULL, *v = NULL;
int r;
/* Looks for a specific key on the kernel command line and (with lower priority) the EFI variable.
* Supports three modes:
*
* a) The "ret_value" parameter is used. In this case a parameter beginning with the "key" string followed by
* "=" is searched for, and the value following it is returned in "ret_value".
*
* b) as above, but the PROC_CMDLINE_VALUE_OPTIONAL flag is set. In this case if the key is found as a separate
* word (i.e. not followed by "=" but instead by whitespace or the end of the command line), then this is
* also accepted, and "value" is returned as NULL.
*
* c) The "ret_value" parameter is NULL. In this case a search for the exact "key" parameter is performed.
*
* In all three cases, > 0 is returned if the key is found, 0 if not. */
if (isempty(key))
return -EINVAL;
if (FLAGS_SET(flags, PROC_CMDLINE_VALUE_OPTIONAL) && !ret_value)
return -EINVAL;
r = proc_cmdline_strv_internal(&args, /* filter_pid1_args = */ true);
if (r < 0)
return r;
if (FLAGS_SET(flags, PROC_CMDLINE_IGNORE_EFI_OPTIONS)) /* Shortcut */
return cmdline_get_key(args, key, flags, ret_value);
r = cmdline_get_key(args, key, flags, ret_value ? &v : NULL);
if (r < 0)
return r;
if (r > 0) {
if (ret_value)
*ret_value = TAKE_PTR(v);
return r;
}
r = systemd_efi_options_variable(&line);
if (r == -ENODATA) {
if (ret_value)
*ret_value = NULL;
return false; /* Not found */
}
if (r < 0)
return r;
args = strv_free(args);
r = strv_split_full(&args, line, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX|EXTRACT_RETAIN_ESCAPE);
if (r < 0)
return r;
return cmdline_get_key(args, key, flags, ret_value);
}
int proc_cmdline_get_bool(const char *key, bool *ret) {
_cleanup_free_ char *v = NULL;
int r;
assert(ret);
r = proc_cmdline_get_key(key, PROC_CMDLINE_VALUE_OPTIONAL, &v);
if (r < 0)
return r;
if (r == 0) { /* key not specified at all */
*ret = false;
return 0;
}
if (v) { /* key with parameter passed */
r = parse_boolean(v);
if (r < 0)
return r;
*ret = r;
} else /* key without parameter passed */
*ret = true;
return 1;
}
static int cmdline_get_key_ap(ProcCmdlineFlags flags, char* const* args, va_list ap) {
int r, ret = 0;
for (;;) {
char **v;
const char *k, *e;
k = va_arg(ap, const char*);
if (!k)
break;
assert_se(v = va_arg(ap, char**));
STRV_FOREACH(p, args) {
const char *word;
word = mangle_word(*p, flags);
if (!word)
continue;
e = proc_cmdline_key_startswith(word, k);
if (e && *e == '=') {
r = free_and_strdup(v, e + 1);
if (r < 0)
return r;
ret++;
}
}
}
return ret;
}
int proc_cmdline_get_key_many_internal(ProcCmdlineFlags flags, ...) {
_cleanup_strv_free_ char **args = NULL;
int r, ret = 0;
va_list ap;
/* The PROC_CMDLINE_VALUE_OPTIONAL flag doesn't really make sense for proc_cmdline_get_key_many(), let's make
* this clear. */
assert(!FLAGS_SET(flags, PROC_CMDLINE_VALUE_OPTIONAL));
/* This call may clobber arguments on failure! */
if (!FLAGS_SET(flags, PROC_CMDLINE_IGNORE_EFI_OPTIONS)) {
_cleanup_free_ char *line = NULL;
r = systemd_efi_options_variable(&line);
if (r < 0 && r != -ENODATA)
log_debug_errno(r, "Failed to get SystemdOptions EFI variable, ignoring: %m");
if (r >= 0) {
r = strv_split_full(&args, line, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX|EXTRACT_RETAIN_ESCAPE);
if (r < 0)
return r;
va_start(ap, flags);
r = cmdline_get_key_ap(flags, args, ap);
va_end(ap);
if (r < 0)
return r;
ret = r;
args = strv_free(args);
}
}
r = proc_cmdline_strv(&args);
if (r < 0)
return r;
va_start(ap, flags);
r = cmdline_get_key_ap(flags, args, ap);
va_end(ap);
if (r < 0)
return r;
return ret + r;
}
| 16,342 | 31.751503 | 119 | c |
null | systemd-main/src/basic/procfs-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <unistd.h>
#include "alloc-util.h"
#include "constants.h"
#include "fd-util.h"
#include "fileio.h"
#include "parse-util.h"
#include "process-util.h"
#include "procfs-util.h"
#include "stdio-util.h"
#include "string-util.h"
int procfs_get_pid_max(uint64_t *ret) {
_cleanup_free_ char *value = NULL;
int r;
assert(ret);
r = read_one_line_file("/proc/sys/kernel/pid_max", &value);
if (r < 0)
return r;
return safe_atou64(value, ret);
}
int procfs_get_threads_max(uint64_t *ret) {
_cleanup_free_ char *value = NULL;
int r;
assert(ret);
r = read_one_line_file("/proc/sys/kernel/threads-max", &value);
if (r < 0)
return r;
return safe_atou64(value, ret);
}
int procfs_tasks_set_limit(uint64_t limit) {
char buffer[DECIMAL_STR_MAX(uint64_t)+1];
uint64_t pid_max;
int r;
if (limit == 0) /* This makes no sense, we are userspace and hence count as tasks too, and we want to live,
* hence the limit conceptually has to be above 0. Also, most likely if anyone asks for a zero
* limit they probably mean "no limit", hence let's better refuse this to avoid
* confusion. */
return -EINVAL;
/* The Linux kernel doesn't allow this value to go below 20, hence don't allow this either, higher values than
* TASKS_MAX are not accepted by the pid_max sysctl. We'll treat anything this high as "unbounded" and hence
* set it to the maximum. */
limit = CLAMP(limit, 20U, TASKS_MAX);
r = procfs_get_pid_max(&pid_max);
if (r < 0)
return r;
/* As pid_max is about the numeric pid_t range we'll bump it if necessary, but only ever increase it, never
* decrease it, as threads-max is the much more relevant sysctl. */
if (limit > pid_max-1) {
sprintf(buffer, "%" PRIu64, limit+1); /* Add one, since PID 0 is not a valid PID */
r = write_string_file("/proc/sys/kernel/pid_max", buffer, WRITE_STRING_FILE_DISABLE_BUFFER);
if (r < 0)
return r;
}
sprintf(buffer, "%" PRIu64, limit);
r = write_string_file("/proc/sys/kernel/threads-max", buffer, WRITE_STRING_FILE_DISABLE_BUFFER);
if (r < 0) {
uint64_t threads_max;
/* Hmm, we couldn't write this? If so, maybe it was already set properly? In that case let's not
* generate an error */
if (procfs_get_threads_max(&threads_max) < 0)
return r; /* return original error */
if (MIN(pid_max - 1, threads_max) != limit)
return r; /* return original error */
/* Yay! Value set already matches what we were trying to set, hence consider this a success. */
}
return 0;
}
int procfs_tasks_get_current(uint64_t *ret) {
_cleanup_free_ char *value = NULL;
const char *p, *nr;
size_t n;
int r;
assert(ret);
r = read_one_line_file("/proc/loadavg", &value);
if (r < 0)
return r;
/* Look for the second part of the fourth field, which is separated by a slash from the first part. None of the
* earlier fields use a slash, hence let's use this to find the right spot. */
p = strchr(value, '/');
if (!p)
return -EINVAL;
p++;
n = strspn(p, DIGITS);
nr = strndupa_safe(p, n);
return safe_atou64(nr, ret);
}
static uint64_t calc_gcd64(uint64_t a, uint64_t b) {
while (b > 0) {
uint64_t t;
t = a % b;
a = b;
b = t;
}
return a;
}
int procfs_cpu_get_usage(nsec_t *ret) {
_cleanup_free_ char *first_line = NULL;
unsigned long user_ticks, nice_ticks, system_ticks, irq_ticks, softirq_ticks,
guest_ticks = 0, guest_nice_ticks = 0;
long ticks_per_second;
uint64_t sum, gcd, a, b;
const char *p;
int r;
assert(ret);
r = read_one_line_file("/proc/stat", &first_line);
if (r < 0)
return r;
p = first_word(first_line, "cpu");
if (!p)
return -EINVAL;
if (sscanf(p, "%lu %lu %lu %*u %*u %lu %lu %*u %lu %lu",
&user_ticks,
&nice_ticks,
&system_ticks,
&irq_ticks,
&softirq_ticks,
&guest_ticks,
&guest_nice_ticks) < 5) /* we only insist on the first five fields */
return -EINVAL;
ticks_per_second = sysconf(_SC_CLK_TCK);
if (ticks_per_second < 0)
return -errno;
assert(ticks_per_second > 0);
sum = (uint64_t) user_ticks + (uint64_t) nice_ticks + (uint64_t) system_ticks +
(uint64_t) irq_ticks + (uint64_t) softirq_ticks +
(uint64_t) guest_ticks + (uint64_t) guest_nice_ticks;
/* Let's reduce this fraction before we apply it to avoid overflows when converting this to μsec */
gcd = calc_gcd64(NSEC_PER_SEC, ticks_per_second);
a = (uint64_t) NSEC_PER_SEC / gcd;
b = (uint64_t) ticks_per_second / gcd;
*ret = DIV_ROUND_UP((nsec_t) sum * (nsec_t) a, (nsec_t) b);
return 0;
}
int convert_meminfo_value_to_uint64_bytes(const char *word, uint64_t *ret) {
_cleanup_free_ char *w = NULL;
char *digits, *e;
uint64_t v;
size_t n;
int r;
assert(word);
assert(ret);
w = strdup(word);
if (!w)
return -ENOMEM;
/* Determine length of numeric value */
n = strspn(w, WHITESPACE);
digits = w + n;
n = strspn(digits, DIGITS);
if (n == 0)
return -EINVAL;
e = digits + n;
/* Ensure the line ends in " kB" */
n = strspn(e, WHITESPACE);
if (n == 0)
return -EINVAL;
if (!streq(e + n, "kB"))
return -EINVAL;
*e = 0;
r = safe_atou64(digits, &v);
if (r < 0)
return r;
if (v == UINT64_MAX)
return -EINVAL;
if (v > UINT64_MAX/1024)
return -EOVERFLOW;
*ret = v * 1024U;
return 0;
}
int procfs_memory_get(uint64_t *ret_total, uint64_t *ret_used) {
uint64_t mem_total = UINT64_MAX, mem_available = UINT64_MAX;
_cleanup_fclose_ FILE *f = NULL;
int r;
f = fopen("/proc/meminfo", "re");
if (!f)
return -errno;
for (;;) {
_cleanup_free_ char *line = NULL;
uint64_t *v;
char *p;
r = read_line(f, LONG_LINE_MAX, &line);
if (r < 0)
return r;
if (r == 0)
return -EINVAL; /* EOF: Couldn't find one or both fields? */
p = first_word(line, "MemTotal:");
if (p)
v = &mem_total;
else {
p = first_word(line, "MemAvailable:");
if (p)
v = &mem_available;
else
continue;
}
r = convert_meminfo_value_to_uint64_bytes(p, v);
if (r < 0)
return r;
if (mem_total != UINT64_MAX && mem_available != UINT64_MAX)
break;
}
if (mem_available > mem_total)
return -EINVAL;
if (ret_total)
*ret_total = mem_total;
if (ret_used)
*ret_used = mem_total - mem_available;
return 0;
}
| 8,137 | 29.252788 | 119 | c |
null | systemd-main/src/basic/procfs-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include "time-util.h"
int procfs_get_pid_max(uint64_t *ret);
int procfs_get_threads_max(uint64_t *ret);
int procfs_tasks_set_limit(uint64_t limit);
int procfs_tasks_get_current(uint64_t *ret);
int procfs_cpu_get_usage(nsec_t *ret);
int procfs_memory_get(uint64_t *ret_total, uint64_t *ret_used);
static inline int procfs_memory_get_used(uint64_t *ret) {
return procfs_memory_get(NULL, ret);
}
int convert_meminfo_value_to_uint64_bytes(const char *word, uint64_t *ret);
| 569 | 24.909091 | 75 | h |
null | systemd-main/src/basic/psi-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdio.h>
#include <unistd.h>
#include "alloc-util.h"
#include "errno-util.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fileio.h"
#include "missing_threads.h"
#include "parse-util.h"
#include "psi-util.h"
#include "string-util.h"
#include "stat-util.h"
#include "strv.h"
int read_resource_pressure(const char *path, PressureType type, ResourcePressure *ret) {
_cleanup_free_ char *line = NULL;
_cleanup_fclose_ FILE *f = NULL;
unsigned field_filled = 0;
ResourcePressure rp = {};
const char *t, *cline;
char *word;
int r;
assert(path);
assert(IN_SET(type, PRESSURE_TYPE_SOME, PRESSURE_TYPE_FULL));
assert(ret);
if (type == PRESSURE_TYPE_SOME)
t = "some";
else if (type == PRESSURE_TYPE_FULL)
t = "full";
else
return -EINVAL;
r = fopen_unlocked(path, "re", &f);
if (r < 0)
return r;
for (;;) {
_cleanup_free_ char *l = NULL;
char *w;
r = read_line(f, LONG_LINE_MAX, &l);
if (r < 0)
return r;
if (r == 0)
break;
w = first_word(l, t);
if (w) {
line = TAKE_PTR(l);
cline = w;
break;
}
}
if (!line)
return -ENODATA;
/* extracts either avgX=Y.Z or total=X */
while ((r = extract_first_word(&cline, &word, NULL, 0)) > 0) {
_cleanup_free_ char *w = word;
const char *v;
if ((v = startswith(w, "avg10="))) {
if (field_filled & (1U << 0))
return -EINVAL;
field_filled |= 1U << 0;
r = parse_loadavg_fixed_point(v, &rp.avg10);
} else if ((v = startswith(w, "avg60="))) {
if (field_filled & (1U << 1))
return -EINVAL;
field_filled |= 1U << 1;
r = parse_loadavg_fixed_point(v, &rp.avg60);
} else if ((v = startswith(w, "avg300="))) {
if (field_filled & (1U << 2))
return -EINVAL;
field_filled |= 1U << 2;
r = parse_loadavg_fixed_point(v, &rp.avg300);
} else if ((v = startswith(w, "total="))) {
if (field_filled & (1U << 3))
return -EINVAL;
field_filled |= 1U << 3;
r = safe_atou64(v, &rp.total);
} else
continue;
if (r < 0)
return r;
}
if (r < 0)
return r;
if (field_filled != 15U)
return -EINVAL;
*ret = rp;
return 0;
}
int is_pressure_supported(void) {
static thread_local int cached = -1;
int r;
/* The pressure files, both under /proc/ and in cgroups, will exist even if the kernel has PSI
* support disabled; we have to read the file to make sure it doesn't return -EOPNOTSUPP */
if (cached >= 0)
return cached;
FOREACH_STRING(p, "/proc/pressure/cpu", "/proc/pressure/io", "/proc/pressure/memory") {
r = read_virtual_file(p, 0, NULL, NULL);
if (r < 0) {
if (r == -ENOENT || ERRNO_IS_NOT_SUPPORTED(r))
return (cached = false);
return r;
}
}
return (cached = true);
}
| 3,918 | 28.916031 | 102 | c |
null | systemd-main/src/basic/psi-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "parse-util.h"
#include "time-util.h"
typedef enum PressureType {
PRESSURE_TYPE_SOME,
PRESSURE_TYPE_FULL,
} PressureType;
/* Averages are stored in fixed-point with 11 bit fractions */
typedef struct ResourcePressure {
loadavg_t avg10;
loadavg_t avg60;
loadavg_t avg300;
usec_t total;
} ResourcePressure;
/** Upstream 4.20+ format
*
* some avg10=0.22 avg60=0.17 avg300=1.11 total=58761459
* full avg10=0.23 avg60=0.16 avg300=1.08 total=58464525
*/
int read_resource_pressure(const char *path, PressureType type, ResourcePressure *ret);
/* Was the kernel compiled with CONFIG_PSI=y? 1 if yes, 0 if not, negative on error. */
int is_pressure_supported(void);
/* Default parameters for memory pressure watch logic in sd-event and PID 1 */
#define MEMORY_PRESSURE_DEFAULT_TYPE "some"
#define MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC (200 * USEC_PER_MSEC)
#define MEMORY_PRESSURE_DEFAULT_WINDOW_USEC (2 * USEC_PER_SEC)
| 1,065 | 28.611111 | 87 | h |
null | systemd-main/src/basic/random-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <elf.h>
#include <errno.h>
#include <fcntl.h>
#include <linux/random.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/time.h>
#if HAVE_SYS_AUXV_H
# include <sys/auxv.h>
#endif
#include "alloc-util.h"
#include "env-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "io-util.h"
#include "missing_random.h"
#include "missing_syscall.h"
#include "missing_threads.h"
#include "parse-util.h"
#include "process-util.h"
#include "random-util.h"
#include "sha256.h"
#include "time-util.h"
/* This is a "best effort" kind of thing, but has no real security value. So, this should only be used by
* random_bytes(), which is not meant for crypto. This could be made better, but we're *not* trying to roll a
* userspace prng here, or even have forward secrecy, but rather just do the shortest thing that is at least
* better than libc rand(). */
static void fallback_random_bytes(void *p, size_t n) {
static thread_local uint64_t fallback_counter = 0;
struct {
char label[32];
uint64_t call_id, block_id;
usec_t stamp_mono, stamp_real;
pid_t pid, tid;
uint8_t auxval[16];
} state = {
/* Arbitrary domain separation to prevent other usage of AT_RANDOM from clashing. */
.label = "systemd fallback random bytes v1",
.call_id = fallback_counter++,
.stamp_mono = now(CLOCK_MONOTONIC),
.stamp_real = now(CLOCK_REALTIME),
.pid = getpid_cached(),
.tid = gettid(),
};
#if HAVE_SYS_AUXV_H
memcpy(state.auxval, ULONG_TO_PTR(getauxval(AT_RANDOM)), sizeof(state.auxval));
#endif
while (n > 0) {
struct sha256_ctx ctx;
sha256_init_ctx(&ctx);
sha256_process_bytes(&state, sizeof(state), &ctx);
if (n < SHA256_DIGEST_SIZE) {
uint8_t partial[SHA256_DIGEST_SIZE];
sha256_finish_ctx(&ctx, partial);
memcpy(p, partial, n);
break;
}
sha256_finish_ctx(&ctx, p);
p = (uint8_t *) p + SHA256_DIGEST_SIZE;
n -= SHA256_DIGEST_SIZE;
++state.block_id;
}
}
void random_bytes(void *p, size_t n) {
static bool have_getrandom = true, have_grndinsecure = true;
_cleanup_close_ int fd = -EBADF;
if (n == 0)
return;
for (;;) {
ssize_t l;
if (!have_getrandom)
break;
l = getrandom(p, n, have_grndinsecure ? GRND_INSECURE : GRND_NONBLOCK);
if (l > 0) {
if ((size_t) l == n)
return; /* Done reading, success. */
p = (uint8_t *) p + l;
n -= l;
continue; /* Interrupted by a signal; keep going. */
} else if (l == 0)
break; /* Weird, so fallback to /dev/urandom. */
else if (ERRNO_IS_NOT_SUPPORTED(errno)) {
have_getrandom = false;
break; /* No syscall, so fallback to /dev/urandom. */
} else if (errno == EINVAL && have_grndinsecure) {
have_grndinsecure = false;
continue; /* No GRND_INSECURE; fallback to GRND_NONBLOCK. */
} else if (errno == EAGAIN && !have_grndinsecure)
break; /* Will block, but no GRND_INSECURE, so fallback to /dev/urandom. */
break; /* Unexpected, so just give up and fallback to /dev/urandom. */
}
fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
if (fd >= 0 && loop_read_exact(fd, p, n, false) == 0)
return;
/* This is a terrible fallback. Oh well. */
fallback_random_bytes(p, n);
}
int crypto_random_bytes(void *p, size_t n) {
static bool have_getrandom = true, seen_initialized = false;
_cleanup_close_ int fd = -EBADF;
if (n == 0)
return 0;
for (;;) {
ssize_t l;
if (!have_getrandom)
break;
l = getrandom(p, n, 0);
if (l > 0) {
if ((size_t) l == n)
return 0; /* Done reading, success. */
p = (uint8_t *) p + l;
n -= l;
continue; /* Interrupted by a signal; keep going. */
} else if (l == 0)
return -EIO; /* Weird, should never happen. */
else if (ERRNO_IS_NOT_SUPPORTED(errno)) {
have_getrandom = false;
break; /* No syscall, so fallback to /dev/urandom. */
}
return -errno;
}
if (!seen_initialized) {
_cleanup_close_ int ready_fd = -EBADF;
int r;
ready_fd = open("/dev/random", O_RDONLY|O_CLOEXEC|O_NOCTTY);
if (ready_fd < 0)
return -errno;
r = fd_wait_for_event(ready_fd, POLLIN, USEC_INFINITY);
if (r < 0)
return r;
seen_initialized = true;
}
fd = open("/dev/urandom", O_RDONLY|O_CLOEXEC|O_NOCTTY);
if (fd < 0)
return -errno;
return loop_read_exact(fd, p, n, false);
}
size_t random_pool_size(void) {
_cleanup_free_ char *s = NULL;
int r;
/* Read pool size, if possible */
r = read_one_line_file("/proc/sys/kernel/random/poolsize", &s);
if (r < 0)
log_debug_errno(r, "Failed to read pool size from kernel: %m");
else {
unsigned sz;
r = safe_atou(s, &sz);
if (r < 0)
log_debug_errno(r, "Failed to parse pool size: %s", s);
else
/* poolsize is in bits on 2.6, but we want bytes */
return CLAMP(sz / 8, RANDOM_POOL_SIZE_MIN, RANDOM_POOL_SIZE_MAX);
}
/* Use the minimum as default, if we can't retrieve the correct value */
return RANDOM_POOL_SIZE_MIN;
}
int random_write_entropy(int fd, const void *seed, size_t size, bool credit) {
_cleanup_close_ int opened_fd = -EBADF;
int r;
assert(seed || size == 0);
if (size == 0)
return 0;
if (fd < 0) {
opened_fd = open("/dev/urandom", O_WRONLY|O_CLOEXEC|O_NOCTTY);
if (opened_fd < 0)
return -errno;
fd = opened_fd;
}
if (credit) {
_cleanup_free_ struct rand_pool_info *info = NULL;
/* The kernel API only accepts "int" as entropy count (which is in bits), let's avoid any
* chance for confusion here. */
if (size > INT_MAX / 8)
return -EOVERFLOW;
info = malloc(offsetof(struct rand_pool_info, buf) + size);
if (!info)
return -ENOMEM;
info->entropy_count = size * 8;
info->buf_size = size;
memcpy(info->buf, seed, size);
if (ioctl(fd, RNDADDENTROPY, info) < 0)
return -errno;
} else {
r = loop_write(fd, seed, size, false);
if (r < 0)
return r;
}
return 1;
}
uint64_t random_u64_range(uint64_t m) {
uint64_t x, remainder;
/* Generates a random number in the range 0…m-1, unbiased. (Java's algorithm) */
if (m == 0) /* Let's take m == 0 as special case to return an integer from the full range */
return random_u64();
if (m == 1)
return 0;
remainder = UINT64_MAX % m;
do {
x = random_u64();
} while (x >= UINT64_MAX - remainder);
return x % m;
}
| 8,432 | 32.464286 | 109 | c |
null | systemd-main/src/basic/random-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
void random_bytes(void *p, size_t n); /* Returns random bytes suitable for most uses, but may be insecure sometimes. */
int crypto_random_bytes(void *p, size_t n); /* Returns secure random bytes after waiting for the RNG to initialize. */
static inline uint64_t random_u64(void) {
uint64_t u;
random_bytes(&u, sizeof(u));
return u;
}
static inline uint32_t random_u32(void) {
uint32_t u;
random_bytes(&u, sizeof(u));
return u;
}
/* Some limits on the pool sizes when we deal with the kernel random pool */
#define RANDOM_POOL_SIZE_MIN 32U
#define RANDOM_POOL_SIZE_MAX (10U*1024U*1024U)
#define RANDOM_EFI_SEED_SIZE 32U
size_t random_pool_size(void);
int random_write_entropy(int fd, const void *seed, size_t size, bool credit);
uint64_t random_u64_range(uint64_t max);
| 948 | 27.757576 | 119 | h |
null | systemd-main/src/basic/ratelimit.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <sys/time.h>
#include "macro.h"
#include "ratelimit.h"
/* Modelled after Linux' lib/ratelimit.c by Dave Young
* <[email protected]>, which is licensed GPLv2. */
bool ratelimit_below(RateLimit *r) {
usec_t ts;
assert(r);
if (!ratelimit_configured(r))
return true;
ts = now(CLOCK_MONOTONIC);
if (r->begin <= 0 ||
usec_sub_unsigned(ts, r->begin) > r->interval) {
r->begin = ts; /* Start a new time window */
r->num = 1; /* Reset counter */
return true;
}
if (_unlikely_(r->num == UINT_MAX))
return false;
r->num++;
return r->num <= r->burst;
}
unsigned ratelimit_num_dropped(RateLimit *r) {
assert(r);
if (r->num == UINT_MAX) /* overflow, return as special case */
return UINT_MAX;
return LESS_BY(r->num, r->burst);
}
usec_t ratelimit_end(const RateLimit *rl) {
assert(rl);
if (rl->begin == 0)
return 0;
return usec_add(rl->begin, rl->interval);
}
usec_t ratelimit_left(const RateLimit *rl) {
assert(rl);
if (rl->begin == 0)
return 0;
return usec_sub_unsigned(ratelimit_end(rl), now(CLOCK_MONOTONIC));
}
| 1,376 | 21.57377 | 74 | c |
null | systemd-main/src/basic/ratelimit.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "time-util.h"
typedef struct RateLimit {
usec_t interval; /* Keep those two fields first so they can be initialized easily: */
unsigned burst; /* RateLimit rl = { INTERVAL, BURST }; */
unsigned num;
usec_t begin;
} RateLimit;
static inline void ratelimit_reset(RateLimit *rl) {
rl->num = rl->begin = 0;
}
static inline bool ratelimit_configured(RateLimit *rl) {
return rl->interval > 0 && rl->burst > 0;
}
bool ratelimit_below(RateLimit *r);
unsigned ratelimit_num_dropped(RateLimit *r);
usec_t ratelimit_end(const RateLimit *rl);
usec_t ratelimit_left(const RateLimit *rl);
| 726 | 24.068966 | 93 | h |
null | systemd-main/src/basic/raw-clone.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/***
Copyright © 2016 Michael Karcher
***/
#include <errno.h>
#include <sched.h>
#include <sys/syscall.h>
#include "log.h"
#include "macro.h"
#include "process-util.h"
/**
* raw_clone() - uses clone to create a new process with clone flags
* @flags: Flags to pass to the clone system call
*
* Uses the clone system call to create a new process with the cloning flags and termination signal passed in the flags
* parameter. Opposed to glibc's clone function, using this function does not set up a separate stack for the child, but
* relies on copy-on-write semantics on the one stack at a common virtual address, just as fork does.
*
* To obtain copy-on-write semantics, flags must not contain CLONE_VM, and thus CLONE_THREAD and CLONE_SIGHAND (which
* require CLONE_VM) are not usable.
*
* Additionally, as this function does not pass the ptid, newtls and ctid parameters to the kernel, flags must not
* contain CLONE_PARENT_SETTID, CLONE_CHILD_SETTID, CLONE_CHILD_CLEARTID or CLONE_SETTLS.
*
* WARNING: 💣 this call (just like glibc's own clone() wrapper) will not synchronize on glibc's malloc
* locks, which means they will be in an undefined state in the child if the parent is
* threaded. This means: the parent must either never use threads, or the child cannot use memory
* allocation itself. This is a major pitfall, hence be careful! 💣
*
* Returns: 0 in the child process and the child process id in the parent.
*/
static inline pid_t raw_clone(unsigned long flags) {
pid_t ret;
assert((flags & (CLONE_VM|CLONE_PARENT_SETTID|CLONE_CHILD_SETTID|
CLONE_CHILD_CLEARTID|CLONE_SETTLS)) == 0);
#if defined(__s390x__) || defined(__s390__) || defined(__CRIS__)
/* On s390/s390x and cris the order of the first and second arguments
* of the raw clone() system call is reversed. */
ret = (pid_t) syscall(__NR_clone, NULL, flags);
#elif defined(__sparc__)
{
/**
* sparc always returns the other process id in %o0, and
* a boolean flag whether this is the child or the parent in
* %o1. Inline assembly is needed to get the flag returned
* in %o1.
*/
int in_child, child_pid, error;
asm volatile("mov %3, %%g1\n\t"
"mov %4, %%o0\n\t"
"mov 0 , %%o1\n\t"
#if defined(__arch64__)
"t 0x6d\n\t"
#else
"t 0x10\n\t"
#endif
"addx %%g0, 0, %2\n\t"
"mov %%o1, %0\n\t"
"mov %%o0, %1" :
"=r"(in_child), "=r"(child_pid), "=r"(error) :
"i"(__NR_clone), "r"(flags) :
"%o1", "%o0", "%g1", "cc" );
if (error) {
errno = child_pid;
ret = -1;
} else
ret = in_child ? 0 : child_pid;
}
#else
ret = (pid_t) syscall(__NR_clone, flags, NULL);
#endif
if (ret == 0)
reset_cached_pid();
return ret;
}
| 3,337 | 37.813953 | 120 | h |
null | systemd-main/src/basic/raw-reboot.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/reboot.h>
#include <sys/reboot.h>
#include <sys/syscall.h>
/* glibc defines the reboot() API call, which is a wrapper around the system call of the same name, but without the
* extra "arg" parameter. Since we need that parameter for some calls, let's add a "raw" wrapper that is defined the
* same way, except it takes the additional argument. */
static inline int raw_reboot(int cmd, const void *arg) {
return (int) syscall(SYS_reboot, LINUX_REBOOT_MAGIC1, LINUX_REBOOT_MAGIC2, cmd, arg);
}
| 583 | 37.933333 | 116 | h |
null | systemd-main/src/basic/replace-var.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stddef.h>
#include <stdlib.h>
#include "alloc-util.h"
#include "macro.h"
#include "replace-var.h"
#include "string-util.h"
/*
* Generic infrastructure for replacing @FOO@ style variables in
* strings. Will call a callback for each replacement.
*/
static int get_variable(const char *b, char **r) {
size_t k;
char *t;
assert(b);
assert(r);
if (*b != '@')
return 0;
k = strspn(b + 1, UPPERCASE_LETTERS "_");
if (k <= 0 || b[k+1] != '@')
return 0;
t = strndup(b + 1, k);
if (!t)
return -ENOMEM;
*r = t;
return 1;
}
char *replace_var(const char *text, char *(*lookup)(const char *variable, void *userdata), void *userdata) {
char *r, *t;
const char *f;
size_t l;
assert(text);
assert(lookup);
l = strlen(text);
r = new(char, l+1);
if (!r)
return NULL;
f = text;
t = r;
while (*f) {
_cleanup_free_ char *v = NULL, *n = NULL;
char *a;
int k;
size_t skip, d, nl;
k = get_variable(f, &v);
if (k < 0)
goto oom;
if (k == 0) {
*(t++) = *(f++);
continue;
}
n = lookup(v, userdata);
if (!n)
goto oom;
skip = strlen(v) + 2;
d = t - r;
nl = l - skip + strlen(n);
a = realloc(r, nl + 1);
if (!a)
goto oom;
l = nl;
r = a;
t = r + d;
t = stpcpy(t, n);
f += skip;
}
*t = 0;
return r;
oom:
return mfree(r);
}
| 2,003 | 20.319149 | 108 | c |
null | systemd-main/src/basic/rlimit-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/resource.h>
#include "macro.h"
const char *rlimit_to_string(int i) _const_;
int rlimit_from_string(const char *s) _pure_;
int rlimit_from_string_harder(const char *s) _pure_;
int setrlimit_closest(int resource, const struct rlimit *rlim);
int setrlimit_closest_all(const struct rlimit * const *rlim, int *which_failed);
int rlimit_parse_one(int resource, const char *val, rlim_t *ret);
int rlimit_parse(int resource, const char *val, struct rlimit *ret);
int rlimit_format(const struct rlimit *rl, char **ret);
void rlimit_free_all(struct rlimit **rl);
#define RLIMIT_MAKE_CONST(lim) ((struct rlimit) { lim, lim })
int rlimit_nofile_bump(int limit);
int rlimit_nofile_safe(void);
| 765 | 28.461538 | 80 | h |
null | systemd-main/src/basic/runtime-scope.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "runtime-scope.h"
#include "string-table.h"
static const char* const runtime_scope_table[_RUNTIME_SCOPE_MAX] = {
[RUNTIME_SCOPE_SYSTEM] = "system",
[RUNTIME_SCOPE_USER] = "user",
[RUNTIME_SCOPE_GLOBAL] = "global",
};
DEFINE_STRING_TABLE_LOOKUP(runtime_scope, RuntimeScope);
static const char* const runtime_scope_cmdline_option_table[_RUNTIME_SCOPE_MAX] = {
[RUNTIME_SCOPE_SYSTEM] = "--system",
[RUNTIME_SCOPE_USER] = "--user",
[RUNTIME_SCOPE_GLOBAL] = "--global",
};
DEFINE_STRING_TABLE_LOOKUP_TO_STRING(runtime_scope_cmdline_option, RuntimeScope);
| 665 | 30.714286 | 83 | c |
null | systemd-main/src/basic/runtime-scope.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include "macro.h"
typedef enum RuntimeScope {
RUNTIME_SCOPE_SYSTEM, /* for the system */
RUNTIME_SCOPE_USER, /* for a user */
RUNTIME_SCOPE_GLOBAL, /* for all users */
_RUNTIME_SCOPE_MAX,
_RUNTIME_SCOPE_INVALID = -EINVAL,
} RuntimeScope;
const char *runtime_scope_to_string(RuntimeScope scope) _const_;
RuntimeScope runtime_scope_from_string(const char *s) _const_;
const char *runtime_scope_cmdline_option_to_string(RuntimeScope scope) _const_;
| 605 | 29.3 | 79 | h |
null | systemd-main/src/basic/set.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "extract-word.h"
#include "hashmap.h"
#include "macro.h"
#define set_free_and_replace(a, b) \
free_and_replace_full(a, b, set_free)
Set* _set_new(const struct hash_ops *hash_ops HASHMAP_DEBUG_PARAMS);
#define set_new(ops) _set_new(ops HASHMAP_DEBUG_SRC_ARGS)
static inline Set* set_free(Set *s) {
return (Set*) _hashmap_free(HASHMAP_BASE(s), NULL, NULL);
}
static inline Set* set_free_free(Set *s) {
return (Set*) _hashmap_free(HASHMAP_BASE(s), free, NULL);
}
/* no set_free_free_free */
#define set_copy(s) ((Set*) _hashmap_copy(HASHMAP_BASE(s) HASHMAP_DEBUG_SRC_ARGS))
int _set_ensure_allocated(Set **s, const struct hash_ops *hash_ops HASHMAP_DEBUG_PARAMS);
#define set_ensure_allocated(h, ops) _set_ensure_allocated(h, ops HASHMAP_DEBUG_SRC_ARGS)
int set_put(Set *s, const void *key);
/* no set_update */
/* no set_replace */
static inline void *set_get(const Set *s, const void *key) {
return _hashmap_get(HASHMAP_BASE((Set *) s), key);
}
/* no set_get2 */
static inline bool set_contains(const Set *s, const void *key) {
return _hashmap_contains(HASHMAP_BASE((Set *) s), key);
}
static inline void *set_remove(Set *s, const void *key) {
return _hashmap_remove(HASHMAP_BASE(s), key);
}
/* no set_remove2 */
/* no set_remove_value */
int set_remove_and_put(Set *s, const void *old_key, const void *new_key);
/* no set_remove_and_replace */
int set_merge(Set *s, Set *other);
static inline int set_reserve(Set *h, unsigned entries_add) {
return _hashmap_reserve(HASHMAP_BASE(h), entries_add);
}
static inline int set_move(Set *s, Set *other) {
return _hashmap_move(HASHMAP_BASE(s), HASHMAP_BASE(other));
}
static inline int set_move_one(Set *s, Set *other, const void *key) {
return _hashmap_move_one(HASHMAP_BASE(s), HASHMAP_BASE(other), key);
}
static inline unsigned set_size(const Set *s) {
return _hashmap_size(HASHMAP_BASE((Set *) s));
}
static inline bool set_isempty(const Set *s) {
return set_size(s) == 0;
}
static inline unsigned set_buckets(const Set *s) {
return _hashmap_buckets(HASHMAP_BASE((Set *) s));
}
static inline bool set_iterate(const Set *s, Iterator *i, void **value) {
return _hashmap_iterate(HASHMAP_BASE((Set*) s), i, value, NULL);
}
static inline void set_clear(Set *s) {
_hashmap_clear(HASHMAP_BASE(s), NULL, NULL);
}
static inline void set_clear_free(Set *s) {
_hashmap_clear(HASHMAP_BASE(s), free, NULL);
}
/* no set_clear_free_free */
static inline void *set_steal_first(Set *s) {
return _hashmap_first_key_and_value(HASHMAP_BASE(s), true, NULL);
}
#define set_clear_with_destructor(s, f) \
({ \
Set *_s = (s); \
void *_item; \
while ((_item = set_steal_first(_s))) \
f(_item); \
_s; \
})
#define set_free_with_destructor(s, f) \
set_free(set_clear_with_destructor(s, f))
/* no set_steal_first_key */
/* no set_first_key */
static inline void *set_first(const Set *s) {
return _hashmap_first_key_and_value(HASHMAP_BASE((Set *) s), false, NULL);
}
/* no set_next */
static inline char **set_get_strv(Set *s) {
return _hashmap_get_strv(HASHMAP_BASE(s));
}
int _set_ensure_put(Set **s, const struct hash_ops *hash_ops, const void *key HASHMAP_DEBUG_PARAMS);
#define set_ensure_put(s, hash_ops, key) _set_ensure_put(s, hash_ops, key HASHMAP_DEBUG_SRC_ARGS)
int _set_ensure_consume(Set **s, const struct hash_ops *hash_ops, void *key HASHMAP_DEBUG_PARAMS);
#define set_ensure_consume(s, hash_ops, key) _set_ensure_consume(s, hash_ops, key HASHMAP_DEBUG_SRC_ARGS)
int set_consume(Set *s, void *value);
int _set_put_strndup_full(Set **s, const struct hash_ops *hash_ops, const char *p, size_t n HASHMAP_DEBUG_PARAMS);
#define set_put_strndup_full(s, hash_ops, p, n) _set_put_strndup_full(s, hash_ops, p, n HASHMAP_DEBUG_SRC_ARGS)
#define set_put_strdup_full(s, hash_ops, p) set_put_strndup_full(s, hash_ops, p, SIZE_MAX)
#define set_put_strndup(s, p, n) set_put_strndup_full(s, &string_hash_ops_free, p, n)
#define set_put_strdup(s, p) set_put_strndup(s, p, SIZE_MAX)
int _set_put_strdupv_full(Set **s, const struct hash_ops *hash_ops, char **l HASHMAP_DEBUG_PARAMS);
#define set_put_strdupv_full(s, hash_ops, l) _set_put_strdupv_full(s, hash_ops, l HASHMAP_DEBUG_SRC_ARGS)
#define set_put_strdupv(s, l) set_put_strdupv_full(s, &string_hash_ops_free, l)
int set_put_strsplit(Set *s, const char *v, const char *separators, ExtractFlags flags);
#define _SET_FOREACH(e, s, i) \
for (Iterator i = ITERATOR_FIRST; set_iterate((s), &i, (void**)&(e)); )
#define SET_FOREACH(e, s) \
_SET_FOREACH(e, s, UNIQ_T(i, UNIQ))
#define SET_FOREACH_MOVE(e, d, s) \
for (; ({ e = set_first(s); assert_se(!e || set_move_one(d, s, e) >= 0); e; }); )
DEFINE_TRIVIAL_CLEANUP_FUNC(Set*, set_free);
DEFINE_TRIVIAL_CLEANUP_FUNC(Set*, set_free_free);
#define _cleanup_set_free_ _cleanup_(set_freep)
#define _cleanup_set_free_free_ _cleanup_(set_free_freep)
int set_strjoin(Set *s, const char *separator, bool wrap_with_separator, char **ret);
bool set_equal(Set *a, Set *b);
bool set_fnmatch(Set *include_patterns, Set *exclude_patterns, const char *needle);
| 5,603 | 34.923077 | 115 | h |
null | systemd-main/src/basic/sigbus.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <signal.h>
#include <stddef.h>
#include <sys/mman.h>
#include "macro.h"
#include "memory-util.h"
#include "missing_syscall.h"
#include "process-util.h"
#include "sigbus.h"
#include "signal-util.h"
#define SIGBUS_QUEUE_MAX 64
static struct sigaction old_sigaction;
static unsigned n_installed = 0;
/* We maintain a fixed size list of page addresses that triggered a
SIGBUS. We access with list with atomic operations, so that we
don't have to deal with locks between signal handler and main
programs in possibly multiple threads. */
static void* volatile sigbus_queue[SIGBUS_QUEUE_MAX];
static volatile sig_atomic_t n_sigbus_queue = 0;
static void sigbus_push(void *addr) {
assert(addr);
/* Find a free place, increase the number of entries and leave, if we can */
for (size_t u = 0; u < SIGBUS_QUEUE_MAX; u++) {
/* OK to initialize this here since we haven't started the atomic ops yet */
void *tmp = NULL;
if (__atomic_compare_exchange_n(&sigbus_queue[u], &tmp, addr, false,
__ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
__atomic_fetch_add(&n_sigbus_queue, 1, __ATOMIC_SEQ_CST);
return;
}
}
/* If we can't, make sure the queue size is out of bounds, to
* mark it as overflow */
for (;;) {
sig_atomic_t c;
__atomic_thread_fence(__ATOMIC_SEQ_CST);
c = n_sigbus_queue;
if (c > SIGBUS_QUEUE_MAX) /* already overflow */
return;
/* OK if we clobber c here, since we either immediately return
* or it will be immediately reinitialized on next loop */
if (__atomic_compare_exchange_n(&n_sigbus_queue, &c, c + SIGBUS_QUEUE_MAX, false,
__ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST))
return;
}
}
int sigbus_pop(void **ret) {
assert(ret);
for (;;) {
unsigned u, c;
__atomic_thread_fence(__ATOMIC_SEQ_CST);
c = n_sigbus_queue;
if (_likely_(c == 0))
return 0;
if (_unlikely_(c >= SIGBUS_QUEUE_MAX))
return -EOVERFLOW;
for (u = 0; u < SIGBUS_QUEUE_MAX; u++) {
void *addr;
addr = sigbus_queue[u];
if (!addr)
continue;
/* OK if we clobber addr here, since we either immediately return
* or it will be immediately reinitialized on next loop */
if (__atomic_compare_exchange_n(&sigbus_queue[u], &addr, NULL, false,
__ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) {
__atomic_fetch_sub(&n_sigbus_queue, 1, __ATOMIC_SEQ_CST);
/* If we successfully entered this if condition, addr won't
* have been modified since its assignment, so safe to use it */
*ret = addr;
return 1;
}
}
}
}
static void sigbus_handler(int sn, siginfo_t *si, void *data) {
unsigned long ul;
void *aligned;
assert(sn == SIGBUS);
assert(si);
if (si->si_code != BUS_ADRERR || !si->si_addr) {
assert_se(sigaction(SIGBUS, &old_sigaction, NULL) == 0);
propagate_signal(sn, si);
return;
}
ul = (unsigned long) si->si_addr;
ul = ul / page_size();
ul = ul * page_size();
aligned = (void*) ul;
/* Let's remember which address failed */
sigbus_push(aligned);
/* Replace mapping with an anonymous page, so that the
* execution can continue, however with a zeroed out page */
assert_se(mmap(aligned, page_size(), PROT_READ|PROT_WRITE, MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED, -1, 0) == aligned);
}
void sigbus_install(void) {
struct sigaction sa = {
.sa_sigaction = sigbus_handler,
.sa_flags = SA_SIGINFO,
};
/* make sure that sysconf() is not called from a signal handler because
* it is not guaranteed to be async-signal-safe since POSIX.1-2008 */
(void) page_size();
n_installed++;
if (n_installed == 1)
assert_se(sigaction(SIGBUS, &sa, &old_sigaction) == 0);
return;
}
void sigbus_reset(void) {
if (n_installed <= 0)
return;
n_installed--;
if (n_installed == 0)
assert_se(sigaction(SIGBUS, &old_sigaction, NULL) == 0);
return;
}
| 5,042 | 31.960784 | 123 | c |
null | systemd-main/src/basic/signal-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdarg.h>
#include "errno-util.h"
#include "macro.h"
#include "missing_syscall.h"
#include "missing_threads.h"
#include "parse-util.h"
#include "signal-util.h"
#include "stdio-util.h"
#include "string-table.h"
#include "string-util.h"
int reset_all_signal_handlers(void) {
static const struct sigaction sa = {
.sa_handler = SIG_DFL,
.sa_flags = SA_RESTART,
};
int r = 0;
for (int sig = 1; sig < _NSIG; sig++) {
/* These two cannot be caught... */
if (IN_SET(sig, SIGKILL, SIGSTOP))
continue;
/* On Linux the first two RT signals are reserved by
* glibc, and sigaction() will return EINVAL for them. */
if (sigaction(sig, &sa, NULL) < 0)
if (errno != EINVAL && r >= 0)
r = -errno;
}
return r;
}
int reset_signal_mask(void) {
sigset_t ss;
if (sigemptyset(&ss) < 0)
return -errno;
return RET_NERRNO(sigprocmask(SIG_SETMASK, &ss, NULL));
}
int sigaction_many_internal(const struct sigaction *sa, ...) {
int sig, r = 0;
va_list ap;
va_start(ap, sa);
/* negative signal ends the list. 0 signal is skipped. */
while ((sig = va_arg(ap, int)) >= 0) {
if (sig == 0)
continue;
if (sigaction(sig, sa, NULL) < 0) {
if (r >= 0)
r = -errno;
}
}
va_end(ap);
return r;
}
static int sigset_add_many_ap(sigset_t *ss, va_list ap) {
int sig, r = 0;
assert(ss);
while ((sig = va_arg(ap, int)) >= 0) {
if (sig == 0)
continue;
if (sigaddset(ss, sig) < 0) {
if (r >= 0)
r = -errno;
}
}
return r;
}
int sigset_add_many(sigset_t *ss, ...) {
va_list ap;
int r;
va_start(ap, ss);
r = sigset_add_many_ap(ss, ap);
va_end(ap);
return r;
}
int sigprocmask_many(int how, sigset_t *old, ...) {
va_list ap;
sigset_t ss;
int r;
if (sigemptyset(&ss) < 0)
return -errno;
va_start(ap, old);
r = sigset_add_many_ap(&ss, ap);
va_end(ap);
if (r < 0)
return r;
if (sigprocmask(how, &ss, old) < 0)
return -errno;
return 0;
}
static const char *const static_signal_table[] = {
[SIGHUP] = "HUP",
[SIGINT] = "INT",
[SIGQUIT] = "QUIT",
[SIGILL] = "ILL",
[SIGTRAP] = "TRAP",
[SIGABRT] = "ABRT",
[SIGBUS] = "BUS",
[SIGFPE] = "FPE",
[SIGKILL] = "KILL",
[SIGUSR1] = "USR1",
[SIGSEGV] = "SEGV",
[SIGUSR2] = "USR2",
[SIGPIPE] = "PIPE",
[SIGALRM] = "ALRM",
[SIGTERM] = "TERM",
#ifdef SIGSTKFLT
[SIGSTKFLT] = "STKFLT", /* Linux on SPARC doesn't know SIGSTKFLT */
#endif
[SIGCHLD] = "CHLD",
[SIGCONT] = "CONT",
[SIGSTOP] = "STOP",
[SIGTSTP] = "TSTP",
[SIGTTIN] = "TTIN",
[SIGTTOU] = "TTOU",
[SIGURG] = "URG",
[SIGXCPU] = "XCPU",
[SIGXFSZ] = "XFSZ",
[SIGVTALRM] = "VTALRM",
[SIGPROF] = "PROF",
[SIGWINCH] = "WINCH",
[SIGIO] = "IO",
[SIGPWR] = "PWR",
[SIGSYS] = "SYS"
};
DEFINE_PRIVATE_STRING_TABLE_LOOKUP(static_signal, int);
const char *signal_to_string(int signo) {
static thread_local char buf[STRLEN("RTMIN+") + DECIMAL_STR_MAX(int)];
const char *name;
name = static_signal_to_string(signo);
if (name)
return name;
if (signo >= SIGRTMIN && signo <= SIGRTMAX)
xsprintf(buf, "RTMIN+%d", signo - SIGRTMIN);
else
xsprintf(buf, "%d", signo);
return buf;
}
int signal_from_string(const char *s) {
const char *p;
int signo, r;
/* Check that the input is a signal number. */
if (safe_atoi(s, &signo) >= 0) {
if (SIGNAL_VALID(signo))
return signo;
else
return -ERANGE;
}
/* Drop "SIG" prefix. */
if (startswith(s, "SIG"))
s += 3;
/* Check that the input is a signal name. */
signo = static_signal_from_string(s);
if (signo > 0)
return signo;
/* Check that the input is RTMIN or
* RTMIN+n (0 <= n <= SIGRTMAX-SIGRTMIN). */
p = startswith(s, "RTMIN");
if (p) {
if (*p == '\0')
return SIGRTMIN;
if (*p != '+')
return -EINVAL;
r = safe_atoi(p, &signo);
if (r < 0)
return r;
if (signo < 0 || signo > SIGRTMAX - SIGRTMIN)
return -ERANGE;
return signo + SIGRTMIN;
}
/* Check that the input is RTMAX or
* RTMAX-n (0 <= n <= SIGRTMAX-SIGRTMIN). */
p = startswith(s, "RTMAX");
if (p) {
if (*p == '\0')
return SIGRTMAX;
if (*p != '-')
return -EINVAL;
r = safe_atoi(p, &signo);
if (r < 0)
return r;
if (signo > 0 || signo < SIGRTMIN - SIGRTMAX)
return -ERANGE;
return signo + SIGRTMAX;
}
return -EINVAL;
}
void nop_signal_handler(int sig) {
/* nothing here */
}
int signal_is_blocked(int sig) {
sigset_t ss;
int r;
r = pthread_sigmask(SIG_SETMASK, NULL, &ss);
if (r != 0)
return -r;
return RET_NERRNO(sigismember(&ss, sig));
}
int pop_pending_signal_internal(int sig, ...) {
sigset_t ss;
va_list ap;
int r;
if (sig < 0) /* Empty list? */
return -EINVAL;
if (sigemptyset(&ss) < 0)
return -errno;
/* Add first signal (if the signal is zero, we'll silently skip it, to make it easier to build
* parameter lists where some element are sometimes off, similar to how sigset_add_many_ap() handles
* this.) */
if (sig > 0 && sigaddset(&ss, sig) < 0)
return -errno;
/* Add all other signals */
va_start(ap, sig);
r = sigset_add_many_ap(&ss, ap);
va_end(ap);
if (r < 0)
return r;
r = sigtimedwait(&ss, NULL, &(struct timespec) { 0, 0 });
if (r < 0) {
if (errno == EAGAIN)
return 0;
return -errno;
}
return r; /* Returns the signal popped */
}
void propagate_signal(int sig, siginfo_t *siginfo) {
pid_t p;
/* To be called from a signal handler. Will raise the same signal again, in our process + in our threads.
*
* Note that we use raw_getpid() instead of getpid_cached(). We might have forked with raw_clone()
* earlier (see PID 1), and hence let's go to the raw syscall here. In particular as this is not
* performance sensitive code.
*
* Note that we use kill() rather than raise() as fallback, for similar reasons. */
p = raw_getpid();
if (rt_tgsigqueueinfo(p, gettid(), sig, siginfo) < 0)
assert_se(kill(p, sig) >= 0);
}
| 7,853 | 24.835526 | 113 | c |
null | systemd-main/src/basic/signal-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <signal.h>
#include "macro.h"
int reset_all_signal_handlers(void);
int reset_signal_mask(void);
int sigaction_many_internal(const struct sigaction *sa, ...);
#define ignore_signals(...) \
sigaction_many_internal( \
&(const struct sigaction) { \
.sa_handler = SIG_IGN, \
.sa_flags = SA_RESTART \
}, \
__VA_ARGS__, \
-1)
#define default_signals(...) \
sigaction_many_internal( \
&(const struct sigaction) { \
.sa_handler = SIG_DFL, \
.sa_flags = SA_RESTART \
}, \
__VA_ARGS__, \
-1)
#define sigaction_many(sa, ...) \
sigaction_many_internal(sa, __VA_ARGS__, -1)
int sigset_add_many(sigset_t *ss, ...);
int sigprocmask_many(int how, sigset_t *old, ...);
const char *signal_to_string(int i) _const_;
int signal_from_string(const char *s) _pure_;
void nop_signal_handler(int sig);
static inline void block_signals_reset(sigset_t *ss) {
assert_se(sigprocmask(SIG_SETMASK, ss, NULL) >= 0);
}
#define BLOCK_SIGNALS(...) \
_cleanup_(block_signals_reset) _unused_ sigset_t _saved_sigset = ({ \
sigset_t _t; \
assert_se(sigprocmask_many(SIG_BLOCK, &_t, __VA_ARGS__, -1) >= 0); \
_t; \
})
static inline bool SIGNAL_VALID(int signo) {
return signo > 0 && signo < _NSIG;
}
static inline const char* signal_to_string_with_check(int n) {
if (!SIGNAL_VALID(n))
return NULL;
return signal_to_string(n);
}
int signal_is_blocked(int sig);
int pop_pending_signal_internal(int sig, ...);
#define pop_pending_signal(...) pop_pending_signal_internal(__VA_ARGS__, -1)
void propagate_signal(int sig, siginfo_t *siginfo);
| 2,693 | 37.485714 | 84 | h |
null | systemd-main/src/basic/siphash24.h | /* SPDX-License-Identifier: CC0-1.0 */
#pragma once
#include <inttypes.h>
#include <stddef.h>
#include <stdint.h>
#include <sys/types.h>
#include "string-util.h"
#include "time-util.h"
struct siphash {
uint64_t v0;
uint64_t v1;
uint64_t v2;
uint64_t v3;
uint64_t padding;
size_t inlen;
};
void siphash24_init(struct siphash *state, const uint8_t k[static 16]);
void siphash24_compress(const void *in, size_t inlen, struct siphash *state);
#define siphash24_compress_byte(byte, state) siphash24_compress((const uint8_t[]) { (byte) }, 1, (state))
static inline void siphash24_compress_boolean(bool in, struct siphash *state) {
uint8_t i = in;
siphash24_compress(&i, sizeof i, state);
}
static inline void siphash24_compress_usec_t(usec_t in, struct siphash *state) {
siphash24_compress(&in, sizeof in, state);
}
static inline void siphash24_compress_safe(const void *in, size_t inlen, struct siphash *state) {
if (inlen == 0)
return;
siphash24_compress(in, inlen, state);
}
static inline void siphash24_compress_string(const char *in, struct siphash *state) {
siphash24_compress_safe(in, strlen_ptr(in), state);
}
uint64_t siphash24_finalize(struct siphash *state);
uint64_t siphash24(const void *in, size_t inlen, const uint8_t k[static 16]);
static inline uint64_t siphash24_string(const char *s, const uint8_t k[static 16]) {
return siphash24(s, strlen(s) + 1, k);
}
| 1,502 | 26.833333 | 105 | h |
null | systemd-main/src/basic/socket-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include <linux/netlink.h>
#include <linux/if_ether.h>
#include <linux/if_infiniband.h>
#include <linux/if_packet.h>
#include <netinet/in.h>
#include <stdbool.h>
#include <stddef.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <sys/un.h>
#include "errno-util.h"
#include "in-addr-util.h"
#include "macro.h"
#include "missing_network.h"
#include "missing_socket.h"
#include "sparse-endian.h"
union sockaddr_union {
/* The minimal, abstract version */
struct sockaddr sa;
/* The libc provided version that allocates "enough room" for every protocol */
struct sockaddr_storage storage;
/* Protoctol-specific implementations */
struct sockaddr_in in;
struct sockaddr_in6 in6;
struct sockaddr_un un;
struct sockaddr_nl nl;
struct sockaddr_ll ll;
struct sockaddr_vm vm;
/* Ensure there is enough space to store Infiniband addresses */
uint8_t ll_buffer[offsetof(struct sockaddr_ll, sll_addr) + CONST_MAX(ETH_ALEN, INFINIBAND_ALEN)];
/* Ensure there is enough space after the AF_UNIX sun_path for one more NUL byte, just to be sure that the path
* component is always followed by at least one NUL byte. */
uint8_t un_buffer[sizeof(struct sockaddr_un) + 1];
};
#define SUN_PATH_LEN (sizeof(((struct sockaddr_un){}).sun_path))
typedef struct SocketAddress {
union sockaddr_union sockaddr;
/* We store the size here explicitly due to the weird
* sockaddr_un semantics for abstract sockets */
socklen_t size;
/* Socket type, i.e. SOCK_STREAM, SOCK_DGRAM, ... */
int type;
/* Socket protocol, IPPROTO_xxx, usually 0, except for netlink */
int protocol;
} SocketAddress;
typedef enum SocketAddressBindIPv6Only {
SOCKET_ADDRESS_DEFAULT,
SOCKET_ADDRESS_BOTH,
SOCKET_ADDRESS_IPV6_ONLY,
_SOCKET_ADDRESS_BIND_IPV6_ONLY_MAX,
_SOCKET_ADDRESS_BIND_IPV6_ONLY_INVALID = -EINVAL,
} SocketAddressBindIPv6Only;
#define socket_address_family(a) ((a)->sockaddr.sa.sa_family)
const char* socket_address_type_to_string(int t) _const_;
int socket_address_type_from_string(const char *s) _pure_;
int sockaddr_un_unlink(const struct sockaddr_un *sa);
static inline int socket_address_unlink(const SocketAddress *a) {
return socket_address_family(a) == AF_UNIX ? sockaddr_un_unlink(&a->sockaddr.un) : 0;
}
bool socket_address_can_accept(const SocketAddress *a) _pure_;
int socket_address_listen(
const SocketAddress *a,
int flags,
int backlog,
SocketAddressBindIPv6Only only,
const char *bind_to_device,
bool reuse_port,
bool free_bind,
bool transparent,
mode_t directory_mode,
mode_t socket_mode,
const char *label);
int socket_address_verify(const SocketAddress *a, bool strict) _pure_;
int socket_address_print(const SocketAddress *a, char **p);
bool socket_address_matches_fd(const SocketAddress *a, int fd);
bool socket_address_equal(const SocketAddress *a, const SocketAddress *b) _pure_;
const char* socket_address_get_path(const SocketAddress *a);
bool socket_ipv6_is_supported(void);
bool socket_ipv6_is_enabled(void);
int sockaddr_port(const struct sockaddr *_sa, unsigned *port);
const union in_addr_union *sockaddr_in_addr(const struct sockaddr *sa);
int sockaddr_set_in_addr(union sockaddr_union *u, int family, const union in_addr_union *a, uint16_t port);
int sockaddr_pretty(const struct sockaddr *_sa, socklen_t salen, bool translate_ipv6, bool include_port, char **ret);
int getpeername_pretty(int fd, bool include_port, char **ret);
int getsockname_pretty(int fd, char **ret);
int socknameinfo_pretty(union sockaddr_union *sa, socklen_t salen, char **_ret);
const char* socket_address_bind_ipv6_only_to_string(SocketAddressBindIPv6Only b) _const_;
SocketAddressBindIPv6Only socket_address_bind_ipv6_only_from_string(const char *s) _pure_;
SocketAddressBindIPv6Only socket_address_bind_ipv6_only_or_bool_from_string(const char *s);
int netlink_family_to_string_alloc(int b, char **s);
int netlink_family_from_string(const char *s) _pure_;
bool sockaddr_equal(const union sockaddr_union *a, const union sockaddr_union *b);
int fd_set_sndbuf(int fd, size_t n, bool increase);
static inline int fd_inc_sndbuf(int fd, size_t n) {
return fd_set_sndbuf(fd, n, true);
}
int fd_set_rcvbuf(int fd, size_t n, bool increase);
static inline int fd_increase_rxbuf(int fd, size_t n) {
return fd_set_rcvbuf(fd, n, true);
}
int ip_tos_to_string_alloc(int i, char **s);
int ip_tos_from_string(const char *s);
typedef enum {
IFNAME_VALID_ALTERNATIVE = 1 << 0, /* Allow "altnames" too */
IFNAME_VALID_NUMERIC = 1 << 1, /* Allow decimal formatted ifindexes too */
IFNAME_VALID_SPECIAL = 1 << 2, /* Allow the special names "all" and "default" */
_IFNAME_VALID_ALL = IFNAME_VALID_ALTERNATIVE | IFNAME_VALID_NUMERIC | IFNAME_VALID_SPECIAL,
} IfnameValidFlags;
bool ifname_valid_char(char a);
bool ifname_valid_full(const char *p, IfnameValidFlags flags);
static inline bool ifname_valid(const char *p) {
return ifname_valid_full(p, 0);
}
bool address_label_valid(const char *p);
int getpeercred(int fd, struct ucred *ucred);
int getpeersec(int fd, char **ret);
int getpeergroups(int fd, gid_t **ret);
ssize_t send_one_fd_iov_sa(
int transport_fd,
int fd,
const struct iovec *iov, size_t iovlen,
const struct sockaddr *sa, socklen_t len,
int flags);
int send_one_fd_sa(int transport_fd,
int fd,
const struct sockaddr *sa, socklen_t len,
int flags);
#define send_one_fd_iov(transport_fd, fd, iov, iovlen, flags) send_one_fd_iov_sa(transport_fd, fd, iov, iovlen, NULL, 0, flags)
#define send_one_fd(transport_fd, fd, flags) send_one_fd_iov_sa(transport_fd, fd, NULL, 0, NULL, 0, flags)
ssize_t receive_one_fd_iov(int transport_fd, struct iovec *iov, size_t iovlen, int flags, int *ret_fd);
int receive_one_fd(int transport_fd, int flags);
ssize_t next_datagram_size_fd(int fd);
int flush_accept(int fd);
#define CMSG_FOREACH(cmsg, mh) \
for ((cmsg) = CMSG_FIRSTHDR(mh); (cmsg); (cmsg) = CMSG_NXTHDR((mh), (cmsg)))
/* Returns the cmsghdr's data pointer, but safely cast to the specified type. Does two alignment checks: one
* at compile time, that the requested type has a smaller or same alignment as 'struct cmsghdr', and one
* during runtime, that the actual pointer matches the alignment too. This is supposed to catch cases such as
* 'struct timeval' is embedded into 'struct cmsghdr' on architectures where the alignment of the former is 8
* bytes (because of a 64-bit time_t), but of the latter is 4 bytes (because size_t is 32 bits), such as
* riscv32. */
#define CMSG_TYPED_DATA(cmsg, type) \
({ \
struct cmsghdr *_cmsg = (cmsg); \
assert_cc(alignof(type) <= alignof(struct cmsghdr)); \
_cmsg ? CAST_ALIGN_PTR(type, CMSG_DATA(_cmsg)) : (type*) NULL; \
})
struct cmsghdr* cmsg_find(struct msghdr *mh, int level, int type, socklen_t length);
void* cmsg_find_and_copy_data(struct msghdr *mh, int level, int type, void *buf, size_t buf_len);
/* Type-safe, dereferencing version of cmsg_find() */
#define CMSG_FIND_DATA(mh, level, type, ctype) \
CMSG_TYPED_DATA(cmsg_find(mh, level, type, CMSG_LEN(sizeof(ctype))), ctype)
/* Type-safe version of cmsg_find_and_copy_data() */
#define CMSG_FIND_AND_COPY_DATA(mh, level, type, ctype) \
(ctype*) cmsg_find_and_copy_data(mh, level, type, &(ctype){}, sizeof(ctype))
/* Resolves to a type that can carry cmsghdr structures. Make sure things are properly aligned, i.e. the type
* itself is placed properly in memory and the size is also aligned to what's appropriate for "cmsghdr"
* structures. */
#define CMSG_BUFFER_TYPE(size) \
union { \
struct cmsghdr cmsghdr; \
uint8_t buf[size]; \
uint8_t align_check[(size) >= CMSG_SPACE(0) && \
(size) == CMSG_ALIGN(size) ? 1 : -1]; \
}
/*
* Certain hardware address types (e.g Infiniband) do not fit into sll_addr
* (8 bytes) and run over the structure. This macro returns the correct size that
* must be passed to kernel.
*/
#define SOCKADDR_LL_LEN(sa) \
({ \
const struct sockaddr_ll *_sa = &(sa); \
size_t _mac_len = sizeof(_sa->sll_addr); \
assert(_sa->sll_family == AF_PACKET); \
if (be16toh(_sa->sll_hatype) == ARPHRD_ETHER) \
_mac_len = MAX(_mac_len, (size_t) ETH_ALEN); \
if (be16toh(_sa->sll_hatype) == ARPHRD_INFINIBAND) \
_mac_len = MAX(_mac_len, (size_t) INFINIBAND_ALEN); \
offsetof(struct sockaddr_ll, sll_addr) + _mac_len; \
})
/* Covers only file system and abstract AF_UNIX socket addresses, but not unnamed socket addresses. */
#define SOCKADDR_UN_LEN(sa) \
({ \
const struct sockaddr_un *_sa = &(sa); \
assert(_sa->sun_family == AF_UNIX); \
offsetof(struct sockaddr_un, sun_path) + \
(_sa->sun_path[0] == 0 ? \
1 + strnlen(_sa->sun_path+1, sizeof(_sa->sun_path)-1) : \
strnlen(_sa->sun_path, sizeof(_sa->sun_path))+1); \
})
#define SOCKADDR_LEN(saddr) \
({ \
const union sockaddr_union *__sa = &(saddr); \
size_t _len; \
switch (__sa->sa.sa_family) { \
case AF_INET: \
_len = sizeof(struct sockaddr_in); \
break; \
case AF_INET6: \
_len = sizeof(struct sockaddr_in6); \
break; \
case AF_UNIX: \
_len = SOCKADDR_UN_LEN(__sa->un); \
break; \
case AF_PACKET: \
_len = SOCKADDR_LL_LEN(__sa->ll); \
break; \
case AF_NETLINK: \
_len = sizeof(struct sockaddr_nl); \
break; \
case AF_VSOCK: \
_len = sizeof(struct sockaddr_vm); \
break; \
default: \
assert_not_reached(); \
} \
_len; \
})
int socket_ioctl_fd(void);
int sockaddr_un_set_path(struct sockaddr_un *ret, const char *path);
static inline int setsockopt_int(int fd, int level, int optname, int value) {
if (setsockopt(fd, level, optname, &value, sizeof(value)) < 0)
return -errno;
return 0;
}
static inline int getsockopt_int(int fd, int level, int optname, int *ret) {
int v;
socklen_t sl = sizeof(v);
if (getsockopt(fd, level, optname, &v, &sl) < 0)
return negative_errno();
if (sl != sizeof(v))
return -EIO;
*ret = v;
return 0;
}
int socket_bind_to_ifname(int fd, const char *ifname);
int socket_bind_to_ifindex(int fd, int ifindex);
/* Define a 64-bit version of timeval/timespec in any case, even on 32-bit userspace. */
struct timeval_large {
uint64_t tvl_sec, tvl_usec;
};
struct timespec_large {
uint64_t tvl_sec, tvl_nsec;
};
/* glibc duplicates timespec/timeval on certain 32-bit arches, once in 32-bit and once in 64-bit.
* See __convert_scm_timestamps() in glibc source code. Hence, we need additional buffer space for them
* to prevent from recvmsg_safe() returning -EXFULL. */
#define CMSG_SPACE_TIMEVAL \
((sizeof(struct timeval) == sizeof(struct timeval_large)) ? \
CMSG_SPACE(sizeof(struct timeval)) : \
CMSG_SPACE(sizeof(struct timeval)) + \
CMSG_SPACE(sizeof(struct timeval_large)))
#define CMSG_SPACE_TIMESPEC \
((sizeof(struct timespec) == sizeof(struct timespec_large)) ? \
CMSG_SPACE(sizeof(struct timespec)) : \
CMSG_SPACE(sizeof(struct timespec)) + \
CMSG_SPACE(sizeof(struct timespec_large)))
ssize_t recvmsg_safe(int sockfd, struct msghdr *msg, int flags);
int socket_get_family(int fd);
int socket_set_recvpktinfo(int fd, int af, bool b);
int socket_set_unicast_if(int fd, int af, int ifi);
int socket_set_option(int fd, int af, int opt_ipv4, int opt_ipv6, int val);
static inline int socket_set_recverr(int fd, int af, bool b) {
return socket_set_option(fd, af, IP_RECVERR, IPV6_RECVERR, b);
}
static inline int socket_set_recvttl(int fd, int af, bool b) {
return socket_set_option(fd, af, IP_RECVTTL, IPV6_RECVHOPLIMIT, b);
}
static inline int socket_set_ttl(int fd, int af, int ttl) {
return socket_set_option(fd, af, IP_TTL, IPV6_UNICAST_HOPS, ttl);
}
static inline int socket_set_freebind(int fd, int af, bool b) {
return socket_set_option(fd, af, IP_FREEBIND, IPV6_FREEBIND, b);
}
static inline int socket_set_transparent(int fd, int af, bool b) {
return socket_set_option(fd, af, IP_TRANSPARENT, IPV6_TRANSPARENT, b);
}
static inline int socket_set_recvfragsize(int fd, int af, bool b) {
return socket_set_option(fd, af, IP_RECVFRAGSIZE, IPV6_RECVFRAGSIZE, b);
}
int socket_get_mtu(int fd, int af, size_t *ret);
/* an initializer for struct ucred that initialized all fields to the invalid value appropriate for each */
#define UCRED_INVALID { .pid = 0, .uid = UID_INVALID, .gid = GID_INVALID }
int connect_unix_path(int fd, int dir_fd, const char *path);
/* Parses AF_UNIX and AF_VSOCK addresses. AF_INET[6] require some netlink calls, so it cannot be in
* src/basic/ and is done from 'socket_local_address from src/shared/. Return -EPROTO in case of
* protocol mismatch. */
int socket_address_parse_unix(SocketAddress *ret_address, const char *s);
int socket_address_parse_vsock(SocketAddress *ret_address, const char *s);
/* libc's SOMAXCONN is defined to 128 or 4096 (at least on glibc). But actually, the value can be much
* larger. In our codebase we want to set it to the max usually, since noawadays socket memory is properly
* tracked by memcg, and hence we don't need to enforce extra limits here. Moreover, the kernel caps it to
* /proc/sys/net/core/somaxconn anyway, thus by setting this to unbounded we just make that sysctl file
* authoritative. */
#define SOMAXCONN_DELUXE INT_MAX
| 16,687 | 44.846154 | 127 | h |
null | systemd-main/src/basic/sort-util.c | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "sort-util.h"
#include "alloc-util.h"
/* hey glibc, APIs with callbacks without a user pointer are so useless */
void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
comparison_userdata_fn_t compar, void *arg) {
size_t l, u, idx;
const void *p;
int comparison;
assert(!size_multiply_overflow(nmemb, size));
l = 0;
u = nmemb;
while (l < u) {
idx = (l + u) / 2;
p = (const uint8_t*) base + idx * size;
comparison = compar(key, p, arg);
if (comparison < 0)
u = idx;
else if (comparison > 0)
l = idx + 1;
else
return (void *)p;
}
return NULL;
}
int cmp_int(const int *a, const int *b) {
return CMP(*a, *b);
}
| 959 | 27.235294 | 78 | c |
null | systemd-main/src/basic/sort-util.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdlib.h>
#include "macro.h"
/* This is the same as glibc's internal __compar_d_fn_t type. glibc exports a public comparison_fn_t, for the
* external type __compar_fn_t, but doesn't do anything similar for __compar_d_fn_t. Let's hence do that
* ourselves, picking a name that is obvious, but likely enough to not clash with glibc's choice of naming if
* they should ever add one. */
typedef int (*comparison_userdata_fn_t)(const void *, const void *, void *);
void *xbsearch_r(const void *key, const void *base, size_t nmemb, size_t size,
comparison_userdata_fn_t compar, void *arg);
#define typesafe_bsearch_r(k, b, n, func, userdata) \
({ \
const typeof((b)[0]) *_k = k; \
int (*_func_)(const typeof((b)[0])*, const typeof((b)[0])*, typeof(userdata)) = func; \
xbsearch_r((const void*) _k, (b), (n), sizeof((b)[0]), (comparison_userdata_fn_t) _func_, userdata); \
})
/**
* Normal bsearch requires base to be nonnull. Here were require
* that only if nmemb > 0.
*/
static inline void* bsearch_safe(const void *key, const void *base,
size_t nmemb, size_t size, comparison_fn_t compar) {
if (nmemb <= 0)
return NULL;
assert(base);
return bsearch(key, base, nmemb, size, compar);
}
#define typesafe_bsearch(k, b, n, func) \
({ \
const typeof((b)[0]) *_k = k; \
int (*_func_)(const typeof((b)[0])*, const typeof((b)[0])*) = func; \
bsearch_safe((const void*) _k, (b), (n), sizeof((b)[0]), (comparison_fn_t) _func_); \
})
/**
* Normal qsort requires base to be nonnull. Here were require
* that only if nmemb > 0.
*/
static inline void _qsort_safe(void *base, size_t nmemb, size_t size, comparison_fn_t compar) {
if (nmemb <= 1)
return;
assert(base);
qsort(base, nmemb, size, compar);
}
/* A wrapper around the above, but that adds typesafety: the element size is automatically derived from the type and so
* is the prototype for the comparison function */
#define typesafe_qsort(p, n, func) \
({ \
int (*_func_)(const typeof((p)[0])*, const typeof((p)[0])*) = func; \
_qsort_safe((p), (n), sizeof((p)[0]), (comparison_fn_t) _func_); \
})
static inline void qsort_r_safe(void *base, size_t nmemb, size_t size, comparison_userdata_fn_t compar, void *userdata) {
if (nmemb <= 1)
return;
assert(base);
qsort_r(base, nmemb, size, compar, userdata);
}
#define typesafe_qsort_r(p, n, func, userdata) \
({ \
int (*_func_)(const typeof((p)[0])*, const typeof((p)[0])*, typeof(userdata)) = func; \
qsort_r_safe((p), (n), sizeof((p)[0]), (comparison_userdata_fn_t) _func_, userdata); \
})
int cmp_int(const int *a, const int *b);
| 3,417 | 42.265823 | 121 | h |
null | systemd-main/src/basic/sparse-endian.h | /* SPDX-License-Identifier: MIT
*
* Copyright (c) 2012 Josh Triplett <[email protected]>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
#pragma once
#include <byteswap.h>
#include <endian.h>
#include <stdint.h>
#ifdef __CHECKER__
#define __sd_bitwise __attribute__((__bitwise__))
#define __sd_force __attribute__((__force__))
#else
#define __sd_bitwise
#define __sd_force
#endif
typedef uint16_t __sd_bitwise le16_t;
typedef uint16_t __sd_bitwise be16_t;
typedef uint32_t __sd_bitwise le32_t;
typedef uint32_t __sd_bitwise be32_t;
typedef uint64_t __sd_bitwise le64_t;
typedef uint64_t __sd_bitwise be64_t;
#undef htobe16
#undef htole16
#undef be16toh
#undef le16toh
#undef htobe32
#undef htole32
#undef be32toh
#undef le32toh
#undef htobe64
#undef htole64
#undef be64toh
#undef le64toh
#if __BYTE_ORDER == __LITTLE_ENDIAN
#define bswap_16_on_le(x) bswap_16(x)
#define bswap_32_on_le(x) bswap_32(x)
#define bswap_64_on_le(x) bswap_64(x)
#define bswap_16_on_be(x) (x)
#define bswap_32_on_be(x) (x)
#define bswap_64_on_be(x) (x)
#elif __BYTE_ORDER == __BIG_ENDIAN
#define bswap_16_on_le(x) (x)
#define bswap_32_on_le(x) (x)
#define bswap_64_on_le(x) (x)
#define bswap_16_on_be(x) bswap_16(x)
#define bswap_32_on_be(x) bswap_32(x)
#define bswap_64_on_be(x) bswap_64(x)
#endif
static inline le16_t htole16(uint16_t value) { return (le16_t __sd_force) bswap_16_on_be(value); }
static inline le32_t htole32(uint32_t value) { return (le32_t __sd_force) bswap_32_on_be(value); }
static inline le64_t htole64(uint64_t value) { return (le64_t __sd_force) bswap_64_on_be(value); }
static inline be16_t htobe16(uint16_t value) { return (be16_t __sd_force) bswap_16_on_le(value); }
static inline be32_t htobe32(uint32_t value) { return (be32_t __sd_force) bswap_32_on_le(value); }
static inline be64_t htobe64(uint64_t value) { return (be64_t __sd_force) bswap_64_on_le(value); }
static inline uint16_t le16toh(le16_t value) { return bswap_16_on_be((uint16_t __sd_force)value); }
static inline uint32_t le32toh(le32_t value) { return bswap_32_on_be((uint32_t __sd_force)value); }
static inline uint64_t le64toh(le64_t value) { return bswap_64_on_be((uint64_t __sd_force)value); }
static inline uint16_t be16toh(be16_t value) { return bswap_16_on_le((uint16_t __sd_force)value); }
static inline uint32_t be32toh(be32_t value) { return bswap_32_on_le((uint32_t __sd_force)value); }
static inline uint64_t be64toh(be64_t value) { return bswap_64_on_le((uint64_t __sd_force)value); }
#undef __sd_bitwise
#undef __sd_force
| 3,553 | 38.054945 | 99 | h |
null | systemd-main/src/basic/special.h | /* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#define SPECIAL_DEFAULT_TARGET "default.target"
#define SPECIAL_INITRD_TARGET "initrd.target"
/* Shutdown targets */
#define SPECIAL_UMOUNT_TARGET "umount.target"
/* This is not really intended to be started by directly. This is
* mostly so that other targets (reboot/halt/poweroff) can depend on
* it to bring all services down that want to be brought down on
* system shutdown. */
#define SPECIAL_SHUTDOWN_TARGET "shutdown.target"
#define SPECIAL_HALT_TARGET "halt.target"
#define SPECIAL_POWEROFF_TARGET "poweroff.target"
#define SPECIAL_REBOOT_TARGET "reboot.target"
#define SPECIAL_SOFT_REBOOT_TARGET "soft-reboot.target"
#define SPECIAL_KEXEC_TARGET "kexec.target"
#define SPECIAL_EXIT_TARGET "exit.target"
#define SPECIAL_SUSPEND_TARGET "suspend.target"
#define SPECIAL_HIBERNATE_TARGET "hibernate.target"
#define SPECIAL_HYBRID_SLEEP_TARGET "hybrid-sleep.target"
#define SPECIAL_SUSPEND_THEN_HIBERNATE_TARGET "suspend-then-hibernate.target"
#define SPECIAL_FACTORY_RESET_TARGET "factory-reset.target"
/* Special boot targets */
#define SPECIAL_RESCUE_TARGET "rescue.target"
#define SPECIAL_EMERGENCY_TARGET "emergency.target"
#define SPECIAL_MULTI_USER_TARGET "multi-user.target"
#define SPECIAL_GRAPHICAL_TARGET "graphical.target"
/* Early boot targets */
#define SPECIAL_SYSINIT_TARGET "sysinit.target"
#define SPECIAL_SOCKETS_TARGET "sockets.target"
#define SPECIAL_TIMERS_TARGET "timers.target"
#define SPECIAL_PATHS_TARGET "paths.target"
#define SPECIAL_LOCAL_FS_TARGET "local-fs.target"
#define SPECIAL_LOCAL_FS_PRE_TARGET "local-fs-pre.target"
#define SPECIAL_INITRD_FS_TARGET "initrd-fs.target"
#define SPECIAL_INITRD_ROOT_DEVICE_TARGET "initrd-root-device.target"
#define SPECIAL_INITRD_ROOT_FS_TARGET "initrd-root-fs.target"
#define SPECIAL_INITRD_USR_FS_TARGET "initrd-usr-fs.target"
#define SPECIAL_REMOTE_FS_TARGET "remote-fs.target" /* LSB's $remote_fs */
#define SPECIAL_REMOTE_FS_PRE_TARGET "remote-fs-pre.target"
#define SPECIAL_SWAP_TARGET "swap.target"
#define SPECIAL_NETWORK_ONLINE_TARGET "network-online.target"
#define SPECIAL_TIME_SYNC_TARGET "time-sync.target" /* LSB's $time */
#define SPECIAL_TIME_SET_TARGET "time-set.target"
#define SPECIAL_BASIC_TARGET "basic.target"
/* LSB compatibility */
#define SPECIAL_NETWORK_TARGET "network.target" /* LSB's $network */
#define SPECIAL_NSS_LOOKUP_TARGET "nss-lookup.target" /* LSB's $named */
#define SPECIAL_RPCBIND_TARGET "rpcbind.target" /* LSB's $portmap */
/*
* Rules regarding adding further high level targets like the above:
*
* - Be conservative, only add more of these when we really need
* them. We need strong usecases for further additions.
*
* - When there can be multiple implementations running side-by-side,
* it needs to be a .target unit which can pull in all
* implementations.
*
* - If something can be implemented with socket activation, and
* without, it needs to be a .target unit, so that it can pull in
* the appropriate unit.
*
* - Otherwise, it should be a .service unit.
*
* - In some cases it is OK to have both a .service and a .target
* unit, i.e. if there can be multiple parallel implementations, but
* only one is the "system" one. Example: syslog.
*
* Or to put this in other words: .service symlinks can be used to
* arbitrate between multiple implementations if there can be only one
* of a kind. .target units can be used to support multiple
* implementations that can run side-by-side.
*/
/* Magic early boot services */
#define SPECIAL_FSCK_SERVICE "[email protected]"
#define SPECIAL_FSCK_ROOT_SERVICE "systemd-fsck-root.service"
#define SPECIAL_FSCK_USR_SERVICE "systemd-fsck-usr.service"
#define SPECIAL_QUOTACHECK_SERVICE "systemd-quotacheck.service"
#define SPECIAL_QUOTAON_SERVICE "quotaon.service"
#define SPECIAL_REMOUNT_FS_SERVICE "systemd-remount-fs.service"
#define SPECIAL_VOLATILE_ROOT_SERVICE "systemd-volatile-root.service"
#define SPECIAL_UDEVD_SERVICE "systemd-udevd.service"
#define SPECIAL_GROWFS_SERVICE "[email protected]"
#define SPECIAL_GROWFS_ROOT_SERVICE "systemd-growfs-root.service"
#define SPECIAL_PCRFS_SERVICE "[email protected]"
#define SPECIAL_PCRFS_ROOT_SERVICE "systemd-pcrfs-root.service"
#define SPECIAL_HIBERNATE_RESUME_SERVICE "systemd-hibernate-resume.service"
/* Services systemd relies on */
#define SPECIAL_DBUS_SERVICE "dbus.service"
#define SPECIAL_DBUS_SOCKET "dbus.socket"
#define SPECIAL_JOURNALD_SOCKET "systemd-journald.socket"
#define SPECIAL_JOURNALD_SERVICE "systemd-journald.service"
#define SPECIAL_TMPFILES_SETUP_SERVICE "systemd-tmpfiles-setup.service"
/* Magic init signals */
#define SPECIAL_KBREQUEST_TARGET "kbrequest.target"
#define SPECIAL_SIGPWR_TARGET "sigpwr.target"
#define SPECIAL_CTRL_ALT_DEL_TARGET "ctrl-alt-del.target"
/* Where we add all our system units, users and machines by default */
#define SPECIAL_SYSTEM_SLICE "system.slice"
#define SPECIAL_USER_SLICE "user.slice"
#define SPECIAL_MACHINE_SLICE "machine.slice"
#define SPECIAL_ROOT_SLICE "-.slice"
/* The scope unit systemd itself lives in. */
#define SPECIAL_INIT_SCOPE "init.scope"
/* The root directory. */
#define SPECIAL_ROOT_MOUNT "-.mount"
/* Special slices valid for the user instance */
#define SPECIAL_SESSION_SLICE "session.slice"
#define SPECIAL_APP_SLICE "app.slice"
#define SPECIAL_BACKGROUND_SLICE "background.slice"
| 5,449 | 42.6 | 80 | h |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.