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/shared/compare-operator.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fnmatch.h>
#include "compare-operator.h"
#include "string-util.h"
CompareOperator parse_compare_operator(const char **s, CompareOperatorParseFlags flags) {
static const struct {
CompareOperator op;
const char *str;
CompareOperatorParseFlags valid_mask; /* If this operator appears when flags in mask not set, fail */
CompareOperatorParseFlags need_mask; /* Skip over this operator when flags in mask not set */
} table[] = {
{ COMPARE_FNMATCH_EQUAL, "$=", .valid_mask = COMPARE_ALLOW_FNMATCH },
{ COMPARE_FNMATCH_UNEQUAL, "!$=", .valid_mask = COMPARE_ALLOW_FNMATCH },
{ COMPARE_UNEQUAL, "<>" },
{ COMPARE_LOWER_OR_EQUAL, "<=" },
{ COMPARE_GREATER_OR_EQUAL, ">=" },
{ COMPARE_LOWER, "<" },
{ COMPARE_GREATER, ">" },
{ COMPARE_EQUAL, "==" },
{ COMPARE_STRING_EQUAL, "=", .need_mask = COMPARE_EQUAL_BY_STRING },
{ COMPARE_EQUAL, "=" },
{ COMPARE_STRING_UNEQUAL, "!=", .need_mask = COMPARE_EQUAL_BY_STRING },
{ COMPARE_UNEQUAL, "!=" },
{ COMPARE_LOWER, "lt", .valid_mask = COMPARE_ALLOW_TEXTUAL },
{ COMPARE_LOWER_OR_EQUAL, "le", .valid_mask = COMPARE_ALLOW_TEXTUAL },
{ COMPARE_EQUAL, "eq", .valid_mask = COMPARE_ALLOW_TEXTUAL },
{ COMPARE_UNEQUAL, "ne", .valid_mask = COMPARE_ALLOW_TEXTUAL },
{ COMPARE_GREATER_OR_EQUAL, "ge", .valid_mask = COMPARE_ALLOW_TEXTUAL },
{ COMPARE_GREATER, "gt", .valid_mask = COMPARE_ALLOW_TEXTUAL },
};
assert(s);
if (!*s) /* Hmm, we already reached the end, for example because extract_first_word() and
* parse_compare_operator() are use on the same string? */
return _COMPARE_OPERATOR_INVALID;
for (size_t i = 0; i < ELEMENTSOF(table); i ++) {
const char *e;
if (table[i].need_mask != 0 && !FLAGS_SET(flags, table[i].need_mask))
continue;
e = startswith(*s, table[i].str);
if (e) {
if (table[i].valid_mask != 0 && !FLAGS_SET(flags, table[i].valid_mask))
return _COMPARE_OPERATOR_INVALID;
*s = e;
return table[i].op;
}
}
return _COMPARE_OPERATOR_INVALID;
}
int test_order(int k, CompareOperator op) {
switch (op) {
case COMPARE_LOWER:
return k < 0;
case COMPARE_LOWER_OR_EQUAL:
return k <= 0;
case COMPARE_EQUAL:
return k == 0;
case COMPARE_UNEQUAL:
return k != 0;
case COMPARE_GREATER_OR_EQUAL:
return k >= 0;
case COMPARE_GREATER:
return k > 0;
default:
return -EINVAL;
}
}
int version_or_fnmatch_compare(
CompareOperator op,
const char *a,
const char *b) {
int r;
switch (op) {
case COMPARE_STRING_EQUAL:
return streq_ptr(a, b);
case COMPARE_STRING_UNEQUAL:
return !streq_ptr(a, b);
case COMPARE_FNMATCH_EQUAL:
r = fnmatch(b, a, 0);
return r == 0 ? true :
r == FNM_NOMATCH ? false : -EINVAL;
case COMPARE_FNMATCH_UNEQUAL:
r = fnmatch(b, a, 0);
return r == FNM_NOMATCH ? true:
r == 0 ? false : -EINVAL;
case _COMPARE_OPERATOR_ORDER_FIRST..._COMPARE_OPERATOR_ORDER_LAST:
return test_order(strverscmp_improved(a, b), op);
default:
return -EINVAL;
}
}
| 4,472 | 36.275 | 117 |
c
|
null |
systemd-main/src/shared/compare-operator.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include <stdbool.h>
#define COMPARE_OPERATOR_CHARS "!<=>"
#define COMPARE_OPERATOR_WITH_FNMATCH_CHARS COMPARE_OPERATOR_CHARS "$"
typedef enum CompareOperator {
/* Listed in order of checking. Note that some comparators are prefixes of others, hence the longest
* should be listed first. */
/* Simple string compare operators */
_COMPARE_OPERATOR_STRING_FIRST,
COMPARE_STRING_EQUAL = _COMPARE_OPERATOR_STRING_FIRST,
COMPARE_STRING_UNEQUAL,
_COMPARE_OPERATOR_STRING_LAST = COMPARE_STRING_UNEQUAL,
/* fnmatch() compare operators */
_COMPARE_OPERATOR_FNMATCH_FIRST,
COMPARE_FNMATCH_EQUAL = _COMPARE_OPERATOR_FNMATCH_FIRST,
COMPARE_FNMATCH_UNEQUAL,
_COMPARE_OPERATOR_FNMATCH_LAST = COMPARE_FNMATCH_UNEQUAL,
/* Order compare operators */
_COMPARE_OPERATOR_ORDER_FIRST,
COMPARE_LOWER_OR_EQUAL = _COMPARE_OPERATOR_ORDER_FIRST,
COMPARE_GREATER_OR_EQUAL,
COMPARE_LOWER,
COMPARE_GREATER,
COMPARE_EQUAL,
COMPARE_UNEQUAL,
_COMPARE_OPERATOR_ORDER_LAST = COMPARE_UNEQUAL,
_COMPARE_OPERATOR_MAX,
_COMPARE_OPERATOR_INVALID = -EINVAL,
} CompareOperator;
static inline bool COMPARE_OPERATOR_IS_STRING(CompareOperator c) {
return c >= _COMPARE_OPERATOR_STRING_FIRST && c <= _COMPARE_OPERATOR_STRING_LAST;
}
static inline bool COMPARE_OPERATOR_IS_FNMATCH(CompareOperator c) {
return c >= _COMPARE_OPERATOR_FNMATCH_FIRST && c <= _COMPARE_OPERATOR_FNMATCH_LAST;
}
static inline bool COMPARE_OPERATOR_IS_ORDER(CompareOperator c) {
return c >= _COMPARE_OPERATOR_ORDER_FIRST && c <= _COMPARE_OPERATOR_ORDER_LAST;
}
typedef enum CompareOperatorParseFlags {
COMPARE_ALLOW_FNMATCH = 1 << 0,
COMPARE_EQUAL_BY_STRING = 1 << 1,
COMPARE_ALLOW_TEXTUAL = 1 << 2,
} CompareOperatorParseFlags;
CompareOperator parse_compare_operator(const char **s, CompareOperatorParseFlags flags);
int test_order(int k, CompareOperator op);
int version_or_fnmatch_compare(CompareOperator op, const char *a, const char *b);
| 2,204 | 34 | 108 |
h
|
null |
systemd-main/src/shared/coredump-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <elf.h>
#include "coredump-util.h"
#include "extract-word.h"
#include "fileio.h"
#include "string-table.h"
#include "unaligned.h"
#include "virt.h"
static const char *const coredump_filter_table[_COREDUMP_FILTER_MAX] = {
[COREDUMP_FILTER_PRIVATE_ANONYMOUS] = "private-anonymous",
[COREDUMP_FILTER_SHARED_ANONYMOUS] = "shared-anonymous",
[COREDUMP_FILTER_PRIVATE_FILE_BACKED] = "private-file-backed",
[COREDUMP_FILTER_SHARED_FILE_BACKED] = "shared-file-backed",
[COREDUMP_FILTER_ELF_HEADERS] = "elf-headers",
[COREDUMP_FILTER_PRIVATE_HUGE] = "private-huge",
[COREDUMP_FILTER_SHARED_HUGE] = "shared-huge",
[COREDUMP_FILTER_PRIVATE_DAX] = "private-dax",
[COREDUMP_FILTER_SHARED_DAX] = "shared-dax",
};
DEFINE_STRING_TABLE_LOOKUP(coredump_filter, CoredumpFilter);
int coredump_filter_mask_from_string(const char *s, uint64_t *ret) {
uint64_t m = 0;
assert(s);
assert(ret);
for (;;) {
_cleanup_free_ char *n = NULL;
CoredumpFilter v;
int r;
r = extract_first_word(&s, &n, NULL, 0);
if (r < 0)
return r;
if (r == 0)
break;
if (streq(n, "default")) {
m |= COREDUMP_FILTER_MASK_DEFAULT;
continue;
}
if (streq(n, "all")) {
m = COREDUMP_FILTER_MASK_ALL;
continue;
}
v = coredump_filter_from_string(n);
if (v >= 0) {
m |= 1u << v;
continue;
}
uint64_t x;
r = safe_atoux64(n, &x);
if (r < 0)
return r;
m |= x;
}
*ret = m;
return 0;
}
#define _DEFINE_PARSE_AUXV(size, type, unaligned_read) \
static int parse_auxv##size( \
int log_level, \
const void *auxv, \
size_t size_bytes, \
int *at_secure, \
uid_t *uid, \
uid_t *euid, \
gid_t *gid, \
gid_t *egid) { \
\
assert(auxv || size_bytes == 0); \
assert(at_secure); \
assert(uid); \
assert(euid); \
assert(gid); \
assert(egid); \
\
if (size_bytes % (2 * sizeof(type)) != 0) \
return log_full_errno(log_level, \
SYNTHETIC_ERRNO(EIO), \
"Incomplete auxv structure (%zu bytes).", \
size_bytes); \
\
size_t words = size_bytes / sizeof(type); \
\
/* Note that we set output variables even on error. */ \
\
for (size_t i = 0; i + 1 < words; i += 2) { \
type key, val; \
\
key = unaligned_read((uint8_t*) auxv + i * sizeof(type)); \
val = unaligned_read((uint8_t*) auxv + (i + 1) * sizeof(type)); \
\
switch (key) { \
case AT_SECURE: \
*at_secure = val != 0; \
break; \
case AT_UID: \
*uid = val; \
break; \
case AT_EUID: \
*euid = val; \
break; \
case AT_GID: \
*gid = val; \
break; \
case AT_EGID: \
*egid = val; \
break; \
case AT_NULL: \
if (val != 0) \
goto error; \
return 0; \
} \
} \
error: \
return log_full_errno(log_level, \
SYNTHETIC_ERRNO(ENODATA), \
"AT_NULL terminator not found, cannot parse auxv structure."); \
}
#define DEFINE_PARSE_AUXV(size) \
_DEFINE_PARSE_AUXV(size, uint##size##_t, unaligned_read_ne##size)
DEFINE_PARSE_AUXV(32);
DEFINE_PARSE_AUXV(64);
int parse_auxv(int log_level,
uint8_t elf_class,
const void *auxv,
size_t size_bytes,
int *at_secure,
uid_t *uid,
uid_t *euid,
gid_t *gid,
gid_t *egid) {
switch (elf_class) {
case ELFCLASS64:
return parse_auxv64(log_level, auxv, size_bytes, at_secure, uid, euid, gid, egid);
case ELFCLASS32:
return parse_auxv32(log_level, auxv, size_bytes, at_secure, uid, euid, gid, egid);
default:
return log_full_errno(log_level, SYNTHETIC_ERRNO(EPROTONOSUPPORT),
"Unknown ELF class %d.", elf_class);
}
}
int set_coredump_filter(uint64_t value) {
char t[HEXADECIMAL_STR_MAX(uint64_t)];
xsprintf(t, "0x%"PRIx64, value);
return write_string_file("/proc/self/coredump_filter", t,
WRITE_STRING_FILE_VERIFY_ON_FAILURE|WRITE_STRING_FILE_DISABLE_BUFFER);
}
/* Turn off core dumps but only if we're running outside of a container. */
void disable_coredumps(void) {
int r;
if (detect_container() > 0)
return;
r = write_string_file("/proc/sys/kernel/core_pattern", "|/bin/false", WRITE_STRING_FILE_DISABLE_BUFFER);
if (r < 0)
log_debug_errno(r, "Failed to turn off coredumps, ignoring: %m");
}
| 8,220 | 44.672222 | 112 |
c
|
null |
systemd-main/src/shared/coredump-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "macro.h"
typedef enum CoredumpFilter {
COREDUMP_FILTER_PRIVATE_ANONYMOUS = 0,
COREDUMP_FILTER_SHARED_ANONYMOUS,
COREDUMP_FILTER_PRIVATE_FILE_BACKED,
COREDUMP_FILTER_SHARED_FILE_BACKED,
COREDUMP_FILTER_ELF_HEADERS,
COREDUMP_FILTER_PRIVATE_HUGE,
COREDUMP_FILTER_SHARED_HUGE,
COREDUMP_FILTER_PRIVATE_DAX,
COREDUMP_FILTER_SHARED_DAX,
_COREDUMP_FILTER_MAX,
_COREDUMP_FILTER_INVALID = -EINVAL,
} CoredumpFilter;
#define COREDUMP_FILTER_MASK_DEFAULT (1u << COREDUMP_FILTER_PRIVATE_ANONYMOUS | \
1u << COREDUMP_FILTER_SHARED_ANONYMOUS | \
1u << COREDUMP_FILTER_ELF_HEADERS | \
1u << COREDUMP_FILTER_PRIVATE_HUGE)
/* The kernel doesn't like UINT64_MAX and returns ERANGE, use UINT32_MAX to support future new flags */
#define COREDUMP_FILTER_MASK_ALL UINT32_MAX
const char* coredump_filter_to_string(CoredumpFilter i) _const_;
CoredumpFilter coredump_filter_from_string(const char *s) _pure_;
int coredump_filter_mask_from_string(const char *s, uint64_t *ret);
int parse_auxv(int log_level,
uint8_t elf_class,
const void *auxv,
size_t size_bytes,
int *at_secure,
uid_t *uid,
uid_t *euid,
gid_t *gid,
gid_t *egid);
int set_coredump_filter(uint64_t value);
void disable_coredumps(void);
| 1,577 | 34.863636 | 103 |
h
|
null |
systemd-main/src/shared/cpu-set-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stddef.h>
#include <stdio.h>
#include <syslog.h>
#include "alloc-util.h"
#include "cpu-set-util.h"
#include "dirent-util.h"
#include "errno-util.h"
#include "extract-word.h"
#include "fd-util.h"
#include "log.h"
#include "macro.h"
#include "memory-util.h"
#include "parse-util.h"
#include "stat-util.h"
#include "string-util.h"
#include "strv.h"
char* cpu_set_to_string(const CPUSet *a) {
_cleanup_free_ char *str = NULL;
size_t len = 0;
int i, r;
for (i = 0; (size_t) i < a->allocated * 8; i++) {
if (!CPU_ISSET_S(i, a->allocated, a->set))
continue;
if (!GREEDY_REALLOC(str, len + 1 + DECIMAL_STR_MAX(int)))
return NULL;
r = sprintf(str + len, len > 0 ? " %d" : "%d", i);
assert_se(r > 0);
len += r;
}
return TAKE_PTR(str) ?: strdup("");
}
char *cpu_set_to_range_string(const CPUSet *set) {
unsigned range_start = 0, range_end;
_cleanup_free_ char *str = NULL;
bool in_range = false;
size_t len = 0;
int r;
for (unsigned i = 0; i < set->allocated * 8; i++)
if (CPU_ISSET_S(i, set->allocated, set->set)) {
if (in_range)
range_end++;
else {
range_start = range_end = i;
in_range = true;
}
} else if (in_range) {
in_range = false;
if (!GREEDY_REALLOC(str, len + 2 + 2 * DECIMAL_STR_MAX(unsigned)))
return NULL;
if (range_end > range_start)
r = sprintf(str + len, len > 0 ? " %u-%u" : "%u-%u", range_start, range_end);
else
r = sprintf(str + len, len > 0 ? " %u" : "%u", range_start);
assert_se(r > 0);
len += r;
}
if (in_range) {
if (!GREEDY_REALLOC(str, len + 2 + 2 * DECIMAL_STR_MAX(int)))
return NULL;
if (range_end > range_start)
r = sprintf(str + len, len > 0 ? " %u-%u" : "%u-%u", range_start, range_end);
else
r = sprintf(str + len, len > 0 ? " %u" : "%u", range_start);
assert_se(r > 0);
}
return TAKE_PTR(str) ?: strdup("");
}
int cpu_set_realloc(CPUSet *cpu_set, unsigned ncpus) {
size_t need;
assert(cpu_set);
need = CPU_ALLOC_SIZE(ncpus);
if (need > cpu_set->allocated) {
cpu_set_t *t;
t = realloc(cpu_set->set, need);
if (!t)
return -ENOMEM;
memzero((uint8_t*) t + cpu_set->allocated, need - cpu_set->allocated);
cpu_set->set = t;
cpu_set->allocated = need;
}
return 0;
}
int cpu_set_add(CPUSet *cpu_set, unsigned cpu) {
int r;
if (cpu >= 8192)
/* As of kernel 5.1, CONFIG_NR_CPUS can be set to 8192 on PowerPC */
return -ERANGE;
r = cpu_set_realloc(cpu_set, cpu + 1);
if (r < 0)
return r;
CPU_SET_S(cpu, cpu_set->allocated, cpu_set->set);
return 0;
}
int cpu_set_add_all(CPUSet *a, const CPUSet *b) {
int r;
/* Do this backwards, so if we fail, we fail before changing anything. */
for (unsigned cpu_p1 = b->allocated * 8; cpu_p1 > 0; cpu_p1--)
if (CPU_ISSET_S(cpu_p1 - 1, b->allocated, b->set)) {
r = cpu_set_add(a, cpu_p1 - 1);
if (r < 0)
return r;
}
return 1;
}
int parse_cpu_set_full(
const char *rvalue,
CPUSet *cpu_set,
bool warn,
const char *unit,
const char *filename,
unsigned line,
const char *lvalue) {
_cleanup_(cpu_set_reset) CPUSet c = {};
const char *p = ASSERT_PTR(rvalue);
assert(cpu_set);
for (;;) {
_cleanup_free_ char *word = NULL;
unsigned cpu_lower, cpu_upper;
int r;
r = extract_first_word(&p, &word, WHITESPACE ",", EXTRACT_UNQUOTE);
if (r == -ENOMEM)
return warn ? log_oom() : -ENOMEM;
if (r < 0)
return warn ? log_syntax(unit, LOG_ERR, filename, line, r, "Invalid value for %s: %s", lvalue, rvalue) : r;
if (r == 0)
break;
r = parse_range(word, &cpu_lower, &cpu_upper);
if (r < 0)
return warn ? log_syntax(unit, LOG_ERR, filename, line, r, "Failed to parse CPU affinity '%s'", word) : r;
if (cpu_lower > cpu_upper) {
if (warn)
log_syntax(unit, LOG_WARNING, filename, line, 0, "Range '%s' is invalid, %u > %u, ignoring.",
word, cpu_lower, cpu_upper);
/* Make sure something is allocated, to distinguish this from the empty case */
r = cpu_set_realloc(&c, 1);
if (r < 0)
return r;
}
for (unsigned cpu_p1 = MIN(cpu_upper, UINT_MAX-1) + 1; cpu_p1 > cpu_lower; cpu_p1--) {
r = cpu_set_add(&c, cpu_p1 - 1);
if (r < 0)
return warn ? log_syntax(unit, LOG_ERR, filename, line, r,
"Cannot add CPU %u to set: %m", cpu_p1 - 1) : r;
}
}
*cpu_set = TAKE_STRUCT(c);
return 0;
}
int parse_cpu_set_extend(
const char *rvalue,
CPUSet *old,
bool warn,
const char *unit,
const char *filename,
unsigned line,
const char *lvalue) {
_cleanup_(cpu_set_reset) CPUSet cpuset = {};
int r;
assert(old);
r = parse_cpu_set_full(rvalue, &cpuset, true, unit, filename, line, lvalue);
if (r < 0)
return r;
if (!cpuset.set) {
/* An empty assignment resets the CPU list */
cpu_set_reset(old);
return 0;
}
if (!old->set) {
*old = TAKE_STRUCT(cpuset);
return 1;
}
return cpu_set_add_all(old, &cpuset);
}
int cpus_in_affinity_mask(void) {
size_t n = 16;
int r;
for (;;) {
cpu_set_t *c;
c = CPU_ALLOC(n);
if (!c)
return -ENOMEM;
if (sched_getaffinity(0, CPU_ALLOC_SIZE(n), c) >= 0) {
int k;
k = CPU_COUNT_S(CPU_ALLOC_SIZE(n), c);
CPU_FREE(c);
if (k <= 0)
return -EINVAL;
return k;
}
r = -errno;
CPU_FREE(c);
if (r != -EINVAL)
return r;
if (n > SIZE_MAX/2)
return -ENOMEM;
n *= 2;
}
}
int cpu_set_to_dbus(const CPUSet *set, uint8_t **ret, size_t *allocated) {
uint8_t *out;
assert(set);
assert(ret);
out = new0(uint8_t, set->allocated);
if (!out)
return -ENOMEM;
for (unsigned cpu = 0; cpu < set->allocated * 8; cpu++)
if (CPU_ISSET_S(cpu, set->allocated, set->set))
out[cpu / 8] |= 1u << (cpu % 8);
*ret = out;
*allocated = set->allocated;
return 0;
}
int cpu_set_from_dbus(const uint8_t *bits, size_t size, CPUSet *set) {
_cleanup_(cpu_set_reset) CPUSet s = {};
int r;
assert(bits);
assert(set);
for (unsigned cpu = size * 8; cpu > 0; cpu--)
if (bits[(cpu - 1) / 8] & (1u << ((cpu - 1) % 8))) {
r = cpu_set_add(&s, cpu - 1);
if (r < 0)
return r;
}
*set = TAKE_STRUCT(s);
return 0;
}
| 8,785 | 28.986348 | 131 |
c
|
null |
systemd-main/src/shared/cpu-set-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sched.h>
#include "macro.h"
#include "missing_syscall.h"
/* This wraps the libc interface with a variable to keep the allocated size. */
typedef struct CPUSet {
cpu_set_t *set;
size_t allocated; /* in bytes */
} CPUSet;
static inline void cpu_set_reset(CPUSet *a) {
assert((a->allocated > 0) == !!a->set);
if (a->set)
CPU_FREE(a->set);
*a = (CPUSet) {};
}
int cpu_set_add_all(CPUSet *a, const CPUSet *b);
int cpu_set_add(CPUSet *a, unsigned cpu);
char* cpu_set_to_string(const CPUSet *a);
char *cpu_set_to_range_string(const CPUSet *a);
int cpu_set_realloc(CPUSet *cpu_set, unsigned ncpus);
int parse_cpu_set_full(
const char *rvalue,
CPUSet *cpu_set,
bool warn,
const char *unit,
const char *filename, unsigned line,
const char *lvalue);
int parse_cpu_set_extend(
const char *rvalue,
CPUSet *old,
bool warn,
const char *unit,
const char *filename,
unsigned line,
const char *lvalue);
static inline int parse_cpu_set(const char *rvalue, CPUSet *cpu_set){
return parse_cpu_set_full(rvalue, cpu_set, false, NULL, NULL, 0, NULL);
}
int cpu_set_to_dbus(const CPUSet *set, uint8_t **ret, size_t *allocated);
int cpu_set_from_dbus(const uint8_t *bits, size_t size, CPUSet *set);
int cpus_in_affinity_mask(void);
| 1,560 | 28.45283 | 79 |
h
|
null |
systemd-main/src/shared/cryptsetup-fido2.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/types.h>
#include "cryptsetup-util.h"
#include "libfido2-util.h"
#include "log.h"
#include "time-util.h"
#if HAVE_LIBFIDO2
int acquire_fido2_key(
const char *volume_name,
const char *friendly_name,
const char *device,
const char *rp_id,
const void *cid,
size_t cid_size,
const char *key_file,
size_t key_file_size,
uint64_t key_file_offset,
const void *key_data,
size_t key_data_size,
usec_t until,
bool headless,
Fido2EnrollFlags required,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size,
AskPasswordFlags ask_password_flags);
int acquire_fido2_key_auto(
struct crypt_device *cd,
const char *name,
const char *friendly_name,
const char *fido2_device,
usec_t until,
bool headless,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size,
AskPasswordFlags ask_password_flags);
#else
static inline int acquire_fido2_key(
const char *volume_name,
const char *friendly_name,
const char *device,
const char *rp_id,
const void *cid,
size_t cid_size,
const char *key_file,
size_t key_file_size,
uint64_t key_file_offset,
const void *key_data,
size_t key_data_size,
usec_t until,
bool headless,
Fido2EnrollFlags required,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size,
AskPasswordFlags ask_password_flags) {
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"FIDO2 token support not available.");
}
static inline int acquire_fido2_key_auto(
struct crypt_device *cd,
const char *name,
const char *friendly_name,
const char *fido2_device,
usec_t until,
bool headless,
void **ret_decrypted_key,
size_t *ret_decrypted_key_size,
AskPasswordFlags ask_password_flags) {
return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"FIDO2 token support not available.");
}
#endif
| 2,674 | 31.228916 | 69 |
h
|
null |
systemd-main/src/shared/daemon-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "daemon-util.h"
#include "fd-util.h"
#include "log.h"
#include "string-util.h"
static int notify_remove_fd_warn(const char *name) {
int r;
assert(name);
r = sd_notifyf(/* unset_environment = */ false,
"FDSTOREREMOVE=1\n"
"FDNAME=%s", name);
if (r < 0)
return log_warning_errno(r,
"Failed to remove file descriptor \"%s\" from the store, ignoring: %m",
name);
return 0;
}
int notify_remove_fd_warnf(const char *format, ...) {
_cleanup_free_ char *p = NULL;
va_list ap;
int r;
assert(format);
va_start(ap, format);
r = vasprintf(&p, format, ap);
va_end(ap);
if (r < 0)
return log_oom();
return notify_remove_fd_warn(p);
}
int close_and_notify_warn(int fd, const char *name) {
if (name)
(void) notify_remove_fd_warn(name);
return safe_close(fd);
}
static int notify_push_fd(int fd, const char *name) {
_cleanup_free_ char *state = NULL;
assert(fd >= 0);
assert(name);
state = strjoin("FDSTORE=1\n"
"FDNAME=", name);
if (!state)
return -ENOMEM;
return sd_pid_notify_with_fds(0, /* unset_environment = */ false, state, &fd, 1);
}
int notify_push_fdf(int fd, const char *format, ...) {
_cleanup_free_ char *name = NULL;
va_list ap;
int r;
assert(fd >= 0);
assert(format);
va_start(ap, format);
r = vasprintf(&name, format, ap);
va_end(ap);
if (r < 0)
return -ENOMEM;
return notify_push_fd(fd, name);
}
| 1,861 | 23.181818 | 112 |
c
|
null |
systemd-main/src/shared/daemon-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "sd-daemon.h"
#include "macro.h"
#define NOTIFY_READY "READY=1\n" "STATUS=Processing requests..."
#define NOTIFY_STOPPING "STOPPING=1\n" "STATUS=Shutting down..."
static inline const char *notify_start(const char *start, const char *stop) {
if (start)
(void) sd_notify(false, start);
return stop;
}
/* This is intended to be used with _cleanup_ attribute. */
static inline void notify_on_cleanup(const char **p) {
if (*p)
(void) sd_notify(false, *p);
}
int notify_remove_fd_warnf(const char *format, ...) _printf_(1, 2);
int close_and_notify_warn(int fd, const char *name);
int notify_push_fdf(int fd, const char *format, ...) _printf_(2, 3);
| 799 | 26.586207 | 77 |
h
|
null |
systemd-main/src/shared/data-fd-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
#if HAVE_LINUX_MEMFD_H
#include <linux/memfd.h>
#endif
#include "alloc-util.h"
#include "copy.h"
#include "data-fd-util.h"
#include "fd-util.h"
#include "fs-util.h"
#include "io-util.h"
#include "memfd-util.h"
#include "missing_mman.h"
#include "missing_syscall.h"
#include "tmpfile-util.h"
/* When the data is smaller or equal to 64K, try to place the copy in a memfd/pipe */
#define DATA_FD_MEMORY_LIMIT (64U*1024U)
/* If memfd/pipe didn't work out, then let's use a file in /tmp up to a size of 1M. If it's large than that use /var/tmp instead. */
#define DATA_FD_TMP_LIMIT (1024U*1024U)
int acquire_data_fd(const void *data, size_t size, unsigned flags) {
_cleanup_close_pair_ int pipefds[2] = PIPE_EBADF;
_cleanup_close_ int fd = -EBADF;
int isz = 0, r;
ssize_t n;
assert(data || size == 0);
/* Acquire a read-only file descriptor that when read from returns the specified data. This is much more
* complex than I wish it was. But here's why:
*
* a) First we try to use memfds. They are the best option, as we can seal them nicely to make them
* read-only. Unfortunately they require kernel 3.17, and – at the time of writing – we still support 3.14.
*
* b) Then, we try classic pipes. They are the second best options, as we can close the writing side, retaining
* a nicely read-only fd in the reading side. However, they are by default quite small, and unprivileged
* clients can only bump their size to a system-wide limit, which might be quite low.
*
* c) Then, we try an O_TMPFILE file in /dev/shm (that dir is the only suitable one known to exist from
* earliest boot on). To make it read-only we open the fd a second time with O_RDONLY via
* /proc/self/<fd>. Unfortunately O_TMPFILE is not available on older kernels on tmpfs.
*
* d) Finally, we try creating a regular file in /dev/shm, which we then delete.
*
* It sucks a bit that depending on the situation we return very different objects here, but that's Linux I
* figure. */
if (size == 0 && ((flags & ACQUIRE_NO_DEV_NULL) == 0))
/* As a special case, return /dev/null if we have been called for an empty data block */
return RET_NERRNO(open("/dev/null", O_RDONLY|O_CLOEXEC|O_NOCTTY));
if ((flags & ACQUIRE_NO_MEMFD) == 0) {
fd = memfd_new_and_seal("data-fd", data, size);
if (fd < 0) {
if (ERRNO_IS_NOT_SUPPORTED(fd))
goto try_pipe;
return fd;
}
return TAKE_FD(fd);
}
try_pipe:
if ((flags & ACQUIRE_NO_PIPE) == 0) {
if (pipe2(pipefds, O_CLOEXEC|O_NONBLOCK) < 0)
return -errno;
isz = fcntl(pipefds[1], F_GETPIPE_SZ, 0);
if (isz < 0)
return -errno;
if ((size_t) isz < size) {
isz = (int) size;
if (isz < 0 || (size_t) isz != size)
return -E2BIG;
/* Try to bump the pipe size */
(void) fcntl(pipefds[1], F_SETPIPE_SZ, isz);
/* See if that worked */
isz = fcntl(pipefds[1], F_GETPIPE_SZ, 0);
if (isz < 0)
return -errno;
if ((size_t) isz < size)
goto try_dev_shm;
}
n = write(pipefds[1], data, size);
if (n < 0)
return -errno;
if ((size_t) n != size)
return -EIO;
(void) fd_nonblock(pipefds[0], false);
return TAKE_FD(pipefds[0]);
}
try_dev_shm:
if ((flags & ACQUIRE_NO_TMPFILE) == 0) {
fd = open("/dev/shm", O_RDWR|O_TMPFILE|O_CLOEXEC, 0500);
if (fd < 0)
goto try_dev_shm_without_o_tmpfile;
n = write(fd, data, size);
if (n < 0)
return -errno;
if ((size_t) n != size)
return -EIO;
/* Let's reopen the thing, in order to get an O_RDONLY fd for the original O_RDWR one */
return fd_reopen(fd, O_RDONLY|O_CLOEXEC);
}
try_dev_shm_without_o_tmpfile:
if ((flags & ACQUIRE_NO_REGULAR) == 0) {
char pattern[] = "/dev/shm/data-fd-XXXXXX";
fd = mkostemp_safe(pattern);
if (fd < 0)
return fd;
n = write(fd, data, size);
if (n < 0) {
r = -errno;
goto unlink_and_return;
}
if ((size_t) n != size) {
r = -EIO;
goto unlink_and_return;
}
/* Let's reopen the thing, in order to get an O_RDONLY fd for the original O_RDWR one */
r = fd_reopen(fd, O_RDONLY|O_CLOEXEC);
unlink_and_return:
(void) unlink(pattern);
return r;
}
return -EOPNOTSUPP;
}
int copy_data_fd(int fd) {
_cleanup_close_ int copy_fd = -EBADF, tmp_fd = -EBADF;
_cleanup_free_ void *remains = NULL;
size_t remains_size = 0;
const char *td;
struct stat st;
int r;
/* Creates a 'data' fd from the specified source fd, containing all the same data in a read-only fashion, but
* independent of it (i.e. the source fd can be closed and unmounted after this call succeeded). Tries to be
* somewhat smart about where to place the data. In the best case uses a memfd(). If memfd() are not supported
* uses a pipe instead. For larger data will use an unlinked file in /tmp, and for even larger data one in
* /var/tmp. */
if (fstat(fd, &st) < 0)
return -errno;
/* For now, let's only accept regular files, sockets, pipes and char devices */
if (S_ISDIR(st.st_mode))
return -EISDIR;
if (S_ISLNK(st.st_mode))
return -ELOOP;
if (!S_ISREG(st.st_mode) && !S_ISSOCK(st.st_mode) && !S_ISFIFO(st.st_mode) && !S_ISCHR(st.st_mode))
return -EBADFD;
/* If we have reason to believe the data is bounded in size, then let's use memfds or pipes as backing fd. Note
* that we use the reported regular file size only as a hint, given that there are plenty special files in
* /proc and /sys which report a zero file size but can be read from. */
if (!S_ISREG(st.st_mode) || st.st_size < DATA_FD_MEMORY_LIMIT) {
/* Try a memfd first */
copy_fd = memfd_new("data-fd");
if (copy_fd >= 0) {
off_t f;
r = copy_bytes(fd, copy_fd, DATA_FD_MEMORY_LIMIT, 0);
if (r < 0)
return r;
f = lseek(copy_fd, 0, SEEK_SET);
if (f != 0)
return -errno;
if (r == 0) {
/* Did it fit into the limit? If so, we are done. */
r = memfd_set_sealed(copy_fd);
if (r < 0)
return r;
return TAKE_FD(copy_fd);
}
/* Hmm, pity, this didn't fit. Let's fall back to /tmp then, see below */
} else {
_cleanup_close_pair_ int pipefds[2] = PIPE_EBADF;
int isz;
/* If memfds aren't available, use a pipe. Set O_NONBLOCK so that we will get EAGAIN rather
* then block indefinitely when we hit the pipe size limit */
if (pipe2(pipefds, O_CLOEXEC|O_NONBLOCK) < 0)
return -errno;
isz = fcntl(pipefds[1], F_GETPIPE_SZ, 0);
if (isz < 0)
return -errno;
/* Try to enlarge the pipe size if necessary */
if ((size_t) isz < DATA_FD_MEMORY_LIMIT) {
(void) fcntl(pipefds[1], F_SETPIPE_SZ, DATA_FD_MEMORY_LIMIT);
isz = fcntl(pipefds[1], F_GETPIPE_SZ, 0);
if (isz < 0)
return -errno;
}
if ((size_t) isz >= DATA_FD_MEMORY_LIMIT) {
r = copy_bytes_full(fd, pipefds[1], DATA_FD_MEMORY_LIMIT, 0, &remains, &remains_size, NULL, NULL);
if (r < 0 && r != -EAGAIN)
return r; /* If we get EAGAIN it could be because of the source or because of
* the destination fd, we can't know, as sendfile() and friends won't
* tell us. Hence, treat this as reason to fall back, just to be
* sure. */
if (r == 0) {
/* Everything fit in, yay! */
(void) fd_nonblock(pipefds[0], false);
return TAKE_FD(pipefds[0]);
}
/* Things didn't fit in. But we read data into the pipe, let's remember that, so that
* when writing the new file we incorporate this first. */
copy_fd = TAKE_FD(pipefds[0]);
}
}
}
/* If we have reason to believe this will fit fine in /tmp, then use that as first fallback. */
if ((!S_ISREG(st.st_mode) || st.st_size < DATA_FD_TMP_LIMIT) &&
(DATA_FD_MEMORY_LIMIT + remains_size) < DATA_FD_TMP_LIMIT) {
off_t f;
tmp_fd = open_tmpfile_unlinkable(NULL /* NULL as directory means /tmp */, O_RDWR|O_CLOEXEC);
if (tmp_fd < 0)
return tmp_fd;
if (copy_fd >= 0) {
/* If we tried a memfd/pipe first and it ended up being too large, then copy this into the
* temporary file first. */
r = copy_bytes(copy_fd, tmp_fd, UINT64_MAX, 0);
if (r < 0)
return r;
assert(r == 0);
}
if (remains_size > 0) {
/* If there were remaining bytes (i.e. read into memory, but not written out yet) from the
* failed copy operation, let's flush them out next. */
r = loop_write(tmp_fd, remains, remains_size, false);
if (r < 0)
return r;
}
r = copy_bytes(fd, tmp_fd, DATA_FD_TMP_LIMIT - DATA_FD_MEMORY_LIMIT - remains_size, COPY_REFLINK);
if (r < 0)
return r;
if (r == 0)
goto finish; /* Yay, it fit in */
/* It didn't fit in. Let's not forget to use what we already used */
f = lseek(tmp_fd, 0, SEEK_SET);
if (f != 0)
return -errno;
close_and_replace(copy_fd, tmp_fd);
remains = mfree(remains);
remains_size = 0;
}
/* As last fallback use /var/tmp */
r = var_tmp_dir(&td);
if (r < 0)
return r;
tmp_fd = open_tmpfile_unlinkable(td, O_RDWR|O_CLOEXEC);
if (tmp_fd < 0)
return tmp_fd;
if (copy_fd >= 0) {
/* If we tried a memfd/pipe first, or a file in /tmp, and it ended up being too large, than copy this
* into the temporary file first. */
r = copy_bytes(copy_fd, tmp_fd, UINT64_MAX, COPY_REFLINK);
if (r < 0)
return r;
assert(r == 0);
}
if (remains_size > 0) {
/* Then, copy in any read but not yet written bytes. */
r = loop_write(tmp_fd, remains, remains_size, false);
if (r < 0)
return r;
}
/* Copy in the rest */
r = copy_bytes(fd, tmp_fd, UINT64_MAX, COPY_REFLINK);
if (r < 0)
return r;
assert(r == 0);
finish:
/* Now convert the O_RDWR file descriptor into an O_RDONLY one (and as side effect seek to the beginning of the
* file again */
return fd_reopen(tmp_fd, O_RDONLY|O_CLOEXEC);
}
int memfd_clone_fd(int fd, const char *name, int mode) {
_cleanup_close_ int mfd = -EBADF;
struct stat st;
bool ro, exec;
int r;
/* Creates a clone of a regular file in a memfd. Unlike copy_data_fd() this returns strictly a memfd
* (and if it can't it will fail). Thus the resulting fd is seekable, and definitely reports as
* S_ISREG. */
assert(fd >= 0);
assert(name);
assert(IN_SET(mode & O_ACCMODE, O_RDONLY, O_RDWR));
assert((mode & ~(O_RDONLY|O_RDWR|O_CLOEXEC)) == 0);
if (fstat(fd, &st) < 0)
return -errno;
ro = (mode & O_ACCMODE) == O_RDONLY;
exec = st.st_mode & 0111;
mfd = memfd_create_wrapper(name,
((FLAGS_SET(mode, O_CLOEXEC) || ro) ? MFD_CLOEXEC : 0) |
(ro ? MFD_ALLOW_SEALING : 0) |
(exec ? MFD_EXEC : MFD_NOEXEC_SEAL));
if (mfd < 0)
return mfd;
r = copy_bytes(fd, mfd, UINT64_MAX, COPY_REFLINK);
if (r < 0)
return r;
if (ro) {
_cleanup_close_ int rfd = -EBADF;
r = memfd_set_sealed(mfd);
if (r < 0)
return r;
rfd = fd_reopen(mfd, mode);
if (rfd < 0)
return rfd;
return TAKE_FD(rfd);
}
off_t f = lseek(mfd, 0, SEEK_SET);
if (f < 0)
return -errno;
return TAKE_FD(mfd);
}
| 15,092 | 37.502551 | 132 |
c
|
null |
systemd-main/src/shared/dev-setup.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include "alloc-util.h"
#include "dev-setup.h"
#include "label-util.h"
#include "log.h"
#include "mkdir-label.h"
#include "nulstr-util.h"
#include "path-util.h"
#include "umask-util.h"
#include "user-util.h"
int dev_setup(const char *prefix, uid_t uid, gid_t gid) {
static const char symlinks[] =
"-/proc/kcore\0" "/dev/core\0"
"/proc/self/fd\0" "/dev/fd\0"
"/proc/self/fd/0\0" "/dev/stdin\0"
"/proc/self/fd/1\0" "/dev/stdout\0"
"/proc/self/fd/2\0" "/dev/stderr\0";
int r;
NULSTR_FOREACH_PAIR(j, k, symlinks) {
_cleanup_free_ char *link_name = NULL;
const char *n;
if (j[0] == '-') {
j++;
if (access(j, F_OK) < 0)
continue;
}
if (prefix) {
link_name = path_join(prefix, k);
if (!link_name)
return -ENOMEM;
n = link_name;
} else
n = k;
r = symlink_label(j, n);
if (r < 0)
log_debug_errno(r, "Failed to symlink %s to %s: %m", j, n);
if (uid != UID_INVALID || gid != GID_INVALID)
if (lchown(n, uid, gid) < 0)
log_debug_errno(errno, "Failed to chown %s: %m", n);
}
return 0;
}
int make_inaccessible_nodes(
const char *parent_dir,
uid_t uid,
gid_t gid) {
static const struct {
const char *name;
mode_t mode;
} table[] = {
{ "inaccessible", S_IFDIR | 0755 },
{ "inaccessible/reg", S_IFREG | 0000 },
{ "inaccessible/dir", S_IFDIR | 0000 },
{ "inaccessible/fifo", S_IFIFO | 0000 },
{ "inaccessible/sock", S_IFSOCK | 0000 },
/* The following two are likely to fail if we lack the privs for it (for example in an userns
* environment, if CAP_SYS_MKNOD is missing, or if a device node policy prohibits creation of
* device nodes with a major/minor of 0). But that's entirely fine. Consumers of these files
* should implement falling back to use a different node then, for example
* <root>/inaccessible/sock, which is close enough in behaviour and semantics for most uses.
*/
{ "inaccessible/chr", S_IFCHR | 0000 },
{ "inaccessible/blk", S_IFBLK | 0000 },
};
int r;
if (!parent_dir)
parent_dir = "/run/systemd";
BLOCK_WITH_UMASK(0000);
/* Set up inaccessible (and empty) file nodes of all types. This are used to as mount sources for over-mounting
* ("masking") file nodes that shall become inaccessible and empty for specific containers or services. We try
* to lock down these nodes as much as we can, but otherwise try to match them as closely as possible with the
* underlying file, i.e. in the best case we offer the same node type as the underlying node. */
for (size_t i = 0; i < ELEMENTSOF(table); i++) {
_cleanup_free_ char *path = NULL;
path = path_join(parent_dir, table[i].name);
if (!path)
return log_oom();
if (S_ISDIR(table[i].mode))
r = mkdir_label(path, table[i].mode & 07777);
else
r = mknod_label(path, table[i].mode, makedev(0, 0));
if (r < 0) {
log_debug_errno(r, "Failed to create '%s', ignoring: %m", path);
continue;
}
if (uid != UID_INVALID || gid != GID_INVALID) {
if (lchown(path, uid, gid) < 0)
log_debug_errno(errno, "Failed to chown '%s': %m", path);
}
}
return 0;
}
| 4,330 | 35.091667 | 119 |
c
|
null |
systemd-main/src/shared/device-nodes.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdio.h>
#include <string.h>
#include <sys/stat.h>
#include "device-nodes.h"
#include "path-util.h"
#include "string-util.h"
#include "utf8.h"
int allow_listed_char_for_devnode(char c, const char *additional) {
return
ascii_isdigit(c) ||
ascii_isalpha(c) ||
strchr("#+-.:=@_", c) ||
(additional && strchr(additional, c));
}
int encode_devnode_name(const char *str, char *str_enc, size_t len) {
size_t i, j;
if (!str || !str_enc)
return -EINVAL;
for (i = 0, j = 0; str[i] != '\0'; i++) {
int seqlen;
seqlen = utf8_encoded_valid_unichar(str + i, SIZE_MAX);
if (seqlen > 1) {
if (len-j < (size_t) seqlen)
return -EINVAL;
memcpy(&str_enc[j], &str[i], seqlen);
j += seqlen;
i += (seqlen-1);
} else if (str[i] == '\\' || !allow_listed_char_for_devnode(str[i], NULL)) {
if (len-j < 4)
return -EINVAL;
sprintf(&str_enc[j], "\\x%02x", (unsigned char) str[i]);
j += 4;
} else {
if (len-j < 1)
return -EINVAL;
str_enc[j] = str[i];
j++;
}
}
if (len-j < 1)
return -EINVAL;
str_enc[j] = '\0';
return 0;
}
int devnode_same(const char *a, const char *b) {
struct stat sa, sb;
assert(a);
assert(b);
if (!valid_device_node_path(a) || !valid_device_node_path(b))
return -EINVAL;
if (stat(a, &sa) < 0)
return -errno;
if (stat(b, &sb) < 0)
return -errno;
if (!S_ISBLK(sa.st_mode) && !S_ISCHR(sa.st_mode))
return -ENODEV;
if (!S_ISBLK(sb.st_mode) && !S_ISCHR(sb.st_mode))
return -ENODEV;
if (((sa.st_mode ^ sb.st_mode) & S_IFMT) != 0) /* both inode same device node type? */
return false;
return sa.st_rdev == sb.st_rdev;
}
| 2,371 | 25.954545 | 94 |
c
|
null |
systemd-main/src/shared/devnode-acl.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include "sd-device.h"
#include "acl-util.h"
#include "alloc-util.h"
#include "device-util.h"
#include "devnode-acl.h"
#include "dirent-util.h"
#include "fd-util.h"
#include "format-util.h"
#include "fs-util.h"
#include "glyph-util.h"
#include "set.h"
#include "string-util.h"
static int flush_acl(acl_t acl) {
acl_entry_t i;
int found;
bool changed = false;
assert(acl);
for (found = acl_get_entry(acl, ACL_FIRST_ENTRY, &i);
found > 0;
found = acl_get_entry(acl, ACL_NEXT_ENTRY, &i)) {
acl_tag_t tag;
if (acl_get_tag_type(i, &tag) < 0)
return -errno;
if (tag != ACL_USER)
continue;
if (acl_delete_entry(acl, i) < 0)
return -errno;
changed = true;
}
if (found < 0)
return -errno;
return changed;
}
int devnode_acl(const char *path,
bool flush,
bool del, uid_t old_uid,
bool add, uid_t new_uid) {
_cleanup_(acl_freep) acl_t acl = NULL;
int r;
bool changed = false;
assert(path);
acl = acl_get_file(path, ACL_TYPE_ACCESS);
if (!acl)
return -errno;
if (flush) {
r = flush_acl(acl);
if (r < 0)
return r;
if (r > 0)
changed = true;
} else if (del && old_uid > 0) {
acl_entry_t entry;
r = acl_find_uid(acl, old_uid, &entry);
if (r < 0)
return r;
if (r > 0) {
if (acl_delete_entry(acl, entry) < 0)
return -errno;
changed = true;
}
}
if (add && new_uid > 0) {
acl_entry_t entry;
acl_permset_t permset;
int rd, wt;
r = acl_find_uid(acl, new_uid, &entry);
if (r < 0)
return r;
if (r == 0) {
if (acl_create_entry(&acl, &entry) < 0)
return -errno;
if (acl_set_tag_type(entry, ACL_USER) < 0 ||
acl_set_qualifier(entry, &new_uid) < 0)
return -errno;
}
if (acl_get_permset(entry, &permset) < 0)
return -errno;
rd = acl_get_perm(permset, ACL_READ);
if (rd < 0)
return -errno;
wt = acl_get_perm(permset, ACL_WRITE);
if (wt < 0)
return -errno;
if (!rd || !wt) {
if (acl_add_perm(permset, ACL_READ|ACL_WRITE) < 0)
return -errno;
changed = true;
}
}
if (!changed)
return 0;
if (acl_calc_mask(&acl) < 0)
return -errno;
if (acl_set_file(path, ACL_TYPE_ACCESS, acl) < 0)
return -errno;
return 0;
}
int devnode_acl_all(const char *seat,
bool flush,
bool del, uid_t old_uid,
bool add, uid_t new_uid) {
_cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
_cleanup_set_free_ Set *nodes = NULL;
_cleanup_closedir_ DIR *dir = NULL;
char *n;
int r;
r = sd_device_enumerator_new(&e);
if (r < 0)
return r;
if (isempty(seat))
seat = "seat0";
/* We can only match by one tag in libudev. We choose
* "uaccess" for that. If we could match for two tags here we
* could add the seat name as second match tag, but this would
* be hardly optimizable in libudev, and hence checking the
* second tag manually in our loop is a good solution. */
r = sd_device_enumerator_add_match_tag(e, "uaccess");
if (r < 0)
return r;
FOREACH_DEVICE(e, d) {
const char *node, *sn;
/* Make sure the tag is still in place */
if (sd_device_has_current_tag(d, "uaccess") <= 0)
continue;
if (sd_device_get_property_value(d, "ID_SEAT", &sn) < 0 || isempty(sn))
sn = "seat0";
if (!streq(seat, sn))
continue;
/* In case people mistag devices with nodes, we need to ignore this */
if (sd_device_get_devname(d, &node) < 0)
continue;
log_device_debug(d, "Found udev node %s for seat %s", node, seat);
r = set_put_strdup_full(&nodes, &path_hash_ops_free, node);
if (r < 0)
return r;
}
/* udev exports "dead" device nodes to allow module on-demand loading,
* these devices are not known to the kernel at this moment */
dir = opendir("/run/udev/static_node-tags/uaccess");
if (dir) {
FOREACH_DIRENT(de, dir, return -errno) {
r = readlinkat_malloc(dirfd(dir), de->d_name, &n);
if (r == -ENOENT)
continue;
if (r < 0) {
log_debug_errno(r,
"Unable to read symlink '/run/udev/static_node-tags/uaccess/%s', ignoring: %m",
de->d_name);
continue;
}
log_debug("Found static node %s for seat %s", n, seat);
r = set_ensure_consume(&nodes, &path_hash_ops_free, n);
if (r < 0)
return r;
}
}
r = 0;
SET_FOREACH(n, nodes) {
int k;
log_debug("Changing ACLs at %s for seat %s (uid "UID_FMT"%s"UID_FMT"%s%s)",
n, seat, old_uid, special_glyph(SPECIAL_GLYPH_ARROW_RIGHT), new_uid,
del ? " del" : "", add ? " add" : "");
k = devnode_acl(n, flush, del, old_uid, add, new_uid);
if (k == -ENOENT)
log_debug("Device %s disappeared while setting ACLs", n);
else if (k < 0 && r == 0)
r = k;
}
return r;
}
| 6,862 | 29.23348 | 127 |
c
|
null |
systemd-main/src/shared/devnode-acl.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <sys/types.h>
#if HAVE_ACL
int devnode_acl(const char *path,
bool flush,
bool del, uid_t old_uid,
bool add, uid_t new_uid);
int devnode_acl_all(const char *seat,
bool flush,
bool del, uid_t old_uid,
bool add, uid_t new_uid);
#else
static inline int devnode_acl(const char *path,
bool flush,
bool del, uid_t old_uid,
bool add, uid_t new_uid) {
return 0;
}
static inline int devnode_acl_all(const char *seat,
bool flush,
bool del, uid_t old_uid,
bool add, uid_t new_uid) {
return 0;
}
#endif
| 863 | 23.685714 | 60 |
h
|
null |
systemd-main/src/shared/discover-image.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "sd-id128.h"
#include "hashmap.h"
#include "image-policy.h"
#include "lock-util.h"
#include "macro.h"
#include "os-util.h"
#include "path-util.h"
#include "string-util.h"
#include "time-util.h"
typedef enum ImageType {
IMAGE_DIRECTORY,
IMAGE_SUBVOLUME,
IMAGE_RAW,
IMAGE_BLOCK,
_IMAGE_TYPE_MAX,
_IMAGE_TYPE_INVALID = -EINVAL,
} ImageType;
typedef struct Image {
unsigned n_ref;
ImageType type;
ImageClass class;
char *name;
char *path;
bool read_only;
usec_t crtime;
usec_t mtime;
uint64_t usage;
uint64_t usage_exclusive;
uint64_t limit;
uint64_t limit_exclusive;
char *hostname;
sd_id128_t machine_id;
char **machine_info;
char **os_release;
char **extension_release;
bool metadata_valid:1;
bool discoverable:1; /* true if we know for sure that image_find() would find the image given just the short name */
void *userdata;
} Image;
Image *image_unref(Image *i);
Image *image_ref(Image *i);
DEFINE_TRIVIAL_CLEANUP_FUNC(Image*, image_unref);
int image_find(ImageClass class, const char *root, const char *name, Image **ret);
int image_from_path(const char *path, Image **ret);
int image_find_harder(ImageClass class, const char *root, const char *name_or_path, Image **ret);
int image_discover(ImageClass class, const char *root, Hashmap *map);
int image_remove(Image *i);
int image_rename(Image *i, const char *new_name);
int image_clone(Image *i, const char *new_name, bool read_only);
int image_read_only(Image *i, bool b);
const char* image_type_to_string(ImageType t) _const_;
ImageType image_type_from_string(const char *s) _pure_;
int image_path_lock(const char *path, int operation, LockFile *global, LockFile *local);
int image_name_lock(const char *name, int operation, LockFile *ret);
int image_set_limit(Image *i, uint64_t referenced_max);
int image_read_metadata(Image *i, const ImagePolicy *image_policy);
bool image_in_search_path(ImageClass class, const char *root, const char *image);
static inline bool IMAGE_IS_HIDDEN(const struct Image *i) {
assert(i);
return i->name && i->name[0] == '.';
}
static inline bool IMAGE_IS_VENDOR(const struct Image *i) {
assert(i);
return i->path && path_startswith(i->path, "/usr");
}
static inline bool IMAGE_IS_HOST(const struct Image *i) {
assert(i);
if (i->name && streq(i->name, ".host"))
return true;
if (i->path && path_equal(i->path, "/"))
return true;
return false;
}
extern const struct hash_ops image_hash_ops;
| 2,820 | 25.12037 | 125 |
h
|
null |
systemd-main/src/shared/dlfcn-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "dlfcn-util.h"
static int dlsym_many_or_warnv(void *dl, int log_level, va_list ap) {
void (**fn)(void);
/* Tries to resolve a bunch of function symbols, and logs an error about if it cannot resolve one of
* them. Note that this function possibly modifies the supplied function pointers if the whole
* operation fails. */
while ((fn = va_arg(ap, typeof(fn)))) {
void (*tfn)(void);
const char *symbol;
symbol = va_arg(ap, typeof(symbol));
tfn = (typeof(tfn)) dlsym(dl, symbol);
if (!tfn)
return log_full_errno(log_level,
SYNTHETIC_ERRNO(ELIBBAD),
"Can't find symbol %s: %s", symbol, dlerror());
*fn = tfn;
}
return 0;
}
int dlsym_many_or_warn_sentinel(void *dl, int log_level, ...) {
va_list ap;
int r;
va_start(ap, log_level);
r = dlsym_many_or_warnv(dl, log_level, ap);
va_end(ap);
return r;
}
int dlopen_many_sym_or_warn_sentinel(void **dlp, const char *filename, int log_level, ...) {
_cleanup_(dlclosep) void *dl = NULL;
int r;
if (*dlp)
return 0; /* Already loaded */
dl = dlopen(filename, RTLD_LAZY);
if (!dl)
return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"%s is not installed: %s", filename, dlerror());
va_list ap;
va_start(ap, log_level);
r = dlsym_many_or_warnv(dl, log_level, ap);
va_end(ap);
if (r < 0)
return r;
/* Note that we never release the reference here, because there's no real reason to. After all this
* was traditionally a regular shared library dependency which lives forever too. */
*dlp = TAKE_PTR(dl);
return 1;
}
| 2,039 | 30.384615 | 108 |
c
|
null |
systemd-main/src/shared/dlfcn-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <dlfcn.h>
#include "macro.h"
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(void*, dlclose, NULL);
int dlsym_many_or_warn_sentinel(void *dl, int log_level, ...) _sentinel_;
int dlopen_many_sym_or_warn_sentinel(void **dlp, const char *filename, int log_level, ...) _sentinel_;
#define dlsym_many_or_warn(dl, log_level, ...) \
dlsym_many_or_warn_sentinel(dl, log_level, __VA_ARGS__, NULL)
#define dlopen_many_sym_or_warn(dlp, filename, log_level, ...) \
dlopen_many_sym_or_warn_sentinel(dlp, filename, log_level, __VA_ARGS__, NULL)
/* Macro useful for putting together variable/symbol name pairs when calling dlsym_many_or_warn(). Assumes
* that each library symbol to resolve will be placed in a variable with the "sym_" prefix, i.e. a symbol
* "foobar" is loaded into a variable "sym_foobar". */
#define DLSYM_ARG(arg) \
({ assert_cc(__builtin_types_compatible_p(typeof(sym_##arg), typeof(&arg))); &sym_##arg; }), STRINGIFY(arg)
/* libbpf is a bit confused about type-safety and API compatibility. Provide a macro that can tape over that mess. Sad. */
#define DLSYM_ARG_FORCE(arg) \
&sym_##arg, STRINGIFY(arg)
static inline void *safe_dlclose(void *p) {
if (!p)
return NULL;
assert_se(dlclose(p) == 0);
return NULL;
}
| 1,358 | 37.828571 | 122 |
h
|
null |
systemd-main/src/shared/dm-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <linux/dm-ioctl.h>
#include <sys/ioctl.h>
#include "dm-util.h"
#include "fd-util.h"
#include "string-util.h"
int dm_deferred_remove_cancel(const char *name) {
_cleanup_close_ int fd = -EBADF;
struct message {
struct dm_ioctl dm_ioctl;
struct dm_target_msg dm_target_msg;
char msg_text[STRLEN("@cancel_deferred_remove") + 1];
} _packed_ message = {
.dm_ioctl = {
.version = {
DM_VERSION_MAJOR,
DM_VERSION_MINOR,
DM_VERSION_PATCHLEVEL
},
.data_size = sizeof(struct message),
.data_start = sizeof(struct dm_ioctl),
},
.msg_text = "@cancel_deferred_remove",
};
assert(name);
if (strlen(name) >= sizeof(message.dm_ioctl.name))
return -ENODEV; /* A device with a name longer than this cannot possibly exist */
strncpy_exact(message.dm_ioctl.name, name, sizeof(message.dm_ioctl.name));
fd = open("/dev/mapper/control", O_RDWR|O_CLOEXEC);
if (fd < 0)
return -errno;
if (ioctl(fd, DM_TARGET_MSG, &message))
return -errno;
return 0;
}
| 1,435 | 30.217391 | 97 |
c
|
null |
systemd-main/src/shared/dns-domain.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include <stdbool.h>
#include <stddef.h>
#include <stdint.h>
#include "dns-def.h"
#include "hashmap.h"
#include "in-addr-util.h"
typedef enum DNSLabelFlags {
DNS_LABEL_LDH = 1 << 0, /* Follow the "LDH" rule — only letters, digits, and internal hyphens. */
DNS_LABEL_NO_ESCAPES = 1 << 1, /* Do not treat backslashes specially */
DNS_LABEL_LEAVE_TRAILING_DOT = 1 << 2, /* Leave trailing dot in place */
} DNSLabelFlags;
int dns_label_unescape(const char **name, char *dest, size_t sz, DNSLabelFlags flags);
int dns_label_unescape_suffix(const char *name, const char **label_end, char *dest, size_t sz);
int dns_label_escape(const char *p, size_t l, char *dest, size_t sz);
int dns_label_escape_new(const char *p, size_t l, char **ret);
static inline int dns_name_parent(const char **name) {
return dns_label_unescape(name, NULL, DNS_LABEL_MAX, 0);
}
#if HAVE_LIBIDN
int dns_label_apply_idna(const char *encoded, size_t encoded_size, char *decoded, size_t decoded_max);
int dns_label_undo_idna(const char *encoded, size_t encoded_size, char *decoded, size_t decoded_max);
#endif
int dns_name_concat(const char *a, const char *b, DNSLabelFlags flags, char **ret);
static inline int dns_name_normalize(const char *s, DNSLabelFlags flags, char **ret) {
/* dns_name_concat() normalizes as a side-effect */
return dns_name_concat(s, NULL, flags, ret);
}
static inline int dns_name_is_valid(const char *s) {
int r;
/* dns_name_concat() verifies as a side effect */
r = dns_name_concat(s, NULL, 0, NULL);
if (r == -EINVAL)
return 0;
if (r < 0)
return r;
return 1;
}
static inline int dns_name_is_valid_ldh(const char *s) {
int r;
r = dns_name_concat(s, NULL, DNS_LABEL_LDH|DNS_LABEL_NO_ESCAPES, NULL);
if (r == -EINVAL)
return 0;
if (r < 0)
return r;
return 1;
}
void dns_name_hash_func(const char *s, struct siphash *state);
int dns_name_compare_func(const char *a, const char *b);
extern const struct hash_ops dns_name_hash_ops;
extern const struct hash_ops dns_name_hash_ops_free;
int dns_name_between(const char *a, const char *b, const char *c);
int dns_name_equal(const char *x, const char *y);
int dns_name_endswith(const char *name, const char *suffix);
int dns_name_startswith(const char *name, const char *prefix);
int dns_name_change_suffix(const char *name, const char *old_suffix, const char *new_suffix, char **ret);
int dns_name_reverse(int family, const union in_addr_union *a, char **ret);
int dns_name_address(const char *p, int *family, union in_addr_union *a);
bool dns_name_is_root(const char *name);
bool dns_name_is_single_label(const char *name);
int dns_name_to_wire_format(const char *domain, uint8_t *buffer, size_t len, bool canonical);
bool dns_srv_type_is_valid(const char *name);
bool dnssd_srv_type_is_valid(const char *name);
bool dns_service_name_is_valid(const char *name);
int dns_service_join(const char *name, const char *type, const char *domain, char **ret);
int dns_service_split(const char *joined, char **ret_name, char **ret_type, char **ret_domain);
int dns_name_suffix(const char *name, unsigned n_labels, const char **ret);
int dns_name_count_labels(const char *name);
int dns_name_skip(const char *a, unsigned n_labels, const char **ret);
int dns_name_equal_skip(const char *a, unsigned n_labels, const char *b);
int dns_name_common_suffix(const char *a, const char *b, const char **ret);
int dns_name_apply_idna(const char *name, char **ret);
int dns_name_is_valid_or_address(const char *name);
int dns_name_dot_suffixed(const char *name);
bool dns_name_dont_resolve(const char *name);
| 3,856 | 35.733333 | 120 |
h
|
null |
systemd-main/src/shared/dropin.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include "alloc-util.h"
#include "chase.h"
#include "conf-files.h"
#include "dirent-util.h"
#include "dropin.h"
#include "escape.h"
#include "fd-util.h"
#include "fileio-label.h"
#include "hashmap.h"
#include "log.h"
#include "macro.h"
#include "mkdir.h"
#include "path-util.h"
#include "set.h"
#include "string-util.h"
#include "strv.h"
#include "unit-name.h"
int drop_in_file(const char *dir, const char *unit, unsigned level,
const char *name, char **ret_p, char **ret_q) {
char prefix[DECIMAL_STR_MAX(unsigned)];
_cleanup_free_ char *b = NULL, *p = NULL, *q = NULL;
assert(unit);
assert(name);
assert(ret_p);
assert(ret_q);
sprintf(prefix, "%u", level);
b = xescape(name, "/.");
if (!b)
return -ENOMEM;
if (!filename_is_valid(b))
return -EINVAL;
p = strjoin(dir, "/", unit, ".d");
q = strjoin(p, "/", prefix, "-", b, ".conf");
if (!p || !q)
return -ENOMEM;
*ret_p = TAKE_PTR(p);
*ret_q = TAKE_PTR(q);
return 0;
}
int write_drop_in(const char *dir, const char *unit, unsigned level,
const char *name, const char *data) {
_cleanup_free_ char *p = NULL, *q = NULL;
int r;
assert(dir);
assert(unit);
assert(name);
assert(data);
r = drop_in_file(dir, unit, level, name, &p, &q);
if (r < 0)
return r;
(void) mkdir_p(p, 0755);
return write_string_file_atomic_label(q, data);
}
int write_drop_in_format(const char *dir, const char *unit, unsigned level,
const char *name, const char *format, ...) {
_cleanup_free_ char *p = NULL;
va_list ap;
int r;
assert(dir);
assert(unit);
assert(name);
assert(format);
va_start(ap, format);
r = vasprintf(&p, format, ap);
va_end(ap);
if (r < 0)
return -ENOMEM;
return write_drop_in(dir, unit, level, name, p);
}
static int unit_file_add_dir(
const char *original_root,
const char *path,
char ***dirs) {
_cleanup_free_ char *chased = NULL;
int r;
assert(path);
/* This adds [original_root]/path to dirs, if it exists. */
r = chase(path, original_root, 0, &chased, NULL);
if (r == -ENOENT) /* Ignore -ENOENT, after all most units won't have a drop-in dir. */
return 0;
if (r == -ENAMETOOLONG) {
/* Also, ignore -ENAMETOOLONG but log about it. After all, users are not even able to create the
* drop-in dir in such case. This mostly happens for device units with an overly long /sys path. */
log_debug_errno(r, "Path '%s' too long, couldn't canonicalize, ignoring.", path);
return 0;
}
if (r < 0)
return log_warning_errno(r, "Failed to canonicalize path '%s': %m", path);
if (strv_consume(dirs, TAKE_PTR(chased)) < 0)
return log_oom();
return 0;
}
static int unit_file_find_dirs(
const char *original_root,
Set *unit_path_cache,
const char *unit_path,
const char *name,
const char *suffix,
char ***dirs) {
_cleanup_free_ char *prefix = NULL, *instance = NULL, *built = NULL;
bool is_instance, chopped;
const char *dash;
UnitType type;
char *path;
size_t n;
int r;
assert(unit_path);
assert(name);
assert(suffix);
path = strjoina(unit_path, "/", name, suffix);
if (!unit_path_cache || set_get(unit_path_cache, path)) {
r = unit_file_add_dir(original_root, path, dirs);
if (r < 0)
return r;
}
is_instance = unit_name_is_valid(name, UNIT_NAME_INSTANCE);
if (is_instance) { /* Also try the template dir */
_cleanup_free_ char *template = NULL;
r = unit_name_template(name, &template);
if (r < 0)
return log_error_errno(r, "Failed to generate template from unit name: %m");
r = unit_file_find_dirs(original_root, unit_path_cache, unit_path, template, suffix, dirs);
if (r < 0)
return r;
}
/* Return early for top level drop-ins. */
if (unit_type_from_string(name) >= 0)
return 0;
/* Let's see if there's a "-" prefix for this unit name. If so, let's invoke ourselves for it. This will then
* recursively do the same for all our prefixes. i.e. this means given "foo-bar-waldo.service" we'll also
* search "foo-bar-.service" and "foo-.service".
*
* Note the order in which we do it: we traverse up adding drop-ins on each step. This means the more specific
* drop-ins may override the more generic drop-ins, which is the intended behaviour. */
r = unit_name_to_prefix(name, &prefix);
if (r < 0)
return log_error_errno(r, "Failed to derive unit name prefix from unit name: %m");
chopped = false;
for (;;) {
dash = strrchr(prefix, '-');
if (!dash) /* No dash? if so we are done */
return 0;
n = (size_t) (dash - prefix);
if (n == 0) /* Leading dash? If so, we are done */
return 0;
if (prefix[n+1] != 0 || chopped) {
prefix[n+1] = 0;
break;
}
/* Trailing dash? If so, chop it off and try again, but not more than once. */
prefix[n] = 0;
chopped = true;
}
if (!unit_prefix_is_valid(prefix))
return 0;
type = unit_name_to_type(name);
if (type < 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Failed to derive unit type from unit name: %s",
name);
if (is_instance) {
r = unit_name_to_instance(name, &instance);
if (r < 0)
return log_error_errno(r, "Failed to derive unit name instance from unit name: %m");
}
r = unit_name_build_from_type(prefix, instance, type, &built);
if (r < 0)
return log_error_errno(r, "Failed to build prefix unit name: %m");
return unit_file_find_dirs(original_root, unit_path_cache, unit_path, built, suffix, dirs);
}
int unit_file_find_dropin_paths(
const char *original_root,
char **lookup_path,
Set *unit_path_cache,
const char *dir_suffix,
const char *file_suffix,
const char *name,
const Set *aliases,
char ***ret) {
_cleanup_strv_free_ char **dirs = NULL;
const char *n;
int r;
assert(ret);
if (name)
STRV_FOREACH(p, lookup_path)
(void) unit_file_find_dirs(original_root, unit_path_cache, *p, name, dir_suffix, &dirs);
SET_FOREACH(n, aliases)
STRV_FOREACH(p, lookup_path)
(void) unit_file_find_dirs(original_root, unit_path_cache, *p, n, dir_suffix, &dirs);
/* All the names in the unit are of the same type so just grab one. */
n = name ?: (const char*) set_first(aliases);
if (n) {
UnitType type = _UNIT_TYPE_INVALID;
type = unit_name_to_type(n);
if (type < 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Failed to derive unit type from unit name: %s", n);
/* Special top level drop in for "<unit type>.<suffix>". Add this last as it's the most generic
* and should be able to be overridden by more specific drop-ins. */
STRV_FOREACH(p, lookup_path)
(void) unit_file_find_dirs(original_root,
unit_path_cache,
*p,
unit_type_to_string(type),
dir_suffix,
&dirs);
}
if (strv_isempty(dirs)) {
*ret = NULL;
return 0;
}
r = conf_files_list_strv(ret, file_suffix, NULL, 0, (const char**) dirs);
if (r < 0)
return log_warning_errno(r, "Failed to create the list of configuration files: %m");
return 1;
}
| 9,192 | 31.949821 | 118 |
c
|
null |
systemd-main/src/shared/dropin.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "hashmap.h"
#include "macro.h"
#include "set.h"
#include "unit-name.h"
int drop_in_file(const char *dir, const char *unit, unsigned level,
const char *name, char **_p, char **_q);
int write_drop_in(const char *dir, const char *unit, unsigned level,
const char *name, const char *data);
int write_drop_in_format(const char *dir, const char *unit, unsigned level,
const char *name, const char *format, ...) _printf_(5, 6);
int unit_file_find_dropin_paths(
const char *original_root,
char **lookup_path,
Set *unit_path_cache,
const char *dir_suffix,
const char *file_suffix,
const char *name,
const Set *aliases,
char ***paths);
| 890 | 32 | 83 |
h
|
null |
systemd-main/src/shared/edit-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#define DROPIN_MARKER_START "### Anything between here and the comment below will become the contents of the drop-in file"
#define DROPIN_MARKER_END "### Edits below this comment will be discarded"
typedef struct EditFile EditFile;
typedef struct EditFileContext EditFileContext;
struct EditFile {
EditFileContext *context;
char *path;
char *original_path;
char **comment_paths;
char *temp;
unsigned line;
};
struct EditFileContext {
EditFile *files;
size_t n_files;
const char *marker_start;
const char *marker_end;
bool remove_parent;
bool overwrite_with_origin; /* whether to always overwrite target with original file */
};
void edit_file_context_done(EditFileContext *context);
bool edit_files_contains(const EditFileContext *context, const char *path);
int edit_files_add(
EditFileContext *context,
const char *path,
const char *original_path,
char * const *comment_paths);
int do_edit_files_and_install(EditFileContext *context);
| 1,189 | 28.02439 | 122 |
h
|
null |
systemd-main/src/shared/efi-loader.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "efi-loader.h"
#include "env-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "stat-util.h"
#include "strv.h"
#include "tpm-pcr.h"
#include "utf8.h"
#if ENABLE_EFI
static int read_usec(const char *variable, usec_t *ret) {
_cleanup_free_ char *j = NULL;
uint64_t x = 0;
int r;
assert(variable);
assert(ret);
r = efi_get_variable_string(variable, &j);
if (r < 0)
return r;
r = safe_atou64(j, &x);
if (r < 0)
return r;
*ret = x;
return 0;
}
int efi_loader_get_boot_usec(usec_t *ret_firmware, usec_t *ret_loader) {
uint64_t x, y;
int r;
assert(ret_firmware);
assert(ret_loader);
if (!is_efi_boot())
return -EOPNOTSUPP;
r = read_usec(EFI_LOADER_VARIABLE(LoaderTimeInitUSec), &x);
if (r < 0)
return log_debug_errno(r, "Failed to read LoaderTimeInitUSec: %m");
r = read_usec(EFI_LOADER_VARIABLE(LoaderTimeExecUSec), &y);
if (r < 0)
return log_debug_errno(r, "Failed to read LoaderTimeExecUSec: %m");
if (y == 0 || y < x || y - x > USEC_PER_HOUR)
return log_debug_errno(SYNTHETIC_ERRNO(EIO),
"Bad LoaderTimeInitUSec=%"PRIu64", LoaderTimeExecUSec=%" PRIu64"; refusing.",
x, y);
*ret_firmware = x;
*ret_loader = y;
return 0;
}
int efi_loader_get_device_part_uuid(sd_id128_t *ret) {
_cleanup_free_ char *p = NULL;
int r;
unsigned parsed[16];
if (!is_efi_boot())
return -EOPNOTSUPP;
r = efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderDevicePartUUID), &p);
if (r < 0)
return r;
if (sscanf(p, SD_ID128_UUID_FORMAT_STR,
&parsed[0], &parsed[1], &parsed[2], &parsed[3],
&parsed[4], &parsed[5], &parsed[6], &parsed[7],
&parsed[8], &parsed[9], &parsed[10], &parsed[11],
&parsed[12], &parsed[13], &parsed[14], &parsed[15]) != 16)
return -EIO;
if (ret)
for (unsigned i = 0; i < ELEMENTSOF(parsed); i++)
ret->bytes[i] = parsed[i];
return 0;
}
int efi_loader_get_entries(char ***ret) {
_cleanup_free_ char16_t *entries = NULL;
_cleanup_strv_free_ char **l = NULL;
size_t size;
int r;
assert(ret);
if (!is_efi_boot())
return -EOPNOTSUPP;
r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntries), NULL, (void**) &entries, &size);
if (r < 0)
return r;
/* The variable contains a series of individually NUL terminated UTF-16 strings. */
for (size_t i = 0, start = 0;; i++) {
_cleanup_free_ char *decoded = NULL;
bool end;
/* Is this the end of the variable's data? */
end = i * sizeof(char16_t) >= size;
/* Are we in the middle of a string? (i.e. not at the end of the variable, nor at a NUL terminator?) If
* so, let's go to the next entry. */
if (!end && entries[i] != 0)
continue;
/* We reached the end of a string, let's decode it into UTF-8 */
decoded = utf16_to_utf8(entries + start, (i - start) * sizeof(char16_t));
if (!decoded)
return -ENOMEM;
if (efi_loader_entry_name_valid(decoded)) {
r = strv_consume(&l, TAKE_PTR(decoded));
if (r < 0)
return r;
} else
log_debug("Ignoring invalid loader entry '%s'.", decoded);
/* We reached the end of the variable */
if (end)
break;
/* Continue after the NUL byte */
start = i + 1;
}
*ret = TAKE_PTR(l);
return 0;
}
int efi_loader_get_features(uint64_t *ret) {
_cleanup_free_ void *v = NULL;
size_t s;
int r;
assert(ret);
if (!is_efi_boot()) {
*ret = 0;
return 0;
}
r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderFeatures), NULL, &v, &s);
if (r == -ENOENT) {
_cleanup_free_ char *info = NULL;
/* The new (v240+) LoaderFeatures variable is not supported, let's see if it's systemd-boot at all */
r = efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderInfo), &info);
if (r < 0) {
if (r != -ENOENT)
return r;
/* Variable not set, definitely means not systemd-boot */
} else if (first_word(info, "systemd-boot")) {
/* An older systemd-boot version. Let's hardcode the feature set, since it was pretty
* static in all its versions. */
*ret = EFI_LOADER_FEATURE_CONFIG_TIMEOUT |
EFI_LOADER_FEATURE_ENTRY_DEFAULT |
EFI_LOADER_FEATURE_ENTRY_ONESHOT;
return 0;
}
/* No features supported */
*ret = 0;
return 0;
}
if (r < 0)
return r;
if (s != sizeof(uint64_t))
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
"LoaderFeatures EFI variable doesn't have the right size.");
memcpy(ret, v, sizeof(uint64_t));
return 0;
}
int efi_stub_get_features(uint64_t *ret) {
_cleanup_free_ void *v = NULL;
size_t s;
int r;
assert(ret);
if (!is_efi_boot()) {
*ret = 0;
return 0;
}
r = efi_get_variable(EFI_LOADER_VARIABLE(StubFeatures), NULL, &v, &s);
if (r == -ENOENT) {
_cleanup_free_ char *info = NULL;
/* The new (v252+) StubFeatures variable is not supported, let's see if it's systemd-stub at all */
r = efi_get_variable_string(EFI_LOADER_VARIABLE(StubInfo), &info);
if (r < 0) {
if (r != -ENOENT)
return r;
/* Variable not set, definitely means not systemd-stub */
} else if (first_word(info, "systemd-stub")) {
/* An older systemd-stub version. Let's hardcode the feature set, since it was pretty
* static in all its versions. */
*ret = EFI_STUB_FEATURE_REPORT_BOOT_PARTITION;
return 0;
}
/* No features supported */
*ret = 0;
return 0;
}
if (r < 0)
return r;
if (s != sizeof(uint64_t))
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
"StubFeatures EFI variable doesn't have the right size.");
memcpy(ret, v, sizeof(uint64_t));
return 0;
}
int efi_stub_measured(int log_level) {
_cleanup_free_ char *pcr_string = NULL;
unsigned pcr_nr;
int r;
/* Checks if we are booted on a kernel with sd-stub which measured the kernel into PCR 11. Or in
* other words, if we are running on a TPM enabled UKI.
*
* Returns == 0 and > 0 depending on the result of the test. Returns -EREMOTE if we detected a stub
* being used, but it measured things into a different PCR than we are configured for in
* userspace. (i.e. we expect PCR 11 being used for this by both sd-stub and us) */
r = getenv_bool_secure("SYSTEMD_FORCE_MEASURE"); /* Give user a chance to override the variable test,
* for debugging purposes */
if (r >= 0)
return r;
if (r != -ENXIO)
log_debug_errno(r, "Failed to parse $SYSTEMD_FORCE_MEASURE, ignoring: %m");
if (!is_efi_boot())
return 0;
r = efi_get_variable_string(EFI_LOADER_VARIABLE(StubPcrKernelImage), &pcr_string);
if (r == -ENOENT)
return 0;
if (r < 0)
return log_full_errno(log_level, r,
"Failed to get StubPcrKernelImage EFI variable: %m");
r = safe_atou(pcr_string, &pcr_nr);
if (r < 0)
return log_full_errno(log_level, r,
"Failed to parse StubPcrKernelImage EFI variable: %s", pcr_string);
if (pcr_nr != TPM_PCR_INDEX_KERNEL_IMAGE)
return log_full_errno(log_level, SYNTHETIC_ERRNO(EREMOTE),
"Kernel stub measured kernel image into PCR %u, which is different than expected %u.",
pcr_nr, TPM_PCR_INDEX_KERNEL_IMAGE);
return 1;
}
int efi_loader_get_config_timeout_one_shot(usec_t *ret) {
_cleanup_free_ char *v = NULL;
static struct stat cache_stat = {};
struct stat new_stat;
static usec_t cache;
uint64_t sec;
int r;
assert(ret);
/* stat() the EFI variable, to see if the mtime changed. If it did, we need to cache again. */
if (stat(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot)), &new_stat) < 0)
return -errno;
if (stat_inode_unmodified(&new_stat, &cache_stat)) {
*ret = cache;
return 0;
}
r = efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot), &v);
if (r < 0)
return r;
r = safe_atou64(v, &sec);
if (r < 0)
return r;
if (sec > USEC_INFINITY / USEC_PER_SEC)
return -ERANGE;
cache_stat = new_stat;
*ret = cache = sec * USEC_PER_SEC; /* return in μs */
return 0;
}
int efi_loader_update_entry_one_shot_cache(char **cache, struct stat *cache_stat) {
_cleanup_free_ char *v = NULL;
struct stat new_stat;
int r;
assert(cache);
assert(cache_stat);
/* stat() the EFI variable, to see if the mtime changed. If it did we need to cache again. */
if (stat(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderEntryOneShot)), &new_stat) < 0)
return -errno;
if (stat_inode_unmodified(&new_stat, cache_stat))
return 0;
r = efi_get_variable_string(EFI_LOADER_VARIABLE(LoaderEntryOneShot), &v);
if (r < 0)
return r;
if (!efi_loader_entry_name_valid(v))
return -EINVAL;
*cache_stat = new_stat;
free_and_replace(*cache, v);
return 0;
}
#endif
bool efi_loader_entry_name_valid(const char *s) {
if (!filename_is_valid(s)) /* Make sure entry names fit in filenames */
return false;
return in_charset(s, ALPHANUMERICAL "+-_.");
}
| 11,464 | 31.571023 | 124 |
c
|
null |
systemd-main/src/shared/efi-loader.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/stat.h>
#include "efivars-fundamental.h"
#include "efivars.h"
/* Various calls that interface with EFI variables implementing https://systemd.io/BOOT_LOADER_INTERFACE */
#if ENABLE_EFI
int efi_loader_get_device_part_uuid(sd_id128_t *ret);
int efi_loader_get_boot_usec(usec_t *ret_firmware, usec_t *ret_loader);
int efi_loader_get_entries(char ***ret);
int efi_loader_get_features(uint64_t *ret);
int efi_stub_get_features(uint64_t *ret);
int efi_stub_measured(int log_level);
int efi_loader_get_config_timeout_one_shot(usec_t *ret);
int efi_loader_update_entry_one_shot_cache(char **cache, struct stat *cache_stat);
#else
static inline int efi_loader_get_device_part_uuid(sd_id128_t *u) {
return -EOPNOTSUPP;
}
static inline int efi_loader_get_boot_usec(usec_t *firmware, usec_t *loader) {
return -EOPNOTSUPP;
}
static inline int efi_loader_get_entries(char ***ret) {
return -EOPNOTSUPP;
}
static inline int efi_loader_get_features(uint64_t *ret) {
return -EOPNOTSUPP;
}
static inline int efi_stub_get_features(uint64_t *ret) {
return -EOPNOTSUPP;
}
static inline int efi_stub_measured(int log_level) {
return log_full_errno(log_level, SYNTHETIC_ERRNO(EOPNOTSUPP),
"Compiled without support for EFI");
}
static inline int efi_loader_get_config_timeout_one_shot(usec_t *ret) {
return -EOPNOTSUPP;
}
static inline int efi_loader_update_entry_one_shot_cache(char **cache, struct stat *cache_stat) {
return -EOPNOTSUPP;
}
#endif
bool efi_loader_entry_name_valid(const char *s);
| 1,664 | 25.015625 | 107 |
h
|
null |
systemd-main/src/shared/ethtool-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <macro.h>
#include <net/ethernet.h>
#include <linux/ethtool.h>
#include "conf-parser.h"
#include "ether-addr-util.h"
#define N_ADVERTISE 4
/* we can't use DUPLEX_ prefix, as it
* clashes with <linux/ethtool.h> */
typedef enum Duplex {
DUP_HALF = DUPLEX_HALF,
DUP_FULL = DUPLEX_FULL,
_DUP_MAX,
_DUP_INVALID = -EINVAL,
} Duplex;
typedef enum NetDevFeature {
NET_DEV_FEAT_SG,
NET_DEV_FEAT_IP_CSUM,
NET_DEV_FEAT_HW_CSUM,
NET_DEV_FEAT_IPV6_CSUM,
NET_DEV_FEAT_HIGHDMA,
NET_DEV_FEAT_FRAGLIST,
NET_DEV_FEAT_HW_VLAN_CTAG_TX,
NET_DEV_FEAT_HW_VLAN_CTAG_RX,
NET_DEV_FEAT_HW_VLAN_CTAG_FILTER,
NET_DEV_FEAT_HW_VLAN_STAG_TX,
NET_DEV_FEAT_HW_VLAN_STAG_RX,
NET_DEV_FEAT_HW_VLAN_STAG_FILTER,
NET_DEV_FEAT_VLAN_CHALLENGED,
NET_DEV_FEAT_GSO,
NET_DEV_FEAT_LLTX,
NET_DEV_FEAT_NETNS_LOCAL,
NET_DEV_FEAT_GRO,
NET_DEV_FEAT_GRO_HW,
NET_DEV_FEAT_LRO,
NET_DEV_FEAT_TSO,
NET_DEV_FEAT_GSO_ROBUST,
NET_DEV_FEAT_TSO_ECN,
NET_DEV_FEAT_TSO_MANGLEID,
NET_DEV_FEAT_TSO6,
NET_DEV_FEAT_FSO,
NET_DEV_FEAT_GSO_GRE,
NET_DEV_FEAT_GSO_GRE_CSUM,
NET_DEV_FEAT_GSO_IPXIP4,
NET_DEV_FEAT_GSO_IPXIP6,
NET_DEV_FEAT_GSO_UDP_TUNNEL,
NET_DEV_FEAT_GSO_UDP_TUNNEL_CSUM,
NET_DEV_FEAT_GSO_PARTIAL,
NET_DEV_FEAT_GSO_TUNNEL_REMCSUM,
NET_DEV_FEAT_GSO_SCTP,
NET_DEV_FEAT_GSO_ESP,
NET_DEV_FEAT_GSO_UDP_L4,
NET_DEV_FEAT_GSO_FRAGLIST,
NET_DEV_FEAT_FCOE_CRC,
NET_DEV_FEAT_SCTP_CRC,
NET_DEV_FEAT_FCOE_MTU,
NET_DEV_FEAT_NTUPLE,
NET_DEV_FEAT_RXHASH,
NET_DEV_FEAT_RXCSUM,
NET_DEV_FEAT_NOCACHE_COPY,
NET_DEV_FEAT_LOOPBACK,
NET_DEV_FEAT_RXFCS,
NET_DEV_FEAT_RXALL,
NET_DEV_FEAT_HW_L2FW_DOFFLOAD,
NET_DEV_FEAT_HW_TC,
NET_DEV_FEAT_HW_ESP,
NET_DEV_FEAT_HW_ESP_TX_CSUM,
NET_DEV_FEAT_RX_UDP_TUNNEL_PORT,
NET_DEV_FEAT_HW_TLS_RECORD,
NET_DEV_FEAT_HW_TLS_TX,
NET_DEV_FEAT_HW_TLS_RX,
NET_DEV_FEAT_GRO_FRAGLIST,
NET_DEV_FEAT_HW_MACSEC,
NET_DEV_FEAT_GRO_UDP_FWD,
NET_DEV_FEAT_HW_HSR_TAG_INS,
NET_DEV_FEAT_HW_HSR_TAG_RM,
NET_DEV_FEAT_HW_HSR_FWD,
NET_DEV_FEAT_HW_HSR_DUP,
_NET_DEV_FEAT_SIMPLE_MAX,
NET_DEV_FEAT_TXCSUM = _NET_DEV_FEAT_SIMPLE_MAX,
_NET_DEV_FEAT_MAX,
_NET_DEV_FEAT_INVALID = -EINVAL,
} NetDevFeature;
typedef enum NetDevPort {
NET_DEV_PORT_TP = PORT_TP,
NET_DEV_PORT_AUI = PORT_AUI,
NET_DEV_PORT_MII = PORT_MII,
NET_DEV_PORT_FIBRE = PORT_FIBRE,
NET_DEV_PORT_BNC = PORT_BNC,
NET_DEV_PORT_DA = PORT_DA,
NET_DEV_PORT_NONE = PORT_NONE,
NET_DEV_PORT_OTHER = PORT_OTHER,
_NET_DEV_PORT_MAX,
_NET_DEV_PORT_INVALID = -EINVAL,
} NetDevPort;
#define ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NU32 (SCHAR_MAX)
#define ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NBYTES (4 * ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NU32)
/* layout of the struct passed from/to userland */
struct ethtool_link_usettings {
struct ethtool_link_settings base;
struct {
uint32_t supported[ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NU32];
uint32_t advertising[ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NU32];
uint32_t lp_advertising[ETHTOOL_LINK_MODE_MASK_MAX_KERNEL_NU32];
} link_modes;
};
typedef struct u32_opt {
uint32_t value; /* a value of 0 indicates the hardware advertised maximum should be used. */
bool set;
} u32_opt;
typedef struct netdev_channels {
u32_opt rx;
u32_opt tx;
u32_opt other;
u32_opt combined;
} netdev_channels;
typedef struct netdev_ring_param {
u32_opt rx;
u32_opt rx_mini;
u32_opt rx_jumbo;
u32_opt tx;
} netdev_ring_param;
typedef struct netdev_coalesce_param {
u32_opt rx_coalesce_usecs;
u32_opt rx_max_coalesced_frames;
u32_opt rx_coalesce_usecs_irq;
u32_opt rx_max_coalesced_frames_irq;
u32_opt tx_coalesce_usecs;
u32_opt tx_max_coalesced_frames;
u32_opt tx_coalesce_usecs_irq;
u32_opt tx_max_coalesced_frames_irq;
u32_opt stats_block_coalesce_usecs;
int use_adaptive_rx_coalesce;
int use_adaptive_tx_coalesce;
u32_opt pkt_rate_low;
u32_opt rx_coalesce_usecs_low;
u32_opt rx_max_coalesced_frames_low;
u32_opt tx_coalesce_usecs_low;
u32_opt tx_max_coalesced_frames_low;
u32_opt pkt_rate_high;
u32_opt rx_coalesce_usecs_high;
u32_opt rx_max_coalesced_frames_high;
u32_opt tx_coalesce_usecs_high;
u32_opt tx_max_coalesced_frames_high;
u32_opt rate_sample_interval;
} netdev_coalesce_param;
int ethtool_get_driver(int *ethtool_fd, const char *ifname, char **ret);
int ethtool_get_link_info(int *ethtool_fd, const char *ifname,
int *ret_autonegotiation, uint64_t *ret_speed,
Duplex *ret_duplex, NetDevPort *ret_port);
int ethtool_get_permanent_hw_addr(int *ethtool_fd, const char *ifname, struct hw_addr_data *ret);
int ethtool_set_wol(int *ethtool_fd, const char *ifname, uint32_t wolopts, const uint8_t password[SOPASS_MAX]);
int ethtool_set_nic_buffer_size(int *ethtool_fd, const char *ifname, const netdev_ring_param *ring);
int ethtool_set_features(int *ethtool_fd, const char *ifname, const int features[static _NET_DEV_FEAT_MAX]);
int ethtool_set_glinksettings(
int *fd,
const char *ifname,
int autonegotiation,
const uint32_t advertise[static N_ADVERTISE],
uint64_t speed,
Duplex duplex,
NetDevPort port,
uint8_t mdi);
int ethtool_set_channels(int *ethtool_fd, const char *ifname, const netdev_channels *channels);
int ethtool_set_flow_control(int *fd, const char *ifname, int rx, int tx, int autoneg);
int ethtool_set_nic_coalesce_settings(int *ethtool_fd, const char *ifname, const netdev_coalesce_param *coalesce);
const char *duplex_to_string(Duplex d) _const_;
Duplex duplex_from_string(const char *d) _pure_;
int wol_options_to_string_alloc(uint32_t opts, char **ret);
const char *port_to_string(NetDevPort port) _const_;
NetDevPort port_from_string(const char *port) _pure_;
const char *mdi_to_string(int mdi) _const_;
const char *ethtool_link_mode_bit_to_string(enum ethtool_link_mode_bit_indices val) _const_;
enum ethtool_link_mode_bit_indices ethtool_link_mode_bit_from_string(const char *str) _pure_;
CONFIG_PARSER_PROTOTYPE(config_parse_duplex);
CONFIG_PARSER_PROTOTYPE(config_parse_wol);
CONFIG_PARSER_PROTOTYPE(config_parse_port);
CONFIG_PARSER_PROTOTYPE(config_parse_mdi);
CONFIG_PARSER_PROTOTYPE(config_parse_advertise);
CONFIG_PARSER_PROTOTYPE(config_parse_ring_buffer_or_channel);
CONFIG_PARSER_PROTOTYPE(config_parse_coalesce_u32);
CONFIG_PARSER_PROTOTYPE(config_parse_coalesce_sec);
CONFIG_PARSER_PROTOTYPE(config_parse_nic_coalesce_setting);
| 7,320 | 34.538835 | 114 |
h
|
null |
systemd-main/src/shared/exec-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <dirent.h>
#include <errno.h>
#include <sys/prctl.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include "alloc-util.h"
#include "conf-files.h"
#include "env-file.h"
#include "env-util.h"
#include "errno-util.h"
#include "exec-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "hashmap.h"
#include "macro.h"
#include "missing_syscall.h"
#include "path-util.h"
#include "process-util.h"
#include "serialize.h"
#include "set.h"
#include "signal-util.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"
#include "tmpfile-util.h"
#define EXIT_SKIP_REMAINING 77
/* Put this test here for a lack of better place */
assert_cc(EAGAIN == EWOULDBLOCK);
static int do_spawn(const char *path, char *argv[], int stdout_fd, pid_t *pid, bool set_systemd_exec_pid) {
pid_t _pid;
int r;
if (null_or_empty_path(path) > 0) {
log_debug("%s is empty (a mask).", path);
return 0;
}
r = safe_fork("(direxec)", FORK_DEATHSIG|FORK_LOG|FORK_RLIMIT_NOFILE_SAFE, &_pid);
if (r < 0)
return r;
if (r == 0) {
char *_argv[2];
if (stdout_fd >= 0) {
r = rearrange_stdio(STDIN_FILENO, TAKE_FD(stdout_fd), STDERR_FILENO);
if (r < 0)
_exit(EXIT_FAILURE);
}
if (set_systemd_exec_pid) {
r = setenv_systemd_exec_pid(false);
if (r < 0)
log_warning_errno(r, "Failed to set $SYSTEMD_EXEC_PID, ignoring: %m");
}
if (!argv) {
_argv[0] = (char*) path;
_argv[1] = NULL;
argv = _argv;
} else
argv[0] = (char*) path;
execv(path, argv);
log_error_errno(errno, "Failed to execute %s: %m", path);
_exit(EXIT_FAILURE);
}
*pid = _pid;
return 1;
}
static int do_execute(
char* const* paths,
const char *root,
usec_t timeout,
gather_stdout_callback_t const callbacks[_STDOUT_CONSUME_MAX],
void* const callback_args[_STDOUT_CONSUME_MAX],
int output_fd,
char *argv[],
char *envp[],
ExecDirFlags flags) {
_cleanup_hashmap_free_free_ Hashmap *pids = NULL;
bool parallel_execution;
int r;
/* We fork this all off from a child process so that we can somewhat cleanly make
* use of SIGALRM to set a time limit.
*
* We attempt to perform parallel execution if configured by the user, however
* if `callbacks` is nonnull, execution must be serial.
*/
parallel_execution = FLAGS_SET(flags, EXEC_DIR_PARALLEL) && !callbacks;
if (parallel_execution) {
pids = hashmap_new(NULL);
if (!pids)
return log_oom();
}
/* Abort execution of this process after the timeout. We simply rely on SIGALRM as
* default action terminating the process, and turn on alarm(). */
if (timeout != USEC_INFINITY)
alarm(DIV_ROUND_UP(timeout, USEC_PER_SEC));
STRV_FOREACH(e, envp)
if (putenv(*e) != 0)
return log_error_errno(errno, "Failed to set environment variable: %m");
STRV_FOREACH(path, paths) {
_cleanup_free_ char *t = NULL;
_cleanup_close_ int fd = -EBADF;
pid_t pid;
t = path_join(root, *path);
if (!t)
return log_oom();
if (callbacks) {
_cleanup_free_ char *bn = NULL;
r = path_extract_filename(*path, &bn);
if (r < 0)
return log_error_errno(r, "Failed to extract filename from path '%s': %m", *path);
fd = open_serialization_fd(bn);
if (fd < 0)
return log_error_errno(fd, "Failed to open serialization file: %m");
}
r = do_spawn(t, argv, fd, &pid, FLAGS_SET(flags, EXEC_DIR_SET_SYSTEMD_EXEC_PID));
if (r <= 0)
continue;
if (parallel_execution) {
r = hashmap_put(pids, PID_TO_PTR(pid), t);
if (r < 0)
return log_oom();
t = NULL;
} else {
bool skip_remaining = false;
r = wait_for_terminate_and_check(t, pid, WAIT_LOG_ABNORMAL);
if (r < 0)
return r;
if (r > 0) {
if (FLAGS_SET(flags, EXEC_DIR_SKIP_REMAINING) && r == EXIT_SKIP_REMAINING) {
log_info("%s succeeded with exit status %i, not executing remaining executables.", *path, r);
skip_remaining = true;
} else if (FLAGS_SET(flags, EXEC_DIR_IGNORE_ERRORS))
log_warning("%s failed with exit status %i, ignoring.", *path, r);
else {
log_error("%s failed with exit status %i.", *path, r);
return r;
}
}
if (callbacks) {
if (lseek(fd, 0, SEEK_SET) < 0)
return log_error_errno(errno, "Failed to seek on serialization fd: %m");
r = callbacks[STDOUT_GENERATE](TAKE_FD(fd), callback_args[STDOUT_GENERATE]);
if (r < 0)
return log_error_errno(r, "Failed to process output from %s: %m", *path);
}
if (skip_remaining)
break;
}
}
if (callbacks) {
r = callbacks[STDOUT_COLLECT](output_fd, callback_args[STDOUT_COLLECT]);
if (r < 0)
return log_error_errno(r, "Callback two failed: %m");
}
while (!hashmap_isempty(pids)) {
_cleanup_free_ char *t = NULL;
pid_t pid;
pid = PTR_TO_PID(hashmap_first_key(pids));
assert(pid > 0);
t = hashmap_remove(pids, PID_TO_PTR(pid));
assert(t);
r = wait_for_terminate_and_check(t, pid, WAIT_LOG);
if (r < 0)
return r;
if (!FLAGS_SET(flags, EXEC_DIR_IGNORE_ERRORS) && r > 0)
return r;
}
return 0;
}
int execute_strv(
const char *name,
char* const* paths,
const char *root,
usec_t timeout,
gather_stdout_callback_t const callbacks[_STDOUT_CONSUME_MAX],
void* const callback_args[_STDOUT_CONSUME_MAX],
char *argv[],
char *envp[],
ExecDirFlags flags) {
_cleanup_close_ int fd = -EBADF;
pid_t executor_pid;
int r;
assert(!FLAGS_SET(flags, EXEC_DIR_PARALLEL | EXEC_DIR_SKIP_REMAINING));
if (strv_isempty(paths))
return 0;
if (callbacks) {
assert(name);
assert(callback_args);
assert(callbacks[STDOUT_GENERATE]);
assert(callbacks[STDOUT_COLLECT]);
assert(callbacks[STDOUT_CONSUME]);
fd = open_serialization_fd(name);
if (fd < 0)
return log_error_errno(fd, "Failed to open serialization file: %m");
}
/* Executes all binaries in the directories serially or in parallel and waits for
* them to finish. Optionally a timeout is applied. If a file with the same name
* exists in more than one directory, the earliest one wins. */
r = safe_fork("(sd-executor)", FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_LOG, &executor_pid);
if (r < 0)
return r;
if (r == 0) {
r = do_execute(paths, root, timeout, callbacks, callback_args, fd, argv, envp, flags);
_exit(r < 0 ? EXIT_FAILURE : r);
}
r = wait_for_terminate_and_check("(sd-executor)", executor_pid, 0);
if (r < 0)
return r;
if (!FLAGS_SET(flags, EXEC_DIR_IGNORE_ERRORS) && r > 0)
return r;
if (!callbacks)
return 0;
if (lseek(fd, 0, SEEK_SET) < 0)
return log_error_errno(errno, "Failed to rewind serialization fd: %m");
r = callbacks[STDOUT_CONSUME](TAKE_FD(fd), callback_args[STDOUT_CONSUME]);
if (r < 0)
return log_error_errno(r, "Failed to parse returned data: %m");
return 0;
}
int execute_directories(
const char* const* directories,
usec_t timeout,
gather_stdout_callback_t const callbacks[_STDOUT_CONSUME_MAX],
void* const callback_args[_STDOUT_CONSUME_MAX],
char *argv[],
char *envp[],
ExecDirFlags flags) {
_cleanup_strv_free_ char **paths = NULL;
_cleanup_free_ char *name = NULL;
int r;
assert(!strv_isempty((char**) directories));
r = conf_files_list_strv(&paths, NULL, NULL, CONF_FILES_EXECUTABLE|CONF_FILES_REGULAR|CONF_FILES_FILTER_MASKED, directories);
if (r < 0)
return log_error_errno(r, "Failed to enumerate executables: %m");
if (strv_isempty(paths)) {
log_debug("No executables found.");
return 0;
}
if (callbacks) {
r = path_extract_filename(directories[0], &name);
if (r < 0)
return log_error_errno(r, "Failed to extract file name from '%s': %m", directories[0]);
}
return execute_strv(name, paths, NULL, timeout, callbacks, callback_args, argv, envp, flags);
}
static int gather_environment_generate(int fd, void *arg) {
char ***env = ASSERT_PTR(arg);
_cleanup_fclose_ FILE *f = NULL;
_cleanup_strv_free_ char **new = NULL;
int r;
/* Read a series of VAR=value assignments from fd, use them to update the list of
* variables in env. Also update the exported environment.
*
* fd is always consumed, even on error.
*/
f = fdopen(fd, "r");
if (!f) {
safe_close(fd);
return -errno;
}
r = load_env_file_pairs(f, NULL, &new);
if (r < 0)
return r;
STRV_FOREACH_PAIR(x, y, new) {
if (!env_name_is_valid(*x)) {
log_warning("Invalid variable assignment \"%s=...\", ignoring.", *x);
continue;
}
r = strv_env_assign(env, *x, *y);
if (r < 0)
return r;
if (setenv(*x, *y, true) < 0)
return -errno;
}
return 0;
}
static int gather_environment_collect(int fd, void *arg) {
_cleanup_fclose_ FILE *f = NULL;
char ***env = ASSERT_PTR(arg);
int r;
/* Write out a series of env=cescape(VAR=value) assignments to fd. */
f = fdopen(fd, "w");
if (!f) {
safe_close(fd);
return -errno;
}
r = serialize_strv(f, "env", *env);
if (r < 0)
return r;
r = fflush_and_check(f);
if (r < 0)
return r;
return 0;
}
static int gather_environment_consume(int fd, void *arg) {
_cleanup_fclose_ FILE *f = NULL;
char ***env = ASSERT_PTR(arg);
int r = 0;
/* Read a series of env=cescape(VAR=value) assignments from fd into env. */
f = fdopen(fd, "r");
if (!f) {
safe_close(fd);
return -errno;
}
for (;;) {
_cleanup_free_ char *line = NULL;
const char *v;
int k;
k = read_line(f, LONG_LINE_MAX, &line);
if (k < 0)
return k;
if (k == 0)
break;
v = startswith(line, "env=");
if (!v) {
log_debug("Serialization line \"%s\" unexpectedly didn't start with \"env=\".", line);
if (r == 0)
r = -EINVAL;
continue;
}
k = deserialize_environment(v, env);
if (k < 0) {
log_debug_errno(k, "Invalid serialization line \"%s\": %m", line);
if (r == 0)
r = k;
}
}
return r;
}
int exec_command_flags_from_strv(char **ex_opts, ExecCommandFlags *flags) {
ExecCommandFlags ex_flag, ret_flags = 0;
assert(flags);
STRV_FOREACH(opt, ex_opts) {
ex_flag = exec_command_flags_from_string(*opt);
if (ex_flag < 0)
return ex_flag;
ret_flags |= ex_flag;
}
*flags = ret_flags;
return 0;
}
int exec_command_flags_to_strv(ExecCommandFlags flags, char ***ex_opts) {
_cleanup_strv_free_ char **ret_opts = NULL;
ExecCommandFlags it = flags;
const char *str;
int r;
assert(ex_opts);
if (flags < 0)
return flags;
for (unsigned i = 0; it != 0; it &= ~(1 << i), i++)
if (FLAGS_SET(flags, (1 << i))) {
str = exec_command_flags_to_string(1 << i);
if (!str)
return -EINVAL;
r = strv_extend(&ret_opts, str);
if (r < 0)
return r;
}
*ex_opts = TAKE_PTR(ret_opts);
return 0;
}
const gather_stdout_callback_t gather_environment[] = {
gather_environment_generate,
gather_environment_collect,
gather_environment_consume,
};
static const char* const exec_command_strings[] = {
"ignore-failure", /* EXEC_COMMAND_IGNORE_FAILURE */
"privileged", /* EXEC_COMMAND_FULLY_PRIVILEGED */
"no-setuid", /* EXEC_COMMAND_NO_SETUID */
"ambient", /* EXEC_COMMAND_AMBIENT_MAGIC */
"no-env-expand", /* EXEC_COMMAND_NO_ENV_EXPAND */
};
const char* exec_command_flags_to_string(ExecCommandFlags i) {
for (size_t idx = 0; idx < ELEMENTSOF(exec_command_strings); idx++)
if (i == (1 << idx))
return exec_command_strings[idx];
return NULL;
}
ExecCommandFlags exec_command_flags_from_string(const char *s) {
ssize_t idx;
idx = string_table_lookup(exec_command_strings, ELEMENTSOF(exec_command_strings), s);
if (idx < 0)
return _EXEC_COMMAND_FLAGS_INVALID;
else
return 1 << idx;
}
int fexecve_or_execve(int executable_fd, const char *executable, char *const argv[], char *const envp[]) {
/* Refuse invalid fds, regardless if fexecve() use is enabled or not */
if (executable_fd < 0)
return -EBADF;
/* Block any attempts on exploiting Linux' liberal argv[] handling, i.e. CVE-2021-4034 and suchlike */
if (isempty(executable) || strv_isempty(argv))
return -EINVAL;
#if ENABLE_FEXECVE
execveat(executable_fd, "", argv, envp, AT_EMPTY_PATH);
if (IN_SET(errno, ENOSYS, ENOENT) || ERRNO_IS_PRIVILEGE(errno))
/* Old kernel or a script or an overzealous seccomp filter? Let's fall back to execve().
*
* fexecve(3): "If fd refers to a script (i.e., it is an executable text file that names a
* script interpreter with a first line that begins with the characters #!) and the
* close-on-exec flag has been set for fd, then fexecve() fails with the error ENOENT. This
* error occurs because, by the time the script interpreter is executed, fd has already been
* closed because of the close-on-exec flag. Thus, the close-on-exec flag can't be set on fd
* if it refers to a script."
*
* Unfortunately, if we unset close-on-exec, the script will be executed just fine, but (at
* least in case of bash) the script name, $0, will be shown as /dev/fd/nnn, which breaks
* scripts which make use of $0. Thus, let's fall back to execve() in this case.
*/
#endif
execve(executable, argv, envp);
return -errno;
}
int fork_agent(const char *name, const int except[], size_t n_except, pid_t *ret_pid, const char *path, ...) {
bool stdout_is_tty, stderr_is_tty;
size_t n, i;
va_list ap;
char **l;
int r;
assert(path);
/* Spawns a temporary TTY agent, making sure it goes away when we go away */
r = safe_fork_full(name,
NULL,
except,
n_except,
FORK_RESET_SIGNALS|FORK_DEATHSIG|FORK_CLOSE_ALL_FDS|FORK_REOPEN_LOG|FORK_RLIMIT_NOFILE_SAFE,
ret_pid);
if (r < 0)
return r;
if (r > 0)
return 0;
/* In the child: */
stdout_is_tty = isatty(STDOUT_FILENO);
stderr_is_tty = isatty(STDERR_FILENO);
if (!stdout_is_tty || !stderr_is_tty) {
int fd;
/* Detach from stdout/stderr and reopen /dev/tty for them. This is important to ensure that
* when systemctl is started via popen() or a similar call that expects to read EOF we
* actually do generate EOF and not delay this indefinitely by keeping an unused copy of
* stdin around. */
fd = open("/dev/tty", O_WRONLY);
if (fd < 0) {
if (errno != ENXIO) {
log_error_errno(errno, "Failed to open /dev/tty: %m");
_exit(EXIT_FAILURE);
}
/* If we get ENXIO here we have no controlling TTY even though stdout/stderr are
* connected to a TTY. That's a weird setup, but let's handle it gracefully: let's
* skip the forking of the agents, given the TTY setup is not in order. */
} else {
if (!stdout_is_tty && dup2(fd, STDOUT_FILENO) < 0) {
log_error_errno(errno, "Failed to dup2 /dev/tty: %m");
_exit(EXIT_FAILURE);
}
if (!stderr_is_tty && dup2(fd, STDERR_FILENO) < 0) {
log_error_errno(errno, "Failed to dup2 /dev/tty: %m");
_exit(EXIT_FAILURE);
}
fd = safe_close_above_stdio(fd);
}
}
/* Count arguments */
va_start(ap, path);
for (n = 0; va_arg(ap, char*); n++)
;
va_end(ap);
/* Allocate strv */
l = newa(char*, n + 1);
/* Fill in arguments */
va_start(ap, path);
for (i = 0; i <= n; i++)
l[i] = va_arg(ap, char*);
va_end(ap);
execv(path, l);
_exit(EXIT_FAILURE);
}
| 20,575 | 33.465662 | 133 |
c
|
null |
systemd-main/src/shared/exec-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "time-util.h"
typedef int (*gather_stdout_callback_t) (int fd, void *arg);
enum {
STDOUT_GENERATE, /* from generators to helper process */
STDOUT_COLLECT, /* from helper process to main process */
STDOUT_CONSUME, /* process data in main process */
_STDOUT_CONSUME_MAX,
};
typedef enum {
EXEC_DIR_NONE = 0, /* No execdir flags */
EXEC_DIR_PARALLEL = 1 << 0, /* Execute scripts in parallel, if possible */
EXEC_DIR_IGNORE_ERRORS = 1 << 1, /* Ignore non-zero exit status of scripts */
EXEC_DIR_SET_SYSTEMD_EXEC_PID = 1 << 2, /* Set $SYSTEMD_EXEC_PID environment variable */
EXEC_DIR_SKIP_REMAINING = 1 << 3, /* Ignore remaining executions when one exit with 77. */
} ExecDirFlags;
typedef enum ExecCommandFlags {
EXEC_COMMAND_IGNORE_FAILURE = 1 << 0,
EXEC_COMMAND_FULLY_PRIVILEGED = 1 << 1,
EXEC_COMMAND_NO_SETUID = 1 << 2,
EXEC_COMMAND_AMBIENT_MAGIC = 1 << 3,
EXEC_COMMAND_NO_ENV_EXPAND = 1 << 4,
_EXEC_COMMAND_FLAGS_INVALID = -EINVAL,
} ExecCommandFlags;
int execute_strv(
const char *name,
char* const* paths,
const char *root,
usec_t timeout,
gather_stdout_callback_t const callbacks[_STDOUT_CONSUME_MAX],
void* const callback_args[_STDOUT_CONSUME_MAX],
char *argv[],
char *envp[],
ExecDirFlags flags);
int execute_directories(
const char* const* directories,
usec_t timeout,
gather_stdout_callback_t const callbacks[_STDOUT_CONSUME_MAX],
void* const callback_args[_STDOUT_CONSUME_MAX],
char *argv[],
char *envp[],
ExecDirFlags flags);
int exec_command_flags_from_strv(char **ex_opts, ExecCommandFlags *flags);
int exec_command_flags_to_strv(ExecCommandFlags flags, char ***ex_opts);
extern const gather_stdout_callback_t gather_environment[_STDOUT_CONSUME_MAX];
const char* exec_command_flags_to_string(ExecCommandFlags i);
ExecCommandFlags exec_command_flags_from_string(const char *s);
int fexecve_or_execve(int executable_fd, const char *executable, char *const argv[], char *const envp[]);
int fork_agent(const char *name, const int except[], size_t n_except, pid_t *ret_pid, const char *path, ...) _sentinel_;
| 2,569 | 38.538462 | 120 |
h
|
null |
systemd-main/src/shared/exit-status.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <signal.h>
#include <stdlib.h>
#include <sysexits.h>
#include "exit-status.h"
#include "macro.h"
#include "parse-util.h"
#include "set.h"
#include "string-util.h"
const ExitStatusMapping exit_status_mappings[256] = {
/* Exit status ranges:
*
* 0…1 │ ISO C, EXIT_SUCCESS + EXIT_FAILURE
* 2…7 │ LSB exit codes for init scripts
* 8…63 │ (Currently unmapped)
* 64…78 │ BSD defined exit codes
* 79…199 │ (Currently unmapped)
* 200…244 │ systemd's private error codes (might be extended to 254 in future development)
* 245…254 │ (Currently unmapped, but see above)
*
* 255 │ EXIT_EXCEPTION (We use this to propagate exit-by-signal events. It's frequently used by others apps (like bash)
* │ to indicate exit reason that cannot really be expressed in a single exit status value — such as a propagated
* │ signal or such, and we follow that logic here.)
*/
[EXIT_SUCCESS] = { "SUCCESS", EXIT_STATUS_LIBC },
[EXIT_FAILURE] = { "FAILURE", EXIT_STATUS_LIBC },
[EXIT_CHDIR] = { "CHDIR", EXIT_STATUS_SYSTEMD },
[EXIT_NICE] = { "NICE", EXIT_STATUS_SYSTEMD },
[EXIT_FDS] = { "FDS", EXIT_STATUS_SYSTEMD },
[EXIT_EXEC] = { "EXEC", EXIT_STATUS_SYSTEMD },
[EXIT_MEMORY] = { "MEMORY", EXIT_STATUS_SYSTEMD },
[EXIT_LIMITS] = { "LIMITS", EXIT_STATUS_SYSTEMD },
[EXIT_OOM_ADJUST] = { "OOM_ADJUST", EXIT_STATUS_SYSTEMD },
[EXIT_SIGNAL_MASK] = { "SIGNAL_MASK", EXIT_STATUS_SYSTEMD },
[EXIT_STDIN] = { "STDIN", EXIT_STATUS_SYSTEMD },
[EXIT_STDOUT] = { "STDOUT", EXIT_STATUS_SYSTEMD },
[EXIT_CHROOT] = { "CHROOT", EXIT_STATUS_SYSTEMD },
[EXIT_IOPRIO] = { "IOPRIO", EXIT_STATUS_SYSTEMD },
[EXIT_TIMERSLACK] = { "TIMERSLACK", EXIT_STATUS_SYSTEMD },
[EXIT_SECUREBITS] = { "SECUREBITS", EXIT_STATUS_SYSTEMD },
[EXIT_SETSCHEDULER] = { "SETSCHEDULER", EXIT_STATUS_SYSTEMD },
[EXIT_CPUAFFINITY] = { "CPUAFFINITY", EXIT_STATUS_SYSTEMD },
[EXIT_GROUP] = { "GROUP", EXIT_STATUS_SYSTEMD },
[EXIT_USER] = { "USER", EXIT_STATUS_SYSTEMD },
[EXIT_CAPABILITIES] = { "CAPABILITIES", EXIT_STATUS_SYSTEMD },
[EXIT_CGROUP] = { "CGROUP", EXIT_STATUS_SYSTEMD },
[EXIT_SETSID] = { "SETSID", EXIT_STATUS_SYSTEMD },
[EXIT_CONFIRM] = { "CONFIRM", EXIT_STATUS_SYSTEMD },
[EXIT_STDERR] = { "STDERR", EXIT_STATUS_SYSTEMD },
[EXIT_PAM] = { "PAM", EXIT_STATUS_SYSTEMD },
[EXIT_NETWORK] = { "NETWORK", EXIT_STATUS_SYSTEMD },
[EXIT_NAMESPACE] = { "NAMESPACE", EXIT_STATUS_SYSTEMD },
[EXIT_NO_NEW_PRIVILEGES] = { "NO_NEW_PRIVILEGES", EXIT_STATUS_SYSTEMD },
[EXIT_SECCOMP] = { "SECCOMP", EXIT_STATUS_SYSTEMD },
[EXIT_SELINUX_CONTEXT] = { "SELINUX_CONTEXT", EXIT_STATUS_SYSTEMD },
[EXIT_PERSONALITY] = { "PERSONALITY", EXIT_STATUS_SYSTEMD },
[EXIT_APPARMOR_PROFILE] = { "APPARMOR", EXIT_STATUS_SYSTEMD },
[EXIT_ADDRESS_FAMILIES] = { "ADDRESS_FAMILIES", EXIT_STATUS_SYSTEMD },
[EXIT_RUNTIME_DIRECTORY] = { "RUNTIME_DIRECTORY", EXIT_STATUS_SYSTEMD },
[EXIT_CHOWN] = { "CHOWN", EXIT_STATUS_SYSTEMD },
[EXIT_SMACK_PROCESS_LABEL] = { "SMACK_PROCESS_LABEL", EXIT_STATUS_SYSTEMD },
[EXIT_KEYRING] = { "KEYRING", EXIT_STATUS_SYSTEMD },
[EXIT_STATE_DIRECTORY] = { "STATE_DIRECTORY", EXIT_STATUS_SYSTEMD },
[EXIT_CACHE_DIRECTORY] = { "CACHE_DIRECTORY", EXIT_STATUS_SYSTEMD },
[EXIT_LOGS_DIRECTORY] = { "LOGS_DIRECTORY", EXIT_STATUS_SYSTEMD },
[EXIT_CONFIGURATION_DIRECTORY] = { "CONFIGURATION_DIRECTORY", EXIT_STATUS_SYSTEMD },
[EXIT_NUMA_POLICY] = { "NUMA_POLICY", EXIT_STATUS_SYSTEMD },
[EXIT_CREDENTIALS] = { "CREDENTIALS", EXIT_STATUS_SYSTEMD },
[EXIT_BPF] = { "BPF", EXIT_STATUS_SYSTEMD },
[EXIT_KSM] = { "KSM", EXIT_STATUS_SYSTEMD },
[EXIT_EXCEPTION] = { "EXCEPTION", EXIT_STATUS_SYSTEMD },
[EXIT_INVALIDARGUMENT] = { "INVALIDARGUMENT", EXIT_STATUS_LSB },
[EXIT_NOTIMPLEMENTED] = { "NOTIMPLEMENTED", EXIT_STATUS_LSB },
[EXIT_NOPERMISSION] = { "NOPERMISSION", EXIT_STATUS_LSB },
[EXIT_NOTINSTALLED] = { "NOTINSTALLED", EXIT_STATUS_LSB },
[EXIT_NOTCONFIGURED] = { "NOTCONFIGURED", EXIT_STATUS_LSB },
[EXIT_NOTRUNNING] = { "NOTRUNNING", EXIT_STATUS_LSB },
[EX_USAGE] = { "USAGE", EXIT_STATUS_BSD },
[EX_DATAERR] = { "DATAERR", EXIT_STATUS_BSD },
[EX_NOINPUT] = { "NOINPUT", EXIT_STATUS_BSD },
[EX_NOUSER] = { "NOUSER", EXIT_STATUS_BSD },
[EX_NOHOST] = { "NOHOST", EXIT_STATUS_BSD },
[EX_UNAVAILABLE] = { "UNAVAILABLE", EXIT_STATUS_BSD },
[EX_SOFTWARE] = { "SOFTWARE", EXIT_STATUS_BSD },
[EX_OSERR] = { "OSERR", EXIT_STATUS_BSD },
[EX_OSFILE] = { "OSFILE", EXIT_STATUS_BSD },
[EX_CANTCREAT] = { "CANTCREAT", EXIT_STATUS_BSD },
[EX_IOERR] = { "IOERR", EXIT_STATUS_BSD },
[EX_TEMPFAIL] = { "TEMPFAIL", EXIT_STATUS_BSD },
[EX_PROTOCOL] = { "PROTOCOL", EXIT_STATUS_BSD },
[EX_NOPERM] = { "NOPERM", EXIT_STATUS_BSD },
[EX_CONFIG] = { "CONFIG", EXIT_STATUS_BSD },
};
const char* exit_status_to_string(int code, ExitStatusClass class) {
if (code < 0 || (size_t) code >= ELEMENTSOF(exit_status_mappings))
return NULL;
return class & exit_status_mappings[code].class ? exit_status_mappings[code].name : NULL;
}
const char* exit_status_class(int code) {
if (code < 0 || (size_t) code >= ELEMENTSOF(exit_status_mappings))
return NULL;
switch (exit_status_mappings[code].class) {
case EXIT_STATUS_LIBC:
return "libc";
case EXIT_STATUS_SYSTEMD:
return "systemd";
case EXIT_STATUS_LSB:
return "LSB";
case EXIT_STATUS_BSD:
return "BSD";
default: return NULL;
}
}
int exit_status_from_string(const char *s) {
uint8_t val;
int r;
for (size_t i = 0; i < ELEMENTSOF(exit_status_mappings); i++)
if (streq_ptr(s, exit_status_mappings[i].name))
return i;
r = safe_atou8(s, &val);
if (r < 0)
return r;
return val;
}
bool is_clean_exit(int code, int status, ExitClean clean, const ExitStatusSet *success_status) {
if (code == CLD_EXITED)
return status == 0 ||
(success_status &&
bitmap_isset(&success_status->status, status));
/* If a daemon does not implement handlers for some of the signals, we do not consider this an
* unclean shutdown */
if (code == CLD_KILLED)
return (clean == EXIT_CLEAN_DAEMON && IN_SET(status, SIGHUP, SIGINT, SIGTERM, SIGPIPE)) ||
(success_status &&
bitmap_isset(&success_status->signal, status));
return false;
}
void exit_status_set_free(ExitStatusSet *x) {
assert(x);
bitmap_clear(&x->status);
bitmap_clear(&x->signal);
}
bool exit_status_set_is_empty(const ExitStatusSet *x) {
if (!x)
return true;
return bitmap_isclear(&x->status) && bitmap_isclear(&x->signal);
}
bool exit_status_set_test(const ExitStatusSet *x, int code, int status) {
if (code == CLD_EXITED && bitmap_isset(&x->status, status))
return true;
if (IN_SET(code, CLD_KILLED, CLD_DUMPED) && bitmap_isset(&x->signal, status))
return true;
return false;
}
| 9,753 | 53.188889 | 132 |
c
|
null |
systemd-main/src/shared/exit-status.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "bitmap.h"
#include "hashmap.h"
#include "macro.h"
/* This defines pretty names for the LSB 'start' verb exit codes. Note that they shouldn't be confused with
* the LSB 'status' verb exit codes which are defined very differently. For details see:
*
* https://refspecs.linuxbase.org/LSB_5.0.0/LSB-Core-generic/LSB-Core-generic/iniscrptact.html
*/
enum {
/* EXIT_SUCCESS defined by libc */
/* EXIT_FAILURE defined by libc */
EXIT_INVALIDARGUMENT = 2,
EXIT_NOTIMPLEMENTED = 3,
EXIT_NOPERMISSION = 4,
EXIT_NOTINSTALLED = 5,
EXIT_NOTCONFIGURED = 6,
EXIT_NOTRUNNING = 7,
/* BSD's sysexits.h defines a couple EX_xyz exit codes in the range 64 … 78 */
/* The LSB suggests that error codes >= 200 are "reserved". We use them here under the assumption
* that they hence are unused by init scripts. */
EXIT_CHDIR = 200,
EXIT_NICE,
EXIT_FDS,
EXIT_EXEC,
EXIT_MEMORY,
EXIT_LIMITS,
EXIT_OOM_ADJUST,
EXIT_SIGNAL_MASK,
EXIT_STDIN,
EXIT_STDOUT,
EXIT_CHROOT, /* 210 */
EXIT_IOPRIO,
EXIT_TIMERSLACK,
EXIT_SECUREBITS,
EXIT_SETSCHEDULER,
EXIT_CPUAFFINITY,
EXIT_GROUP,
EXIT_USER,
EXIT_CAPABILITIES,
EXIT_CGROUP,
EXIT_SETSID, /* 220 */
EXIT_CONFIRM,
EXIT_STDERR,
_EXIT_RESERVED, /* used to be tcpwrap, don't reuse! */
EXIT_PAM,
EXIT_NETWORK,
EXIT_NAMESPACE,
EXIT_NO_NEW_PRIVILEGES,
EXIT_SECCOMP,
EXIT_SELINUX_CONTEXT,
EXIT_PERSONALITY, /* 230 */
EXIT_APPARMOR_PROFILE,
EXIT_ADDRESS_FAMILIES,
EXIT_RUNTIME_DIRECTORY,
_EXIT_RESERVED2, /* used to be used by kdbus, don't reuse */
EXIT_CHOWN,
EXIT_SMACK_PROCESS_LABEL,
EXIT_KEYRING,
EXIT_STATE_DIRECTORY,
EXIT_CACHE_DIRECTORY,
EXIT_LOGS_DIRECTORY, /* 240 */
EXIT_CONFIGURATION_DIRECTORY,
EXIT_NUMA_POLICY,
EXIT_CREDENTIALS,
EXIT_BPF,
EXIT_KSM,
EXIT_EXCEPTION = 255, /* Whenever we want to propagate an abnormal/signal exit, in line with bash */
};
typedef enum ExitStatusClass {
EXIT_STATUS_LIBC = 1 << 0, /* libc EXIT_STATUS/EXIT_FAILURE */
EXIT_STATUS_SYSTEMD = 1 << 1, /* systemd's own exit codes */
EXIT_STATUS_LSB = 1 << 2, /* LSB exit codes */
EXIT_STATUS_BSD = 1 << 3, /* BSD (EX_xyz) exit codes */
EXIT_STATUS_FULL = EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD | EXIT_STATUS_LSB | EXIT_STATUS_BSD,
} ExitStatusClass;
typedef struct ExitStatusSet {
Bitmap status;
Bitmap signal;
} ExitStatusSet;
const char* exit_status_to_string(int code, ExitStatusClass class) _const_;
const char* exit_status_class(int code) _const_;
int exit_status_from_string(const char *s) _pure_;
typedef struct ExitStatusMapping {
const char *name;
ExitStatusClass class;
} ExitStatusMapping;
extern const ExitStatusMapping exit_status_mappings[256];
typedef enum ExitClean {
EXIT_CLEAN_DAEMON,
EXIT_CLEAN_COMMAND,
} ExitClean;
bool is_clean_exit(int code, int status, ExitClean clean, const ExitStatusSet *success_status);
void exit_status_set_free(ExitStatusSet *x);
bool exit_status_set_is_empty(const ExitStatusSet *x);
bool exit_status_set_test(const ExitStatusSet *x, int code, int status);
| 3,585 | 30.45614 | 109 |
h
|
null |
systemd-main/src/shared/extension-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "architecture.h"
#include "chase.h"
#include "env-util.h"
#include "extension-util.h"
#include "log.h"
#include "os-util.h"
#include "strv.h"
int extension_release_validate(
const char *name,
const char *host_os_release_id,
const char *host_os_release_version_id,
const char *host_os_extension_release_level,
const char *host_extension_scope,
char **extension_release,
ImageClass image_class) {
const char *extension_release_id = NULL, *extension_release_level = NULL, *extension_architecture = NULL;
const char *extension_level = image_class == IMAGE_CONFEXT ? "CONFEXT_LEVEL" : "SYSEXT_LEVEL";
const char *extension_scope = image_class == IMAGE_CONFEXT ? "CONFEXT_SCOPE" : "SYSEXT_SCOPE";
assert(name);
assert(!isempty(host_os_release_id));
/* Now that we can look into the extension/confext image, let's see if the OS version is compatible */
if (strv_isempty(extension_release)) {
log_debug("Extension '%s' carries no release data, ignoring.", name);
return 0;
}
if (host_extension_scope) {
_cleanup_strv_free_ char **scope_list = NULL;
const char *scope;
bool valid;
scope = strv_env_pairs_get(extension_release, extension_scope);
if (scope) {
scope_list = strv_split(scope, WHITESPACE);
if (!scope_list)
return -ENOMEM;
}
/* By default extension are good for attachment in portable service and on the system */
valid = strv_contains(
scope_list ?: STRV_MAKE("system", "portable"),
host_extension_scope);
if (!valid) {
log_debug("Extension '%s' is not suitable for scope %s, ignoring.", name, host_extension_scope);
return 0;
}
}
/* When the architecture field is present and not '_any' it must match the host - for now just look at uname but in
* the future we could check if the kernel also supports 32 bit or binfmt has a translator set up for the architecture */
extension_architecture = strv_env_pairs_get(extension_release, "ARCHITECTURE");
if (!isempty(extension_architecture) && !streq(extension_architecture, "_any") &&
!streq(architecture_to_string(uname_architecture()), extension_architecture)) {
log_debug("Extension '%s' is for architecture '%s', but deployed on top of '%s'.",
name, extension_architecture, architecture_to_string(uname_architecture()));
return 0;
}
extension_release_id = strv_env_pairs_get(extension_release, "ID");
if (isempty(extension_release_id)) {
log_debug("Extension '%s' does not contain ID in release file but requested to match '%s' or be '_any'",
name, host_os_release_id);
return 0;
}
/* A sysext(or confext) with no host OS dependency (static binaries or scripts) can match
* '_any' host OS, and VERSION_ID or SYSEXT_LEVEL(or CONFEXT_LEVEL) are not required anywhere */
if (streq(extension_release_id, "_any")) {
log_debug("Extension '%s' matches '_any' OS.", name);
return 1;
}
if (!streq(host_os_release_id, extension_release_id)) {
log_debug("Extension '%s' is for OS '%s', but deployed on top of '%s'.",
name, extension_release_id, host_os_release_id);
return 0;
}
/* Rolling releases do not typically set VERSION_ID (eg: ArchLinux) */
if (isempty(host_os_release_version_id) && isempty(host_os_extension_release_level)) {
log_debug("No version info on the host (rolling release?), but ID in %s matched.", name);
return 1;
}
/* If the extension has a sysext API level declared, then it must match the host API
* level. Otherwise, compare OS version as a whole */
extension_release_level = strv_env_pairs_get(extension_release, extension_level);
if (!isempty(host_os_extension_release_level) && !isempty(extension_release_level)) {
if (!streq_ptr(host_os_extension_release_level, extension_release_level)) {
log_debug("Extension '%s' is for API level '%s', but running on API level '%s'",
name, strna(extension_release_level), strna(host_os_extension_release_level));
return 0;
}
} else if (!isempty(host_os_release_version_id)) {
const char *extension_release_version_id;
extension_release_version_id = strv_env_pairs_get(extension_release, "VERSION_ID");
if (isempty(extension_release_version_id)) {
log_debug("Extension '%s' does not contain VERSION_ID in release file but requested to match '%s'",
name, strna(host_os_release_version_id));
return 0;
}
if (!streq_ptr(host_os_release_version_id, extension_release_version_id)) {
log_debug("Extension '%s' is for OS '%s', but deployed on top of '%s'.",
name, strna(extension_release_version_id), strna(host_os_release_version_id));
return 0;
}
} else if (isempty(host_os_release_version_id) && isempty(host_os_extension_release_level)) {
/* Rolling releases do not typically set VERSION_ID (eg: ArchLinux) */
log_debug("No version info on the host (rolling release?), but ID in %s matched.", name);
return 1;
}
log_debug("Version info of extension '%s' matches host.", name);
return 1;
}
int parse_env_extension_hierarchies(char ***ret_hierarchies, const char *hierarchy_env) {
_cleanup_free_ char **l = NULL;
int r;
assert(hierarchy_env);
r = getenv_path_list(hierarchy_env, &l);
if (r == -ENXIO) {
if (streq(hierarchy_env, "SYSTEMD_CONFEXT_HIERARCHIES"))
/* Default for confext when unset */
l = strv_new("/etc");
else if (streq(hierarchy_env, "SYSTEMD_SYSEXT_HIERARCHIES"))
/* Default for sysext when unset */
l = strv_new("/usr", "/opt");
else
return -ENXIO;
} else if (r < 0)
return r;
*ret_hierarchies = TAKE_PTR(l);
return 0;
}
int extension_has_forbidden_content(const char *root) {
int r;
/* Insist that extension images do not overwrite the underlying OS release file (it's fine if
* they place one in /etc/os-release, i.e. where things don't matter, as they aren't
* merged.) */
r = chase("/usr/lib/os-release", root, CHASE_PREFIX_ROOT, NULL, NULL);
if (r > 0) {
log_debug("Extension contains '/usr/lib/os-release', which is not allowed, refusing.");
return 1;
}
if (r < 0 && r != -ENOENT)
return log_debug_errno(r, "Failed to determine whether '/usr/lib/os-release' exists in the extension: %m");
return 0;
}
| 7,735 | 46.170732 | 129 |
c
|
null |
systemd-main/src/shared/extension-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "os-util.h"
/* Given an image name (for logging purposes), a set of os-release values from the host and a key-value pair
* vector of extension-release variables, check that the distro and (system extension level or distro
* version) match and return 1, and 0 otherwise. */
int extension_release_validate(
const char *name,
const char *host_os_release_id,
const char *host_os_release_version_id,
const char *host_os_extension_release_level,
const char *host_extension_scope,
char **extension_release,
ImageClass image_class);
/* Parse hierarchy variables and if not set, return "/usr /opt" for sysext and "/etc" for confext */
int parse_env_extension_hierarchies(char ***ret_hierarchies, const char *hierarchy_env);
/* Insist that extension images do not overwrite the underlying OS release file (it's fine if they place one
* in /etc/os-release, i.e. where things don't matter, as they aren't merged.) */
int extension_has_forbidden_content(const char *root);
| 1,150 | 46.958333 | 108 |
h
|
null |
systemd-main/src/shared/fdisk-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "dissect-image.h"
#include "fd-util.h"
#include "fdisk-util.h"
#if HAVE_LIBFDISK
int fdisk_new_context_fd(
int fd,
bool read_only,
uint32_t sector_size,
struct fdisk_context **ret) {
_cleanup_(fdisk_unref_contextp) struct fdisk_context *c = NULL;
int r;
assert(ret);
if (fd < 0)
return -EBADF;
c = fdisk_new_context();
if (!c)
return -ENOMEM;
if (sector_size == UINT32_MAX) {
r = probe_sector_size_prefer_ioctl(fd, §or_size);
if (r < 0)
return r;
}
if (sector_size != 0) {
r = fdisk_save_user_sector_size(c, /* phy= */ 0, sector_size);
if (r < 0)
return r;
}
r = fdisk_assign_device(c, FORMAT_PROC_FD_PATH(fd), read_only);
if (r < 0)
return r;
*ret = TAKE_PTR(c);
return 0;
}
int fdisk_partition_get_uuid_as_id128(struct fdisk_partition *p, sd_id128_t *ret) {
const char *ids;
assert(p);
assert(ret);
ids = fdisk_partition_get_uuid(p);
if (!ids)
return -ENXIO;
return sd_id128_from_string(ids, ret);
}
int fdisk_partition_get_type_as_id128(struct fdisk_partition *p, sd_id128_t *ret) {
struct fdisk_parttype *pt;
const char *pts;
assert(p);
assert(ret);
pt = fdisk_partition_get_type(p);
if (!pt)
return -ENXIO;
pts = fdisk_parttype_get_string(pt);
if (!pts)
return -ENXIO;
return sd_id128_from_string(pts, ret);
}
#endif
| 1,809 | 21.911392 | 83 |
c
|
null |
systemd-main/src/shared/fdisk-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#if HAVE_LIBFDISK
#include <libfdisk.h>
#include "sd-id128.h"
#include "macro.h"
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_context*, fdisk_unref_context, NULL);
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_partition*, fdisk_unref_partition, NULL);
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_parttype*, fdisk_unref_parttype, NULL);
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct fdisk_table*, fdisk_unref_table, NULL);
int fdisk_new_context_fd(int fd, bool read_only, uint32_t sector_size, struct fdisk_context **ret);
int fdisk_partition_get_uuid_as_id128(struct fdisk_partition *p, sd_id128_t *ret);
int fdisk_partition_get_type_as_id128(struct fdisk_partition *p, sd_id128_t *ret);
#endif
| 762 | 32.173913 | 99 |
h
|
null |
systemd-main/src/shared/fdset.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <fcntl.h>
#include <stddef.h>
#include "sd-daemon.h"
#include "alloc-util.h"
#include "dirent-util.h"
#include "fd-util.h"
#include "fdset.h"
#include "log.h"
#include "macro.h"
#include "parse-util.h"
#include "path-util.h"
#include "set.h"
#include "stat-util.h"
#define MAKE_SET(s) ((Set*) s)
#define MAKE_FDSET(s) ((FDSet*) s)
FDSet *fdset_new(void) {
return MAKE_FDSET(set_new(NULL));
}
static inline void fdset_shallow_freep(FDSet **s) {
/* Destroys the set, but does not free the fds inside, like fdset_free()! */
set_free(MAKE_SET(*ASSERT_PTR(s)));
}
int fdset_new_array(FDSet **ret, const int fds[], size_t n_fds) {
_cleanup_(fdset_shallow_freep) FDSet *s = NULL;
int r;
assert(ret);
assert(fds || n_fds == 0);
s = fdset_new();
if (!s)
return -ENOMEM;
for (size_t i = 0; i < n_fds; i++) {
r = fdset_put(s, fds[i]);
if (r < 0)
return r;
}
*ret = TAKE_PTR(s);
return 0;
}
void fdset_close(FDSet *s) {
void *p;
while ((p = set_steal_first(MAKE_SET(s)))) {
/* Valgrind's fd might have ended up in this set here, due to fdset_new_fill(). We'll ignore
* all failures here, so that the EBADFD that valgrind will return us on close() doesn't
* influence us */
/* When reloading duplicates of the private bus connection fds and suchlike are closed here,
* which has no effect at all, since they are only duplicates. So don't be surprised about
* these log messages. */
log_debug("Closing set fd %i", PTR_TO_FD(p));
(void) close_nointr(PTR_TO_FD(p));
}
}
FDSet* fdset_free(FDSet *s) {
fdset_close(s);
set_free(MAKE_SET(s));
return NULL;
}
int fdset_put(FDSet *s, int fd) {
assert(s);
assert(fd >= 0);
/* Avoid integer overflow in FD_TO_PTR() */
if (fd == INT_MAX)
return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Refusing invalid fd: %d", fd);
return set_put(MAKE_SET(s), FD_TO_PTR(fd));
}
int fdset_consume(FDSet *s, int fd) {
int r;
assert(s);
assert(fd >= 0);
r = fdset_put(s, fd);
if (r < 0)
safe_close(fd);
return r;
}
int fdset_put_dup(FDSet *s, int fd) {
_cleanup_close_ int copy = -EBADF;
int r;
assert(s);
assert(fd >= 0);
copy = fcntl(fd, F_DUPFD_CLOEXEC, 3);
if (copy < 0)
return -errno;
r = fdset_put(s, copy);
if (r < 0)
return r;
return TAKE_FD(copy);
}
bool fdset_contains(FDSet *s, int fd) {
assert(s);
assert(fd >= 0);
/* Avoid integer overflow in FD_TO_PTR() */
if (fd == INT_MAX) {
log_debug("Refusing invalid fd: %d", fd);
return false;
}
return !!set_get(MAKE_SET(s), FD_TO_PTR(fd));
}
int fdset_remove(FDSet *s, int fd) {
assert(s);
assert(fd >= 0);
/* Avoid integer overflow in FD_TO_PTR() */
if (fd == INT_MAX)
return log_debug_errno(SYNTHETIC_ERRNO(ENOENT), "Refusing invalid fd: %d", fd);
return set_remove(MAKE_SET(s), FD_TO_PTR(fd)) ? fd : -ENOENT;
}
int fdset_new_fill(
int filter_cloexec, /* if < 0 takes all fds, otherwise only those with O_CLOEXEC set (1) or unset (0) */
FDSet **ret) {
_cleanup_(fdset_shallow_freep) FDSet *s = NULL;
_cleanup_closedir_ DIR *d = NULL;
int r;
assert(ret);
/* Creates an fdset and fills in all currently open file descriptors. */
d = opendir("/proc/self/fd");
if (!d) {
if (errno == ENOENT && proc_mounted() == 0)
return -ENOSYS;
return -errno;
}
s = fdset_new();
if (!s)
return -ENOMEM;
FOREACH_DIRENT(de, d, return -errno) {
int fd;
if (!IN_SET(de->d_type, DT_LNK, DT_UNKNOWN))
continue;
fd = parse_fd(de->d_name);
if (fd < 0)
return fd;
if (fd < 3)
continue;
if (fd == dirfd(d))
continue;
if (filter_cloexec >= 0) {
int fl;
/* If user asked for that filter by O_CLOEXEC. This is useful so that fds that have
* been passed in can be collected and fds which have been created locally can be
* ignored, under the assumption that only the latter have O_CLOEXEC set. */
fl = fcntl(fd, F_GETFD);
if (fl < 0)
return -errno;
if (FLAGS_SET(fl, FD_CLOEXEC) != !!filter_cloexec)
continue;
}
r = fdset_put(s, fd);
if (r < 0)
return r;
}
*ret = TAKE_PTR(s);
return 0;
}
int fdset_cloexec(FDSet *fds, bool b) {
void *p;
int r;
assert(fds);
SET_FOREACH(p, MAKE_SET(fds)) {
r = fd_cloexec(PTR_TO_FD(p), b);
if (r < 0)
return r;
}
return 0;
}
int fdset_new_listen_fds(FDSet **ret, bool unset) {
_cleanup_(fdset_shallow_freep) FDSet *s = NULL;
int n, fd, r;
assert(ret);
/* Creates an fdset and fills in all passed file descriptors */
s = fdset_new();
if (!s)
return -ENOMEM;
n = sd_listen_fds(unset);
for (fd = SD_LISTEN_FDS_START; fd < SD_LISTEN_FDS_START + n; fd ++) {
r = fdset_put(s, fd);
if (r < 0)
return r;
}
*ret = TAKE_PTR(s);
return 0;
}
int fdset_to_array(FDSet *fds, int **ret) {
unsigned j = 0, m;
void *e;
int *a;
assert(ret);
m = fdset_size(fds);
if (m > INT_MAX) /* We want to be able to return an "int" */
return -ENOMEM;
if (m == 0) {
*ret = NULL; /* suppress array allocation if empty */
return 0;
}
a = new(int, m);
if (!a)
return -ENOMEM;
SET_FOREACH(e, MAKE_SET(fds))
a[j++] = PTR_TO_FD(e);
assert(j == m);
*ret = TAKE_PTR(a);
return (int) m;
}
int fdset_close_others(FDSet *fds) {
_cleanup_free_ int *a = NULL;
int n;
n = fdset_to_array(fds, &a);
if (n < 0)
return n;
return close_all_fds(a, n);
}
unsigned fdset_size(FDSet *fds) {
return set_size(MAKE_SET(fds));
}
bool fdset_isempty(FDSet *fds) {
return set_isempty(MAKE_SET(fds));
}
int fdset_iterate(FDSet *s, Iterator *i) {
void *p;
if (!set_iterate(MAKE_SET(s), i, &p))
return -ENOENT;
return PTR_TO_FD(p);
}
int fdset_steal_first(FDSet *fds) {
void *p;
p = set_steal_first(MAKE_SET(fds));
if (!p)
return -ENOENT;
return PTR_TO_FD(p);
}
| 7,581 | 23.777778 | 120 |
c
|
null |
systemd-main/src/shared/fdset.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "hashmap.h"
#include "macro.h"
#include "set.h"
typedef struct FDSet FDSet;
FDSet* fdset_new(void);
FDSet* fdset_free(FDSet *s);
int fdset_put(FDSet *s, int fd);
int fdset_consume(FDSet *s, int fd);
int fdset_put_dup(FDSet *s, int fd);
bool fdset_contains(FDSet *s, int fd);
int fdset_remove(FDSet *s, int fd);
int fdset_new_array(FDSet **ret, const int *fds, size_t n_fds);
int fdset_new_fill(int filter_cloexec, FDSet **ret);
int fdset_new_listen_fds(FDSet **ret, bool unset);
int fdset_cloexec(FDSet *fds, bool b);
int fdset_to_array(FDSet *fds, int **ret);
int fdset_close_others(FDSet *fds);
unsigned fdset_size(FDSet *fds);
bool fdset_isempty(FDSet *fds);
int fdset_iterate(FDSet *s, Iterator *i);
int fdset_steal_first(FDSet *fds);
void fdset_close(FDSet *fds);
#define _FDSET_FOREACH(fd, fds, i) \
for (Iterator i = ITERATOR_FIRST; ((fd) = fdset_iterate((fds), &i)) >= 0; )
#define FDSET_FOREACH(fd, fds) \
_FDSET_FOREACH(fd, fds, UNIQ_T(i, UNIQ))
DEFINE_TRIVIAL_CLEANUP_FUNC(FDSet*, fdset_free);
#define _cleanup_fdset_free_ _cleanup_(fdset_freep)
| 1,181 | 23.625 | 83 |
h
|
null |
systemd-main/src/shared/fileio-label.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <sys/stat.h>
#include "fileio-label.h"
#include "fileio.h"
#include "selinux-util.h"
int write_string_file_atomic_label_ts(const char *fn, const char *line, struct timespec *ts) {
int r;
r = mac_selinux_create_file_prepare(fn, S_IFREG);
if (r < 0)
return r;
r = write_string_file_ts(fn, line, WRITE_STRING_FILE_CREATE|WRITE_STRING_FILE_ATOMIC, ts);
mac_selinux_create_file_clear();
return r;
}
int create_shutdown_run_nologin_or_warn(void) {
int r;
/* This is used twice: once in systemd-user-sessions.service, in order to block logins when we
* actually go down, and once in systemd-logind.service when shutdowns are scheduled, and logins are
* to be turned off a bit in advance. We use the same wording of the message in both cases.
*
* Traditionally, there was only /etc/nologin, and we managed that. Then, in PAM 1.1
* support for /run/nologin was added as alternative
* (https://github.com/linux-pam/linux-pam/commit/e9e593f6ddeaf975b7fe8446d184e6bc387d450b).
* 13 years later we stopped managing /etc/nologin, leaving it for the administrator to manage.
*/
r = write_string_file_atomic_label("/run/nologin",
"System is going down. Unprivileged users are not permitted to log in anymore. "
"For technical details, see pam_nologin(8).");
if (r < 0)
return log_error_errno(r, "Failed to create /run/nologin: %m");
return 0;
}
| 1,676 | 37.113636 | 123 |
c
|
null |
systemd-main/src/shared/fileio-label.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdio.h>
/* These functions are split out of fileio.h (and not for example just flags to the functions they wrap) in order to
* optimize linking: This way, -lselinux is needed only for the callers of these functions that need selinux, but not
* for all */
int write_string_file_atomic_label_ts(const char *fn, const char *line, struct timespec *ts);
static inline int write_string_file_atomic_label(const char *fn, const char *line) {
return write_string_file_atomic_label_ts(fn, line, NULL);
}
int create_shutdown_run_nologin_or_warn(void);
| 628 | 38.3125 | 117 |
h
|
null |
systemd-main/src/shared/firewall-util-iptables.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/* Temporary work-around for broken glibc vs. linux kernel header definitions
* This is already fixed upstream, remove this when distributions have updated.
*/
#define _NET_IF_H 1
#include <arpa/inet.h>
#include <endian.h>
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include <net/if.h>
#ifndef IFNAMSIZ
#define IFNAMSIZ 16
#endif
#include <linux/if.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/netfilter/nf_nat.h>
#include <linux/netfilter/xt_addrtype.h>
#include <libiptc/libiptc.h>
#include "alloc-util.h"
#include "firewall-util.h"
#include "firewall-util-private.h"
#include "in-addr-util.h"
#include "macro.h"
#include "socket-util.h"
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct xtc_handle*, iptc_free, NULL);
static int entry_fill_basics(
struct ipt_entry *entry,
int protocol,
const char *in_interface,
const union in_addr_union *source,
unsigned source_prefixlen,
const char *out_interface,
const union in_addr_union *destination,
unsigned destination_prefixlen) {
assert(entry);
if (out_interface && !ifname_valid(out_interface))
return -EINVAL;
if (in_interface && !ifname_valid(in_interface))
return -EINVAL;
entry->ip.proto = protocol;
if (in_interface) {
size_t l;
l = strlen(in_interface);
assert(l < sizeof entry->ip.iniface);
assert(l < sizeof entry->ip.iniface_mask);
strcpy(entry->ip.iniface, in_interface);
memset(entry->ip.iniface_mask, 0xFF, l + 1);
}
if (source) {
entry->ip.src = source->in;
in4_addr_prefixlen_to_netmask(&entry->ip.smsk, source_prefixlen);
}
if (out_interface) {
size_t l = strlen(out_interface);
assert(l < sizeof entry->ip.outiface);
assert(l < sizeof entry->ip.outiface_mask);
strcpy(entry->ip.outiface, out_interface);
memset(entry->ip.outiface_mask, 0xFF, l + 1);
}
if (destination) {
entry->ip.dst = destination->in;
in4_addr_prefixlen_to_netmask(&entry->ip.dmsk, destination_prefixlen);
}
return 0;
}
int fw_iptables_add_masquerade(
bool add,
int af,
const union in_addr_union *source,
unsigned source_prefixlen) {
static const xt_chainlabel chain = "POSTROUTING";
_cleanup_(iptc_freep) struct xtc_handle *h = NULL;
struct ipt_entry *entry, *mask;
struct ipt_entry_target *t;
size_t sz;
struct nf_nat_ipv4_multi_range_compat *mr;
int r, protocol = 0;
const char *out_interface = NULL;
const union in_addr_union *destination = NULL;
unsigned destination_prefixlen = 0;
if (af != AF_INET)
return -EOPNOTSUPP;
if (!source || source_prefixlen == 0)
return -EINVAL;
r = fw_iptables_init_nat(&h);
if (r < 0)
return r;
sz = XT_ALIGN(sizeof(struct ipt_entry)) +
XT_ALIGN(sizeof(struct ipt_entry_target)) +
XT_ALIGN(sizeof(struct nf_nat_ipv4_multi_range_compat));
/* Put together the entry we want to add or remove */
entry = alloca0(sz);
entry->next_offset = sz;
entry->target_offset = XT_ALIGN(sizeof(struct ipt_entry));
r = entry_fill_basics(entry, protocol, NULL, source, source_prefixlen, out_interface, destination, destination_prefixlen);
if (r < 0)
return r;
/* Fill in target part */
t = ipt_get_target(entry);
t->u.target_size =
XT_ALIGN(sizeof(struct ipt_entry_target)) +
XT_ALIGN(sizeof(struct nf_nat_ipv4_multi_range_compat));
strncpy(t->u.user.name, "MASQUERADE", sizeof(t->u.user.name));
mr = (struct nf_nat_ipv4_multi_range_compat*) t->data;
mr->rangesize = 1;
/* Create a search mask entry */
mask = alloca_safe(sz);
memset(mask, 0xFF, sz);
if (add) {
if (iptc_check_entry(chain, entry, (unsigned char*) mask, h))
return 0;
if (errno != ENOENT) /* if other error than not existing yet, fail */
return -errno;
if (!iptc_insert_entry(chain, entry, 0, h))
return -errno;
} else {
if (!iptc_delete_entry(chain, entry, (unsigned char*) mask, h)) {
if (errno == ENOENT) /* if it's already gone, all is good! */
return 0;
return -errno;
}
}
if (!iptc_commit(h))
return -errno;
return 0;
}
int fw_iptables_add_local_dnat(
bool add,
int af,
int protocol,
uint16_t local_port,
const union in_addr_union *remote,
uint16_t remote_port,
const union in_addr_union *previous_remote) {
static const xt_chainlabel chain_pre = "PREROUTING", chain_output = "OUTPUT";
_cleanup_(iptc_freep) struct xtc_handle *h = NULL;
struct ipt_entry *entry, *mask;
struct ipt_entry_target *t;
struct ipt_entry_match *m;
struct xt_addrtype_info_v1 *at;
struct nf_nat_ipv4_multi_range_compat *mr;
size_t sz, msz;
int r;
const char *in_interface = NULL;
const union in_addr_union *source = NULL;
unsigned source_prefixlen = 0;
const union in_addr_union *destination = NULL;
unsigned destination_prefixlen = 0;
assert(add || !previous_remote);
if (af != AF_INET)
return -EOPNOTSUPP;
if (!IN_SET(protocol, IPPROTO_TCP, IPPROTO_UDP))
return -EOPNOTSUPP;
if (local_port <= 0)
return -EINVAL;
if (remote_port <= 0)
return -EINVAL;
r = fw_iptables_init_nat(&h);
if (r < 0)
return r;
sz = XT_ALIGN(sizeof(struct ipt_entry)) +
XT_ALIGN(sizeof(struct ipt_entry_match)) +
XT_ALIGN(sizeof(struct xt_addrtype_info_v1)) +
XT_ALIGN(sizeof(struct ipt_entry_target)) +
XT_ALIGN(sizeof(struct nf_nat_ipv4_multi_range_compat));
if (protocol == IPPROTO_TCP)
msz = XT_ALIGN(sizeof(struct ipt_entry_match)) +
XT_ALIGN(sizeof(struct xt_tcp));
else
msz = XT_ALIGN(sizeof(struct ipt_entry_match)) +
XT_ALIGN(sizeof(struct xt_udp));
sz += msz;
/* Fill in basic part */
entry = alloca0(sz);
entry->next_offset = sz;
entry->target_offset =
XT_ALIGN(sizeof(struct ipt_entry)) +
XT_ALIGN(sizeof(struct ipt_entry_match)) +
XT_ALIGN(sizeof(struct xt_addrtype_info_v1)) +
msz;
r = entry_fill_basics(entry, protocol, in_interface, source, source_prefixlen, NULL, destination, destination_prefixlen);
if (r < 0)
return r;
/* Fill in first match */
m = (struct ipt_entry_match*) ((uint8_t*) entry + XT_ALIGN(sizeof(struct ipt_entry)));
m->u.match_size = msz;
if (protocol == IPPROTO_TCP) {
struct xt_tcp *tcp;
strncpy(m->u.user.name, "tcp", sizeof(m->u.user.name));
tcp = (struct xt_tcp*) m->data;
tcp->dpts[0] = tcp->dpts[1] = local_port;
tcp->spts[0] = 0;
tcp->spts[1] = 0xFFFF;
} else {
struct xt_udp *udp;
strncpy(m->u.user.name, "udp", sizeof(m->u.user.name));
udp = (struct xt_udp*) m->data;
udp->dpts[0] = udp->dpts[1] = local_port;
udp->spts[0] = 0;
udp->spts[1] = 0xFFFF;
}
/* Fill in second match */
m = (struct ipt_entry_match*) ((uint8_t*) entry + XT_ALIGN(sizeof(struct ipt_entry)) + msz);
m->u.match_size =
XT_ALIGN(sizeof(struct ipt_entry_match)) +
XT_ALIGN(sizeof(struct xt_addrtype_info_v1));
strncpy(m->u.user.name, "addrtype", sizeof(m->u.user.name));
m->u.user.revision = 1;
at = (struct xt_addrtype_info_v1*) m->data;
at->dest = XT_ADDRTYPE_LOCAL;
/* Fill in target part */
t = ipt_get_target(entry);
t->u.target_size =
XT_ALIGN(sizeof(struct ipt_entry_target)) +
XT_ALIGN(sizeof(struct nf_nat_ipv4_multi_range_compat));
strncpy(t->u.user.name, "DNAT", sizeof(t->u.user.name));
mr = (struct nf_nat_ipv4_multi_range_compat*) t->data;
mr->rangesize = 1;
mr->range[0].flags = NF_NAT_RANGE_PROTO_SPECIFIED|NF_NAT_RANGE_MAP_IPS;
mr->range[0].min_ip = mr->range[0].max_ip = remote->in.s_addr;
if (protocol == IPPROTO_TCP)
mr->range[0].min.tcp.port = mr->range[0].max.tcp.port = htobe16(remote_port);
else
mr->range[0].min.udp.port = mr->range[0].max.udp.port = htobe16(remote_port);
mask = alloca0(sz);
memset(mask, 0xFF, sz);
if (add) {
/* Add the PREROUTING rule, if it is missing so far */
if (!iptc_check_entry(chain_pre, entry, (unsigned char*) mask, h)) {
if (errno != ENOENT)
return -EINVAL;
if (!iptc_insert_entry(chain_pre, entry, 0, h))
return -errno;
}
/* If a previous remote is set, remove its entry */
if (previous_remote && previous_remote->in.s_addr != remote->in.s_addr) {
mr->range[0].min_ip = mr->range[0].max_ip = previous_remote->in.s_addr;
if (!iptc_delete_entry(chain_pre, entry, (unsigned char*) mask, h)) {
if (errno != ENOENT)
return -errno;
}
mr->range[0].min_ip = mr->range[0].max_ip = remote->in.s_addr;
}
/* Add the OUTPUT rule, if it is missing so far */
if (!in_interface) {
/* Don't apply onto loopback addresses */
if (!destination) {
entry->ip.dst.s_addr = htobe32(0x7F000000);
entry->ip.dmsk.s_addr = htobe32(0xFF000000);
entry->ip.invflags = IPT_INV_DSTIP;
}
if (!iptc_check_entry(chain_output, entry, (unsigned char*) mask, h)) {
if (errno != ENOENT)
return -errno;
if (!iptc_insert_entry(chain_output, entry, 0, h))
return -errno;
}
/* If a previous remote is set, remove its entry */
if (previous_remote && previous_remote->in.s_addr != remote->in.s_addr) {
mr->range[0].min_ip = mr->range[0].max_ip = previous_remote->in.s_addr;
if (!iptc_delete_entry(chain_output, entry, (unsigned char*) mask, h)) {
if (errno != ENOENT)
return -errno;
}
}
}
} else {
if (!iptc_delete_entry(chain_pre, entry, (unsigned char*) mask, h)) {
if (errno != ENOENT)
return -errno;
}
if (!in_interface) {
if (!destination) {
entry->ip.dst.s_addr = htobe32(0x7F000000);
entry->ip.dmsk.s_addr = htobe32(0xFF000000);
entry->ip.invflags = IPT_INV_DSTIP;
}
if (!iptc_delete_entry(chain_output, entry, (unsigned char*) mask, h)) {
if (errno != ENOENT)
return -errno;
}
}
}
if (!iptc_commit(h))
return -errno;
return 0;
}
int fw_iptables_init_nat(struct xtc_handle **ret) {
_cleanup_(iptc_freep) struct xtc_handle *h = NULL;
h = iptc_init("nat");
if (!h)
return log_debug_errno(errno, "Failed to init \"nat\" table: %s", iptc_strerror(errno));
if (ret)
*ret = TAKE_PTR(h);
return 0;
}
| 13,248 | 35.398352 | 130 |
c
|
null |
systemd-main/src/shared/firewall-util-private.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "sd-netlink.h"
#include "in-addr-util.h"
typedef enum FirewallBackend {
FW_BACKEND_NONE,
#if HAVE_LIBIPTC
FW_BACKEND_IPTABLES,
#endif
FW_BACKEND_NFTABLES,
_FW_BACKEND_MAX,
_FW_BACKEND_INVALID = -EINVAL,
} FirewallBackend;
struct FirewallContext {
FirewallBackend backend;
sd_netlink *nfnl;
};
const char *firewall_backend_to_string(FirewallBackend b) _const_;
int fw_nftables_init(FirewallContext *ctx);
void fw_nftables_exit(FirewallContext *ctx);
int fw_nftables_add_masquerade(
FirewallContext *ctx,
bool add,
int af,
const union in_addr_union *source,
unsigned source_prefixlen);
int fw_nftables_add_local_dnat(
FirewallContext *ctx,
bool add,
int af,
int protocol,
uint16_t local_port,
const union in_addr_union *remote,
uint16_t remote_port,
const union in_addr_union *previous_remote);
#if HAVE_LIBIPTC
struct xtc_handle;
int fw_iptables_add_masquerade(
bool add,
int af,
const union in_addr_union *source,
unsigned source_prefixlen);
int fw_iptables_add_local_dnat(
bool add,
int af,
int protocol,
uint16_t local_port,
const union in_addr_union *remote,
uint16_t remote_port,
const union in_addr_union *previous_remote);
int fw_iptables_init_nat(struct xtc_handle **ret);
#endif
| 1,752 | 24.779412 | 66 |
h
|
null |
systemd-main/src/shared/firewall-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stddef.h>
#include <string.h>
#include "alloc-util.h"
#include "firewall-util.h"
#include "firewall-util-private.h"
#include "log.h"
#include "string-table.h"
static const char * const firewall_backend_table[_FW_BACKEND_MAX] = {
[FW_BACKEND_NONE] = "none",
#if HAVE_LIBIPTC
[FW_BACKEND_IPTABLES] = "iptables",
#endif
[FW_BACKEND_NFTABLES] = "nftables",
};
DEFINE_STRING_TABLE_LOOKUP_TO_STRING(firewall_backend, FirewallBackend);
static void firewall_backend_probe(FirewallContext *ctx) {
assert(ctx);
if (ctx->backend != _FW_BACKEND_INVALID)
return;
if (fw_nftables_init(ctx) >= 0)
ctx->backend = FW_BACKEND_NFTABLES;
else
#if HAVE_LIBIPTC
ctx->backend = FW_BACKEND_IPTABLES;
#else
ctx->backend = FW_BACKEND_NONE;
#endif
if (ctx->backend != FW_BACKEND_NONE)
log_debug("Using %s as firewall backend.", firewall_backend_to_string(ctx->backend));
else
log_debug("No firewall backend found.");
}
int fw_ctx_new(FirewallContext **ret) {
_cleanup_free_ FirewallContext *ctx = NULL;
ctx = new(FirewallContext, 1);
if (!ctx)
return -ENOMEM;
*ctx = (FirewallContext) {
.backend = _FW_BACKEND_INVALID,
};
firewall_backend_probe(ctx);
*ret = TAKE_PTR(ctx);
return 0;
}
FirewallContext *fw_ctx_free(FirewallContext *ctx) {
if (!ctx)
return NULL;
fw_nftables_exit(ctx);
return mfree(ctx);
}
int fw_add_masquerade(
FirewallContext **ctx,
bool add,
int af,
const union in_addr_union *source,
unsigned source_prefixlen) {
int r;
assert(ctx);
if (!*ctx) {
r = fw_ctx_new(ctx);
if (r < 0)
return r;
}
switch ((*ctx)->backend) {
#if HAVE_LIBIPTC
case FW_BACKEND_IPTABLES:
return fw_iptables_add_masquerade(add, af, source, source_prefixlen);
#endif
case FW_BACKEND_NFTABLES:
return fw_nftables_add_masquerade(*ctx, add, af, source, source_prefixlen);
default:
return -EOPNOTSUPP;
}
}
int fw_add_local_dnat(
FirewallContext **ctx,
bool add,
int af,
int protocol,
uint16_t local_port,
const union in_addr_union *remote,
uint16_t remote_port,
const union in_addr_union *previous_remote) {
int r;
assert(ctx);
if (!*ctx) {
r = fw_ctx_new(ctx);
if (r < 0)
return r;
}
switch ((*ctx)->backend) {
#if HAVE_LIBIPTC
case FW_BACKEND_IPTABLES:
return fw_iptables_add_local_dnat(add, af, protocol, local_port, remote, remote_port, previous_remote);
#endif
case FW_BACKEND_NFTABLES:
return fw_nftables_add_local_dnat(*ctx, add, af, protocol, local_port, remote, remote_port, previous_remote);
default:
return -EOPNOTSUPP;
}
}
| 3,362 | 24.869231 | 125 |
c
|
null |
systemd-main/src/shared/firewall-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stdint.h>
#include "in-addr-util.h"
typedef struct FirewallContext FirewallContext;
int fw_ctx_new(FirewallContext **ret);
FirewallContext *fw_ctx_free(FirewallContext *ctx);
DEFINE_TRIVIAL_CLEANUP_FUNC(FirewallContext *, fw_ctx_free);
int fw_add_masquerade(
FirewallContext **ctx,
bool add,
int af,
const union in_addr_union *source,
unsigned source_prefixlen);
int fw_add_local_dnat(
FirewallContext **ctx,
bool add,
int af,
int protocol,
uint16_t local_port,
const union in_addr_union *remote,
uint16_t remote_port,
const union in_addr_union *previous_remote);
| 872 | 26.28125 | 60 |
h
|
null |
systemd-main/src/shared/fstab-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include "alloc-util.h"
#include "device-nodes.h"
#include "fstab-util.h"
#include "initrd-util.h"
#include "macro.h"
#include "mount-util.h"
#include "nulstr-util.h"
#include "parse-util.h"
#include "path-util.h"
#include "string-util.h"
#include "strv.h"
int fstab_has_fstype(const char *fstype) {
_cleanup_endmntent_ FILE *f = NULL;
struct mntent *m;
assert(fstype);
f = setmntent(fstab_path(), "re");
if (!f)
return errno == ENOENT ? false : -errno;
for (;;) {
errno = 0;
m = getmntent(f);
if (!m)
return errno != 0 ? -errno : false;
if (streq(m->mnt_type, fstype))
return true;
}
return false;
}
bool fstab_is_extrinsic(const char *mount, const char *opts) {
/* Don't bother with the OS data itself */
if (PATH_IN_SET(mount,
"/",
"/usr",
"/etc"))
return true;
if (PATH_STARTSWITH_SET(mount,
"/run/initramfs", /* This should stay around from before we boot until after we shutdown */
"/run/nextroot", /* Similar (though might be updated from the host) */
"/proc", /* All of this is API VFS */
"/sys", /* … dito … */
"/dev")) /* … dito … */
return true;
/* If this is an initrd mount, and we are not in the initrd, then leave
* this around forever, too. */
if (fstab_test_option(opts, "x-initrd.mount\0") && !in_initrd())
return true;
return false;
}
int fstab_is_mount_point(const char *mount) {
_cleanup_endmntent_ FILE *f = NULL;
struct mntent *m;
f = setmntent(fstab_path(), "re");
if (!f)
return errno == ENOENT ? false : -errno;
for (;;) {
errno = 0;
m = getmntent(f);
if (!m)
return errno != 0 ? -errno : false;
if (path_equal(m->mnt_dir, mount))
return true;
}
return false;
}
int fstab_filter_options(
const char *opts,
const char *names,
const char **ret_namefound,
char **ret_value,
char ***ret_values,
char **ret_filtered) {
const char *namefound = NULL, *x;
_cleanup_strv_free_ char **stor = NULL, **values = NULL;
_cleanup_free_ char *value = NULL, **filtered = NULL;
int r;
assert(names && *names);
assert(!(ret_value && ret_values));
if (!opts)
goto answer;
/* Finds any options matching 'names', and returns:
* - the last matching option name in ret_namefound,
* - the last matching value in ret_value,
* - any matching values in ret_values,
* - the rest of the option string in ret_filtered.
*
* If !ret_value and !ret_values and !ret_filtered, this function is not allowed to fail.
*
* Returns negative on error, true if any matching options were found, false otherwise. */
if (ret_filtered || ret_value || ret_values) {
/* For backwards compatibility, we need to pass-through escape characters.
* The only ones we "consume" are the ones used as "\," or "\\". */
r = strv_split_full(&stor, opts, ",", EXTRACT_UNESCAPE_SEPARATORS | EXTRACT_UNESCAPE_RELAX);
if (r < 0)
return r;
filtered = memdup(stor, sizeof(char*) * (strv_length(stor) + 1));
if (!filtered)
return -ENOMEM;
char **t = filtered;
for (char **s = t; *s; s++) {
NULSTR_FOREACH(name, names) {
x = startswith(*s, name);
if (!x)
continue;
/* Match name, but when ret_values, only when followed by assignment. */
if (*x == '=' || (!ret_values && *x == '\0')) {
/* Keep the last occurrence found */
namefound = name;
goto found;
}
}
*t = *s;
t++;
continue;
found:
if (ret_value || ret_values) {
assert(IN_SET(*x, '=', '\0'));
if (ret_value) {
r = free_and_strdup(&value, *x == '=' ? x + 1 : NULL);
if (r < 0)
return r;
} else if (*x) {
r = strv_extend(&values, x + 1);
if (r < 0)
return r;
}
}
}
*t = NULL;
} else
for (const char *word = opts;;) {
const char *end = word;
/* Look for a *non-escaped* comma separator. Only commas and backslashes can be
* escaped, so "\," and "\\" are the only valid escape sequences, and we can do a
* very simple test here. */
for (;;) {
end += strcspn(end, ",\\");
if (IN_SET(*end, ',', '\0'))
break;
assert(*end == '\\');
end ++; /* Skip the backslash */
if (*end != '\0')
end ++; /* Skip the escaped char, but watch out for a trailing comma */
}
NULSTR_FOREACH(name, names) {
if (end < word + strlen(name))
continue;
if (!strneq(word, name, strlen(name)))
continue;
/* We know that the string is NUL terminated, so *x is valid */
x = word + strlen(name);
if (IN_SET(*x, '\0', '=', ',')) {
namefound = name;
break;
}
}
if (*end)
word = end + 1;
else
break;
}
answer:
if (ret_namefound)
*ret_namefound = namefound;
if (ret_filtered) {
char *f;
f = strv_join_full(filtered, ",", NULL, true);
if (!f)
return -ENOMEM;
*ret_filtered = f;
}
if (ret_value)
*ret_value = TAKE_PTR(value);
if (ret_values)
*ret_values = TAKE_PTR(values);
return !!namefound;
}
int fstab_find_pri(const char *options, int *ret) {
_cleanup_free_ char *opt = NULL;
int r, pri;
assert(ret);
r = fstab_filter_options(options, "pri\0", NULL, &opt, NULL, NULL);
if (r < 0)
return r;
if (r == 0 || !opt)
return 0;
r = safe_atoi(opt, &pri);
if (r < 0)
return r;
*ret = pri;
return 1;
}
static char *unquote(const char *s, const char* quotes) {
size_t l;
assert(s);
/* This is rather stupid, simply removes the heading and
* trailing quotes if there is one. Doesn't care about
* escaping or anything.
*
* DON'T USE THIS FOR NEW CODE ANYMORE! */
l = strlen(s);
if (l < 2)
return strdup(s);
if (strchr(quotes, s[0]) && s[l-1] == s[0])
return strndup(s+1, l-2);
return strdup(s);
}
static char *tag_to_udev_node(const char *tagvalue, const char *by) {
_cleanup_free_ char *t = NULL, *u = NULL;
size_t enc_len;
u = unquote(tagvalue, QUOTES);
if (!u)
return NULL;
enc_len = strlen(u) * 4 + 1;
t = new(char, enc_len);
if (!t)
return NULL;
if (encode_devnode_name(u, t, enc_len) < 0)
return NULL;
return strjoin("/dev/disk/by-", by, "/", t);
}
char *fstab_node_to_udev_node(const char *p) {
assert(p);
if (startswith(p, "LABEL="))
return tag_to_udev_node(p+6, "label");
if (startswith(p, "UUID="))
return tag_to_udev_node(p+5, "uuid");
if (startswith(p, "PARTUUID="))
return tag_to_udev_node(p+9, "partuuid");
if (startswith(p, "PARTLABEL="))
return tag_to_udev_node(p+10, "partlabel");
return strdup(p);
}
bool fstab_is_bind(const char *options, const char *fstype) {
if (fstab_test_option(options, "bind\0" "rbind\0"))
return true;
if (fstype && STR_IN_SET(fstype, "bind", "rbind"))
return true;
return false;
}
| 10,049 | 32.059211 | 126 |
c
|
null |
systemd-main/src/shared/fstab-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stddef.h>
#include "macro.h"
bool fstab_is_extrinsic(const char *mount, const char *opts);
int fstab_is_mount_point(const char *mount);
int fstab_has_fstype(const char *fstype);
int fstab_filter_options(
const char *opts,
const char *names,
const char **ret_namefound,
char **ret_value,
char ***ret_values,
char **ret_filtered);
static inline bool fstab_test_option(const char *opts, const char *names) {
return !!fstab_filter_options(opts, names, NULL, NULL, NULL, NULL);
}
int fstab_find_pri(const char *options, int *ret);
static inline bool fstab_test_yes_no_option(const char *opts, const char *yes_no) {
const char *opt;
/* If first name given is last, return 1.
* If second name given is last or neither is found, return 0. */
assert_se(fstab_filter_options(opts, yes_no, &opt, NULL, NULL, NULL) >= 0);
return opt == yes_no;
}
char *fstab_node_to_udev_node(const char *p);
static inline const char* fstab_path(void) {
return secure_getenv("SYSTEMD_FSTAB") ?: "/etc/fstab";
}
bool fstab_is_bind(const char *options, const char *fstype);
| 1,302 | 27.955556 | 83 |
h
|
null |
systemd-main/src/shared/generator.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdio.h>
#include "macro.h"
#include "main-func.h"
int generator_open_unit_file_full(const char *dest, const char *source, const char *name, FILE **ret_file, char **ret_temp_path);
static inline int generator_open_unit_file(const char *dest, const char *source, const char *name, FILE **ret_file) {
return generator_open_unit_file_full(dest, source, name, ret_file, NULL);
}
int generator_add_symlink_full(const char *dir, const char *dst, const char *dep_type, const char *src, const char *instance);
static inline int generator_add_symlink(const char *dir, const char *dst, const char *dep_type, const char *src) {
return generator_add_symlink_full(dir, dst, dep_type, src, NULL);
}
int generator_write_fsck_deps(
FILE *f,
const char *dir,
const char *what,
const char *where,
const char *type);
int generator_write_timeouts(
const char *dir,
const char *what,
const char *where,
const char *opts,
char **filtered);
int generator_write_blockdev_dependency(
FILE *f,
const char *what);
int generator_write_cryptsetup_unit_section(
FILE *f,
const char *source);
int generator_write_cryptsetup_service_section(
FILE *f,
const char *name,
const char *what,
const char *password,
const char *options);
int generator_write_veritysetup_unit_section(
FILE *f,
const char *source);
int generator_write_veritysetup_service_section(
FILE *f,
const char *name,
const char *data_what,
const char *hash_what,
const char *roothash,
const char *options);
int generator_write_device_deps(
const char *dir,
const char *what,
const char *where,
const char *opts);
int generator_write_initrd_root_device_deps(
const char *dir,
const char *what);
int generator_hook_up_mkswap(
const char *dir,
const char *what);
int generator_hook_up_mkfs(
const char *dir,
const char *what,
const char *where,
const char *type);
int generator_hook_up_growfs(
const char *dir,
const char *where,
const char *target);
int generator_hook_up_pcrfs(
const char *dir,
const char *where,
const char *target);
int generator_enable_remount_fs_service(const char *dir);
void log_setup_generator(void);
/* Similar to DEFINE_MAIN_FUNCTION, but initializes logging and assigns positional arguments. */
#define DEFINE_MAIN_GENERATOR_FUNCTION(impl) \
_DEFINE_MAIN_FUNCTION( \
({ \
log_setup_generator(); \
if (!IN_SET(argc, 2, 4)) \
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), \
"This program takes one or three arguments."); \
}), \
impl(argv[1], \
argv[argc == 4 ? 2 : 1], \
argv[argc == 4 ? 3 : 1]), \
r < 0 ? EXIT_FAILURE : EXIT_SUCCESS)
| 3,663 | 33.566038 | 129 |
h
|
null |
systemd-main/src/shared/gpt.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-gpt.h"
#include "sd-id128.h"
#include "architecture.h"
#include "id128-util.h"
/* maximum length of gpt label */
#define GPT_LABEL_MAX 36
typedef enum PartitionDesignator {
PARTITION_ROOT, /* Primary architecture */
PARTITION_USR,
PARTITION_HOME,
PARTITION_SRV,
PARTITION_ESP,
PARTITION_XBOOTLDR,
PARTITION_SWAP,
PARTITION_ROOT_VERITY, /* verity data for the PARTITION_ROOT partition */
PARTITION_USR_VERITY,
PARTITION_ROOT_VERITY_SIG, /* PKCS#7 signature for root hash for the PARTITION_ROOT partition */
PARTITION_USR_VERITY_SIG,
PARTITION_TMP,
PARTITION_VAR,
_PARTITION_DESIGNATOR_MAX,
_PARTITION_DESIGNATOR_INVALID = -EINVAL,
} PartitionDesignator;
bool partition_designator_is_versioned(PartitionDesignator d);
PartitionDesignator partition_verity_of(PartitionDesignator p);
PartitionDesignator partition_verity_sig_of(PartitionDesignator p);
PartitionDesignator partition_verity_to_data(PartitionDesignator d);
PartitionDesignator partition_verity_sig_to_data(PartitionDesignator d);
const char* partition_designator_to_string(PartitionDesignator d) _const_;
PartitionDesignator partition_designator_from_string(const char *name) _pure_;
const char *gpt_partition_type_uuid_to_string(sd_id128_t id);
const char *gpt_partition_type_uuid_to_string_harder(
sd_id128_t id,
char buffer[static SD_ID128_UUID_STRING_MAX]);
#define GPT_PARTITION_TYPE_UUID_TO_STRING_HARDER(id) \
gpt_partition_type_uuid_to_string_harder((id), (char[SD_ID128_UUID_STRING_MAX]) {})
Architecture gpt_partition_type_uuid_to_arch(sd_id128_t id);
typedef struct GptPartitionType {
sd_id128_t uuid;
const char *name;
Architecture arch;
PartitionDesignator designator;
} GptPartitionType;
extern const GptPartitionType gpt_partition_type_table[];
int gpt_partition_label_valid(const char *s);
GptPartitionType gpt_partition_type_from_uuid(sd_id128_t id);
int gpt_partition_type_from_string(const char *s, GptPartitionType *ret);
GptPartitionType gpt_partition_type_override_architecture(GptPartitionType type, Architecture arch);
const char *gpt_partition_type_mountpoint_nulstr(GptPartitionType type);
bool gpt_partition_type_knows_read_only(GptPartitionType type);
bool gpt_partition_type_knows_growfs(GptPartitionType type);
bool gpt_partition_type_knows_no_auto(GptPartitionType type);
| 2,547 | 34.388889 | 104 |
h
|
null |
systemd-main/src/shared/group-record.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "json.h"
#include "user-record.h"
typedef struct GroupRecord {
unsigned n_ref;
UserRecordMask mask;
bool incomplete;
char *group_name;
char *realm;
char *group_name_and_realm_auto;
char *description;
UserDisposition disposition;
uint64_t last_change_usec;
gid_t gid;
char **members;
char *service;
/* The following exist mostly so that we can cover the full /etc/gshadow set of fields, we currently
* do not actually make use of these */
char **administrators; /* maps to 'struct sgrp' .sg_adm field */
char **hashed_password; /* maps to 'struct sgrp' .sg_passwd field */
JsonVariant *json;
} GroupRecord;
GroupRecord* group_record_new(void);
GroupRecord* group_record_ref(GroupRecord *g);
GroupRecord* group_record_unref(GroupRecord *g);
DEFINE_TRIVIAL_CLEANUP_FUNC(GroupRecord*, group_record_unref);
int group_record_load(GroupRecord *h, JsonVariant *v, UserRecordLoadFlags flags);
int group_record_build(GroupRecord **ret, ...);
int group_record_clone(GroupRecord *g, UserRecordLoadFlags flags, GroupRecord **ret);
const char *group_record_group_name_and_realm(GroupRecord *h);
UserDisposition group_record_disposition(GroupRecord *h);
| 1,362 | 28 | 108 |
h
|
null |
systemd-main/src/shared/hostname-setup.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/utsname.h>
#include <unistd.h>
#include "alloc-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "fs-util.h"
#include "hostname-setup.h"
#include "hostname-util.h"
#include "log.h"
#include "macro.h"
#include "proc-cmdline.h"
#include "string-table.h"
#include "string-util.h"
static int sethostname_idempotent_full(const char *s, bool really) {
struct utsname u;
assert(s);
assert_se(uname(&u) >= 0);
if (streq_ptr(s, u.nodename))
return 0;
if (really &&
sethostname(s, strlen(s)) < 0)
return -errno;
return 1;
}
int sethostname_idempotent(const char *s) {
return sethostname_idempotent_full(s, true);
}
int shorten_overlong(const char *s, char **ret) {
char *h, *p;
/* Shorten an overlong name to HOST_NAME_MAX or to the first dot,
* whatever comes earlier. */
assert(s);
h = strdup(s);
if (!h)
return -ENOMEM;
if (hostname_is_valid(h, 0)) {
*ret = h;
return 0;
}
p = strchr(h, '.');
if (p)
*p = 0;
strshorten(h, HOST_NAME_MAX);
if (!hostname_is_valid(h, 0)) {
free(h);
return -EDOM;
}
*ret = h;
return 1;
}
int read_etc_hostname_stream(FILE *f, char **ret) {
int r;
assert(f);
assert(ret);
for (;;) {
_cleanup_free_ char *line = NULL;
char *p;
r = read_line(f, LONG_LINE_MAX, &line);
if (r < 0)
return r;
if (r == 0) /* EOF without any hostname? the file is empty, let's treat that exactly like no file at all: ENOENT */
return -ENOENT;
p = strstrip(line);
/* File may have empty lines or comments, ignore them */
if (!IN_SET(*p, '\0', '#')) {
char *copy;
hostname_cleanup(p); /* normalize the hostname */
if (!hostname_is_valid(p, VALID_HOSTNAME_TRAILING_DOT)) /* check that the hostname we return is valid */
return -EBADMSG;
copy = strdup(p);
if (!copy)
return -ENOMEM;
*ret = copy;
return 0;
}
}
}
int read_etc_hostname(const char *path, char **ret) {
_cleanup_fclose_ FILE *f = NULL;
assert(ret);
if (!path)
path = "/etc/hostname";
f = fopen(path, "re");
if (!f)
return -errno;
return read_etc_hostname_stream(f, ret);
}
void hostname_update_source_hint(const char *hostname, HostnameSource source) {
int r;
/* Why save the value and not just create a flag file? This way we will
* notice if somebody sets the hostname directly (not going through hostnamed).
*/
if (source == HOSTNAME_DEFAULT) {
r = write_string_file("/run/systemd/default-hostname", hostname,
WRITE_STRING_FILE_CREATE | WRITE_STRING_FILE_ATOMIC);
if (r < 0)
log_warning_errno(r, "Failed to create \"/run/systemd/default-hostname\": %m");
} else
unlink_or_warn("/run/systemd/default-hostname");
}
int hostname_setup(bool really) {
_cleanup_free_ char *b = NULL;
const char *hn = NULL;
HostnameSource source;
bool enoent = false;
int r;
r = proc_cmdline_get_key("systemd.hostname", 0, &b);
if (r < 0)
log_warning_errno(r, "Failed to retrieve system hostname from kernel command line, ignoring: %m");
else if (r > 0) {
if (hostname_is_valid(b, VALID_HOSTNAME_TRAILING_DOT)) {
hn = b;
source = HOSTNAME_TRANSIENT;
} else {
log_warning("Hostname specified on kernel command line is invalid, ignoring: %s", b);
b = mfree(b);
}
}
if (!hn) {
r = read_etc_hostname(NULL, &b);
if (r < 0) {
if (r == -ENOENT)
enoent = true;
else
log_warning_errno(r, "Failed to read configured hostname: %m");
} else {
hn = b;
source = HOSTNAME_STATIC;
}
}
if (!hn) {
_cleanup_free_ char *buf = NULL;
/* Don't override the hostname if it is already set and not explicitly configured */
r = gethostname_full(GET_HOSTNAME_ALLOW_LOCALHOST, &buf);
if (r == -ENOMEM)
return log_oom();
if (r >= 0) {
log_debug("No hostname configured, leaving existing hostname <%s> in place.", buf);
return 0;
}
if (enoent)
log_info("No hostname configured, using default hostname.");
hn = b = get_default_hostname();
if (!hn)
return log_oom();
source = HOSTNAME_DEFAULT;
}
r = sethostname_idempotent_full(hn, really);
if (r < 0)
return log_warning_errno(r, "Failed to set hostname to <%s>: %m", hn);
if (r == 0)
log_debug("Hostname was already set to <%s>.", hn);
else
log_info("Hostname %s to <%s>.",
really ? "set" : "would have been set",
hn);
if (really)
hostname_update_source_hint(hn, source);
return r;
}
static const char* const hostname_source_table[] = {
[HOSTNAME_STATIC] = "static",
[HOSTNAME_TRANSIENT] = "transient",
[HOSTNAME_DEFAULT] = "default",
};
DEFINE_STRING_TABLE_LOOKUP(hostname_source, HostnameSource);
| 6,415 | 27.900901 | 131 |
c
|
null |
systemd-main/src/shared/hostname-setup.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include <stdio.h>
typedef enum HostnameSource {
HOSTNAME_STATIC, /* from /etc/hostname */
HOSTNAME_TRANSIENT, /* a transient hostname set through systemd, hostnamed, the container manager, or otherwise */
HOSTNAME_DEFAULT, /* the os-release default or the compiled-in fallback were used */
_HOSTNAME_INVALID = -EINVAL,
} HostnameSource;
const char* hostname_source_to_string(HostnameSource source) _const_;
HostnameSource hostname_source_from_string(const char *str) _pure_;
int sethostname_idempotent(const char *s);
int shorten_overlong(const char *s, char **ret);
int read_etc_hostname_stream(FILE *f, char **ret);
int read_etc_hostname(const char *path, char **ret);
void hostname_update_source_hint(const char *hostname, HostnameSource source);
int hostname_setup(bool really);
| 914 | 34.192308 | 123 |
h
|
null |
systemd-main/src/shared/id128-print.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdio.h>
#include "sd-id128.h"
#include "alloc-util.h"
#include "id128-print.h"
#include "log.h"
#include "pretty-print.h"
#include "terminal-util.h"
int id128_pretty_print_sample(const char *name, sd_id128_t id) {
_cleanup_free_ char *man_link = NULL, *mod_link = NULL;
const char *on, *off;
unsigned i;
on = ansi_highlight();
off = ansi_normal();
if (terminal_urlify("man:systemd-id128(1)", "systemd-id128(1)", &man_link) < 0)
return log_oom();
if (terminal_urlify("https://docs.python.org/3/library/uuid.html", "uuid", &mod_link) < 0)
return log_oom();
printf("As string:\n"
"%s" SD_ID128_FORMAT_STR "%s\n\n"
"As UUID:\n"
"%s" SD_ID128_UUID_FORMAT_STR "%s\n\n"
"As %s macro:\n"
"%s#define %s SD_ID128_MAKE(",
on, SD_ID128_FORMAT_VAL(id), off,
on, SD_ID128_FORMAT_VAL(id), off,
man_link,
on, name);
for (i = 0; i < 16; i++)
printf("%02x%s", id.bytes[i], i != 15 ? "," : "");
printf(")%s\n\n", off);
printf("As Python constant:\n"
">>> import %s\n"
">>> %s%s = uuid.UUID('" SD_ID128_FORMAT_STR "')%s\n",
mod_link,
on, name, SD_ID128_FORMAT_VAL(id), off);
return 0;
}
int id128_pretty_print(sd_id128_t id, Id128PrettyPrintMode mode) {
assert(mode >= 0);
assert(mode < _ID128_PRETTY_PRINT_MODE_MAX);
if (mode == ID128_PRINT_ID128) {
printf(SD_ID128_FORMAT_STR "\n",
SD_ID128_FORMAT_VAL(id));
return 0;
} else if (mode == ID128_PRINT_UUID) {
printf(SD_ID128_UUID_FORMAT_STR "\n",
SD_ID128_FORMAT_VAL(id));
return 0;
} else
return id128_pretty_print_sample("XYZ", id);
}
int id128_print_new(Id128PrettyPrintMode mode) {
sd_id128_t id;
int r;
r = sd_id128_randomize(&id);
if (r < 0)
return log_error_errno(r, "Failed to generate ID: %m");
return id128_pretty_print(id, mode);
}
| 2,309 | 29 | 98 |
c
|
null |
systemd-main/src/shared/id128-print.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "sd-id128.h"
typedef enum Id128PrettyPrintMode {
ID128_PRINT_ID128,
ID128_PRINT_UUID,
ID128_PRINT_PRETTY,
_ID128_PRETTY_PRINT_MODE_MAX,
_ID128_PRETTY_PRINT_MODE_INVALID = -EINVAL,
} Id128PrettyPrintMode;
int id128_pretty_print_sample(const char *name, sd_id128_t id);
int id128_pretty_print(sd_id128_t id, Id128PrettyPrintMode mode);
int id128_print_new(Id128PrettyPrintMode mode);
| 519 | 25 | 65 |
h
|
null |
systemd-main/src/shared/idn-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#if HAVE_LIBIDN2
# include <idn2.h>
#elif HAVE_LIBIDN
# include <idna.h>
# include <stringprep.h>
#endif
#include "alloc-util.h"
#include "dlfcn-util.h"
#include "idn-util.h"
#if HAVE_LIBIDN || HAVE_LIBIDN2
static void* idn_dl = NULL;
#endif
#if HAVE_LIBIDN2
int (*sym_idn2_lookup_u8)(const uint8_t* src, uint8_t** lookupname, int flags) = NULL;
const char *(*sym_idn2_strerror)(int rc) _const_ = NULL;
int (*sym_idn2_to_unicode_8z8z)(const char * input, char ** output, int flags) = NULL;
int dlopen_idn(void) {
return dlopen_many_sym_or_warn(
&idn_dl, "libidn2.so.0", LOG_DEBUG,
DLSYM_ARG(idn2_lookup_u8),
DLSYM_ARG(idn2_strerror),
DLSYM_ARG(idn2_to_unicode_8z8z));
}
#endif
#if HAVE_LIBIDN
int (*sym_idna_to_ascii_4i)(const uint32_t * in, size_t inlen, char *out, int flags);
int (*sym_idna_to_unicode_44i)(const uint32_t * in, size_t inlen, uint32_t * out, size_t * outlen, int flags);
char* (*sym_stringprep_ucs4_to_utf8)(const uint32_t * str, ssize_t len, size_t * items_read, size_t * items_written);
uint32_t* (*sym_stringprep_utf8_to_ucs4)(const char *str, ssize_t len, size_t *items_written);
int dlopen_idn(void) {
_cleanup_(dlclosep) void *dl = NULL;
int r;
if (idn_dl)
return 0; /* Already loaded */
dl = dlopen("libidn.so.12", RTLD_LAZY);
if (!dl) {
/* libidn broke ABI in 1.34, but not in a way we care about (a new field got added to an
* open-coded struct we do not use), hence support both versions. */
dl = dlopen("libidn.so.11", RTLD_LAZY);
if (!dl)
return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP),
"libidn support is not installed: %s", dlerror());
}
r = dlsym_many_or_warn(
dl,
LOG_DEBUG,
DLSYM_ARG(idna_to_ascii_4i),
DLSYM_ARG(idna_to_unicode_44i),
DLSYM_ARG(stringprep_ucs4_to_utf8),
DLSYM_ARG(stringprep_utf8_to_ucs4));
if (r < 0)
return r;
idn_dl = TAKE_PTR(dl);
return 1;
}
#endif
| 2,371 | 32.885714 | 117 |
c
|
null |
systemd-main/src/shared/idn-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#if HAVE_LIBIDN2
# include <idn2.h>
#elif HAVE_LIBIDN
# include <idna.h>
# include <stringprep.h>
#endif
#include <inttypes.h>
#if HAVE_LIBIDN2 || HAVE_LIBIDN
int dlopen_idn(void);
#else
static inline int dlopen_idn(void) {
return -EOPNOTSUPP;
}
#endif
#if HAVE_LIBIDN2
extern int (*sym_idn2_lookup_u8)(const uint8_t* src, uint8_t** lookupname, int flags);
extern const char *(*sym_idn2_strerror)(int rc) _const_;
extern int (*sym_idn2_to_unicode_8z8z)(const char * input, char ** output, int flags);
#endif
#if HAVE_LIBIDN
extern int (*sym_idna_to_ascii_4i)(const uint32_t * in, size_t inlen, char *out, int flags);
extern int (*sym_idna_to_unicode_44i)(const uint32_t * in, size_t inlen,uint32_t * out, size_t * outlen, int flags);
extern char* (*sym_stringprep_ucs4_to_utf8)(const uint32_t * str, ssize_t len, size_t * items_read, size_t * items_written);
extern uint32_t* (*sym_stringprep_utf8_to_ucs4)(const char *str, ssize_t len, size_t *items_written);
#endif
| 1,046 | 30.727273 | 124 |
h
|
null |
systemd-main/src/shared/import-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "macro.h"
typedef enum ImportVerify {
IMPORT_VERIFY_NO,
IMPORT_VERIFY_CHECKSUM,
IMPORT_VERIFY_SIGNATURE,
_IMPORT_VERIFY_MAX,
_IMPORT_VERIFY_INVALID = -EINVAL,
} ImportVerify;
int import_url_last_component(const char *url, char **ret);
int import_url_change_suffix(const char *url, size_t n_drop_components, const char *suffix, char **ret);
static inline int import_url_change_last_component(const char *url, const char *suffix, char **ret) {
return import_url_change_suffix(url, 1, suffix, ret);
}
static inline int import_url_append_component(const char *url, const char *suffix, char **ret) {
return import_url_change_suffix(url, 0, suffix, ret);
}
const char* import_verify_to_string(ImportVerify v) _const_;
ImportVerify import_verify_from_string(const char *s) _pure_;
int tar_strip_suffixes(const char *name, char **ret);
int raw_strip_suffixes(const char *name, char **ret);
int import_assign_pool_quota_and_warn(const char *path);
int import_set_nocow_and_log(int fd, const char *path);
| 1,154 | 30.216216 | 104 |
h
|
null |
systemd-main/src/shared/in-addr-prefix-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "conf-parser.h"
#include "in-addr-util.h"
#include "set.h"
struct in_addr_prefix {
int family;
uint8_t prefixlen;
union in_addr_union address;
};
int in_addr_prefix_add(Set **prefixes, const struct in_addr_prefix *prefix);
int in_addr_prefixes_reduce(Set *prefixes);
int in_addr_prefixes_merge(Set **dest, Set *src);
/* Returns true if a set contains the two items necessary for "any" (0.0.0.0/0 and ::/0). */
bool in_addr_prefixes_is_any(Set *prefixes);
extern const struct hash_ops in_addr_prefix_hash_ops;
extern const struct hash_ops in_addr_prefix_hash_ops_free;
CONFIG_PARSER_PROTOTYPE(config_parse_in_addr_prefixes);
| 724 | 29.208333 | 92 |
h
|
null |
systemd-main/src/shared/initreq.h
|
/* SPDX-License-Identifier: LGPL-2.0-or-later */
/*
* initreq.h Interface to talk to init through /dev/initctl.
*
* Copyright (C) 1995-2004 Miquel van Smoorenburg
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2 of the License, or (at your option) any later version.
*
* Version: @(#)initreq.h 1.28 31-Mar-2004 MvS
*/
#pragma once
#include <sys/param.h>
#if defined(__FreeBSD_kernel__)
# define INIT_FIFO "/etc/.initctl"
#else
# define INIT_FIFO "/dev/initctl"
#endif
#define INIT_MAGIC 0x03091969
#define INIT_CMD_START 0
#define INIT_CMD_RUNLVL 1
#define INIT_CMD_POWERFAIL 2
#define INIT_CMD_POWERFAILNOW 3
#define INIT_CMD_POWEROK 4
#define INIT_CMD_BSD 5
#define INIT_CMD_SETENV 6
#define INIT_CMD_UNSETENV 7
#define INIT_CMD_CHANGECONS 12345
#ifdef MAXHOSTNAMELEN
# define INITRQ_HLEN MAXHOSTNAMELEN
#else
# define INITRQ_HLEN 64
#endif
/*
* This is what BSD 4.4 uses when talking to init.
* Linux doesn't use this right now.
*/
struct init_request_bsd {
char gen_id[8]; /* Beats me.. telnetd uses "fe" */
char tty_id[16]; /* Tty name minus /dev/tty */
char host[INITRQ_HLEN]; /* Hostname */
char term_type[16]; /* Terminal type */
int signal; /* Signal to send */
int pid; /* Process to send to */
char exec_name[128]; /* Program to execute */
char reserved[128]; /* For future expansion. */
};
/*
* Because of legacy interfaces, "runlevel" and "sleeptime"
* aren't in a separate struct in the union.
*
* The weird sizes are because init expects the whole
* struct to be 384 bytes.
*/
struct init_request {
int magic; /* Magic number */
int cmd; /* What kind of request */
int runlevel; /* Runlevel to change to */
int sleeptime; /* Time between TERM and KILL */
union {
struct init_request_bsd bsd;
char data[368];
} i;
};
| 2,215 | 28.546667 | 71 |
h
|
null |
systemd-main/src/shared/install-file.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
int fs_make_very_read_only(int fd);
typedef enum InstallFileFlags {
INSTALL_REPLACE = 1 << 0, /* Replace an existing inode */
INSTALL_READ_ONLY = 1 << 1, /* Call fs_make_very_read_only() to make the inode comprehensively read-only */
INSTALL_FSYNC = 1 << 2, /* fsync() file contents before moving file in */
INSTALL_FSYNC_FULL = 1 << 3, /* like INSTALL_FSYNC, but also fsync() parent dir before+after moving file in */
INSTALL_SYNCFS = 1 << 4, /* syncfs() before moving file in, fsync() parent dir after moving file in */
} InstallFileFlags;
int install_file(int source_atfd, const char *source_name, int target_atfd, const char *target_name, InstallFileFlags flags);
| 786 | 51.466667 | 125 |
h
|
null |
systemd-main/src/shared/install-printf.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <stdio.h>
#include <unistd.h>
#include "format-util.h"
#include "install-printf.h"
#include "install.h"
#include "macro.h"
#include "specifier.h"
#include "string-util.h"
#include "unit-name.h"
#include "user-util.h"
static int specifier_prefix_and_instance(char specifier, const void *data, const char *root, const void *userdata, char **ret) {
const InstallInfo *i = ASSERT_PTR(userdata);
_cleanup_free_ char *prefix = NULL;
int r;
r = unit_name_to_prefix_and_instance(i->name, &prefix);
if (r < 0)
return r;
if (endswith(prefix, "@") && i->default_instance) {
char *ans;
ans = strjoin(prefix, i->default_instance);
if (!ans)
return -ENOMEM;
*ret = ans;
} else
*ret = TAKE_PTR(prefix);
return 0;
}
static int specifier_name(char specifier, const void *data, const char *root, const void *userdata, char **ret) {
const InstallInfo *i = ASSERT_PTR(userdata);
char *ans;
if (unit_name_is_valid(i->name, UNIT_NAME_TEMPLATE) && i->default_instance)
return unit_name_replace_instance(i->name, i->default_instance, ret);
ans = strdup(i->name);
if (!ans)
return -ENOMEM;
*ret = ans;
return 0;
}
static int specifier_prefix(char specifier, const void *data, const char *root, const void *userdata, char **ret) {
const InstallInfo *i = ASSERT_PTR(userdata);
return unit_name_to_prefix(i->name, ret);
}
static int specifier_instance(char specifier, const void *data, const char *root, const void *userdata, char **ret) {
const InstallInfo *i = ASSERT_PTR(userdata);
char *instance;
int r;
r = unit_name_to_instance(i->name, &instance);
if (r < 0)
return r;
if (isempty(instance)) {
r = free_and_strdup(&instance, strempty(i->default_instance));
if (r < 0)
return r;
}
*ret = instance;
return 0;
}
static int specifier_last_component(char specifier, const void *data, const char *root, const void *userdata, char **ret) {
_cleanup_free_ char *prefix = NULL;
char *dash;
int r;
assert(ret);
r = specifier_prefix(specifier, data, root, userdata, &prefix);
if (r < 0)
return r;
dash = strrchr(prefix, '-');
if (dash) {
dash = strdup(dash + 1);
if (!dash)
return -ENOMEM;
*ret = dash;
} else
*ret = TAKE_PTR(prefix);
return 0;
}
int install_name_printf(
RuntimeScope scope,
const InstallInfo *info,
const char *format,
char **ret) {
/* This is similar to unit_name_printf() */
const Specifier table[] = {
{ 'i', specifier_instance, NULL },
{ 'j', specifier_last_component, NULL },
{ 'n', specifier_name, NULL },
{ 'N', specifier_prefix_and_instance, NULL },
{ 'p', specifier_prefix, NULL },
COMMON_SYSTEM_SPECIFIERS,
COMMON_CREDS_SPECIFIERS(scope),
{}
};
assert(info);
assert(format);
assert(ret);
return specifier_printf(format, UNIT_NAME_MAX, table, info->root, info, ret);
}
| 3,676 | 28.18254 | 128 |
c
|
null |
systemd-main/src/shared/ip-protocol-list.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <netinet/in.h>
#include "alloc-util.h"
#include "ip-protocol-list.h"
#include "macro.h"
#include "parse-util.h"
#include "string-util.h"
static const struct ip_protocol_name* lookup_ip_protocol(register const char *str, register GPERF_LEN_TYPE len);
#include "ip-protocol-from-name.h"
#include "ip-protocol-to-name.h"
const char *ip_protocol_to_name(int id) {
if (id < 0)
return NULL;
if ((size_t) id >= ELEMENTSOF(ip_protocol_names))
return NULL;
return ip_protocol_names[id];
}
int ip_protocol_from_name(const char *name) {
const struct ip_protocol_name *sc;
assert(name);
sc = lookup_ip_protocol(name, strlen(name));
if (!sc)
return -EINVAL;
return sc->id;
}
int parse_ip_protocol(const char *s) {
_cleanup_free_ char *str = NULL;
int i, r;
assert(s);
if (isempty(s))
return IPPROTO_IP;
/* Do not use strdupa() here, as the input string may come from *
* command line or config files. */
str = strdup(s);
if (!str)
return -ENOMEM;
i = ip_protocol_from_name(ascii_strlower(str));
if (i >= 0)
return i;
r = safe_atoi(str, &i);
if (r < 0)
return r;
if (!ip_protocol_to_name(i))
return -EINVAL;
return i;
}
const char *ip_protocol_to_tcp_udp(int id) {
return IN_SET(id, IPPROTO_TCP, IPPROTO_UDP) ?
ip_protocol_to_name(id) : NULL;
}
int ip_protocol_from_tcp_udp(const char *ip_protocol) {
int id = ip_protocol_from_name(ip_protocol);
return IN_SET(id, IPPROTO_TCP, IPPROTO_UDP) ? id : -EINVAL;
}
| 1,838 | 22.576923 | 112 |
c
|
null |
systemd-main/src/shared/ipvlan-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <net/if.h>
#include "ipvlan-util.h"
#include "string-table.h"
static const char* const ipvlan_mode_table[_NETDEV_IPVLAN_MODE_MAX] = {
[NETDEV_IPVLAN_MODE_L2] = "L2",
[NETDEV_IPVLAN_MODE_L3] = "L3",
[NETDEV_IPVLAN_MODE_L3S] = "L3S",
};
DEFINE_STRING_TABLE_LOOKUP(ipvlan_mode, IPVlanMode);
static const char* const ipvlan_flags_table[_NETDEV_IPVLAN_FLAGS_MAX] = {
[NETDEV_IPVLAN_FLAGS_BRIGDE] = "bridge",
[NETDEV_IPVLAN_FLAGS_PRIVATE] = "private",
[NETDEV_IPVLAN_FLAGS_VEPA] = "vepa",
};
DEFINE_STRING_TABLE_LOOKUP(ipvlan_flags, IPVlanFlags);
| 653 | 27.434783 | 73 |
c
|
null |
systemd-main/src/shared/ipvlan-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <netinet/in.h>
#include <linux/if_link.h>
#include "macro.h"
typedef enum IPVlanMode {
NETDEV_IPVLAN_MODE_L2 = IPVLAN_MODE_L2,
NETDEV_IPVLAN_MODE_L3 = IPVLAN_MODE_L3,
NETDEV_IPVLAN_MODE_L3S = IPVLAN_MODE_L3S,
_NETDEV_IPVLAN_MODE_MAX,
_NETDEV_IPVLAN_MODE_INVALID = -EINVAL,
} IPVlanMode;
typedef enum IPVlanFlags {
NETDEV_IPVLAN_FLAGS_BRIGDE,
NETDEV_IPVLAN_FLAGS_PRIVATE = IPVLAN_F_PRIVATE,
NETDEV_IPVLAN_FLAGS_VEPA = IPVLAN_F_VEPA,
_NETDEV_IPVLAN_FLAGS_MAX,
_NETDEV_IPVLAN_FLAGS_INVALID = -EINVAL,
} IPVlanFlags;
const char *ipvlan_mode_to_string(IPVlanMode d) _const_;
IPVlanMode ipvlan_mode_from_string(const char *d) _pure_;
const char *ipvlan_flags_to_string(IPVlanFlags d) _const_;
IPVlanFlags ipvlan_flags_from_string(const char *d) _pure_;
| 904 | 29.166667 | 59 |
h
|
null |
systemd-main/src/shared/journal-importer.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <malloc.h>
#include <unistd.h>
#include "alloc-util.h"
#include "errno-util.h"
#include "escape.h"
#include "fd-util.h"
#include "io-util.h"
#include "journal-file.h"
#include "journal-importer.h"
#include "journal-util.h"
#include "parse-util.h"
#include "string-util.h"
#include "strv.h"
#include "unaligned.h"
enum {
IMPORTER_STATE_LINE = 0, /* waiting to read, or reading line */
IMPORTER_STATE_DATA_START, /* reading binary data header */
IMPORTER_STATE_DATA, /* reading binary data */
IMPORTER_STATE_DATA_FINISH, /* expecting newline */
IMPORTER_STATE_EOF, /* done */
};
void journal_importer_cleanup(JournalImporter *imp) {
if (imp->fd >= 0 && !imp->passive_fd) {
log_debug("Closing %s (fd=%d)", imp->name ?: "importer", imp->fd);
safe_close(imp->fd);
}
free(imp->name);
free(imp->buf);
iovw_free_contents(&imp->iovw, false);
}
static char* realloc_buffer(JournalImporter *imp, size_t size) {
char *b, *old = ASSERT_PTR(imp)->buf;
b = GREEDY_REALLOC(imp->buf, size);
if (!b)
return NULL;
iovw_rebase(&imp->iovw, old, imp->buf);
return b;
}
static int get_line(JournalImporter *imp, char **line, size_t *size) {
ssize_t n;
char *c = NULL;
assert(imp);
assert(imp->state == IMPORTER_STATE_LINE);
assert(imp->offset <= imp->filled);
assert(imp->filled <= MALLOC_SIZEOF_SAFE(imp->buf));
assert(imp->fd >= 0);
for (;;) {
if (imp->buf) {
size_t start = MAX(imp->scanned, imp->offset);
c = memchr(imp->buf + start, '\n',
imp->filled - start);
if (c)
break;
}
imp->scanned = imp->filled;
if (imp->scanned >= DATA_SIZE_MAX)
return log_warning_errno(SYNTHETIC_ERRNO(ENOBUFS),
"Entry is bigger than %u bytes.",
DATA_SIZE_MAX);
if (imp->passive_fd)
/* we have to wait for some data to come to us */
return -EAGAIN;
/* We know that imp->filled is at most DATA_SIZE_MAX, so if
we reallocate it, we'll increase the size at least a bit. */
assert_cc(DATA_SIZE_MAX < ENTRY_SIZE_MAX);
if (MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled < LINE_CHUNK &&
!realloc_buffer(imp, MIN(imp->filled + LINE_CHUNK, ENTRY_SIZE_MAX)))
return log_oom();
assert(imp->buf);
assert(MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled >= LINE_CHUNK ||
MALLOC_SIZEOF_SAFE(imp->buf) >= ENTRY_SIZE_MAX);
n = read(imp->fd,
imp->buf + imp->filled,
MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled);
if (n < 0) {
if (errno != EAGAIN)
log_error_errno(errno, "read(%d, ..., %zu): %m",
imp->fd,
MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled);
return -errno;
} else if (n == 0)
return 0;
imp->filled += n;
}
*line = imp->buf + imp->offset;
*size = c + 1 - imp->buf - imp->offset;
imp->offset += *size;
return 1;
}
static int fill_fixed_size(JournalImporter *imp, void **data, size_t size) {
assert(imp);
assert(IN_SET(imp->state, IMPORTER_STATE_DATA_START, IMPORTER_STATE_DATA, IMPORTER_STATE_DATA_FINISH));
assert(size <= DATA_SIZE_MAX);
assert(imp->offset <= imp->filled);
assert(imp->filled <= MALLOC_SIZEOF_SAFE(imp->buf));
assert(imp->fd >= 0);
assert(data);
while (imp->filled - imp->offset < size) {
int n;
if (imp->passive_fd)
/* we have to wait for some data to come to us */
return -EAGAIN;
if (!realloc_buffer(imp, imp->offset + size))
return log_oom();
n = read(imp->fd, imp->buf + imp->filled,
MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled);
if (n < 0) {
if (errno != EAGAIN)
log_error_errno(errno, "read(%d, ..., %zu): %m", imp->fd,
MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled);
return -errno;
} else if (n == 0)
return 0;
imp->filled += n;
}
*data = imp->buf + imp->offset;
imp->offset += size;
return 1;
}
static int get_data_size(JournalImporter *imp) {
int r;
void *data;
assert(imp);
assert(imp->state == IMPORTER_STATE_DATA_START);
assert(imp->data_size == 0);
r = fill_fixed_size(imp, &data, sizeof(uint64_t));
if (r <= 0)
return r;
imp->data_size = unaligned_read_le64(data);
if (imp->data_size > DATA_SIZE_MAX)
return log_warning_errno(SYNTHETIC_ERRNO(EINVAL),
"Stream declares field with size %zu > DATA_SIZE_MAX = %u",
imp->data_size, DATA_SIZE_MAX);
if (imp->data_size == 0)
log_warning("Binary field with zero length");
return 1;
}
static int get_data_data(JournalImporter *imp, void **data) {
int r;
assert(imp);
assert(data);
assert(imp->state == IMPORTER_STATE_DATA);
r = fill_fixed_size(imp, data, imp->data_size);
if (r <= 0)
return r;
return 1;
}
static int get_data_newline(JournalImporter *imp) {
int r;
char *data;
assert(imp);
assert(imp->state == IMPORTER_STATE_DATA_FINISH);
r = fill_fixed_size(imp, (void**) &data, 1);
if (r <= 0)
return r;
assert(data);
if (*data != '\n') {
char buf[4];
int l;
l = cescape_char(*data, buf);
return log_warning_errno(SYNTHETIC_ERRNO(EINVAL),
"Expected newline, got '%.*s'", l, buf);
}
return 1;
}
static int process_special_field(JournalImporter *imp, char *line) {
const char *value;
char buf[CELLESCAPE_DEFAULT_LENGTH];
int r;
assert(line);
if (STARTSWITH_SET(line, "__CURSOR=", "__SEQNUM=", "__SEQNUM_ID="))
/* ignore __CURSOR=, __SEQNUM=, __SEQNUM_ID= which we cannot replicate */
return 1;
value = startswith(line, "__REALTIME_TIMESTAMP=");
if (value) {
uint64_t x;
r = safe_atou64(value, &x);
if (r < 0)
return log_warning_errno(r, "Failed to parse __REALTIME_TIMESTAMP '%s': %m",
cellescape(buf, sizeof buf, value));
else if (!VALID_REALTIME(x)) {
log_warning("__REALTIME_TIMESTAMP out of range, ignoring: %"PRIu64, x);
return -ERANGE;
}
imp->ts.realtime = x;
return 1;
}
value = startswith(line, "__MONOTONIC_TIMESTAMP=");
if (value) {
uint64_t x;
r = safe_atou64(value, &x);
if (r < 0)
return log_warning_errno(r, "Failed to parse __MONOTONIC_TIMESTAMP '%s': %m",
cellescape(buf, sizeof buf, value));
else if (!VALID_MONOTONIC(x)) {
log_warning("__MONOTONIC_TIMESTAMP out of range, ignoring: %"PRIu64, x);
return -ERANGE;
}
imp->ts.monotonic = x;
return 1;
}
/* Just a single underline, but it needs special treatment too. */
value = startswith(line, "_BOOT_ID=");
if (value) {
r = sd_id128_from_string(value, &imp->boot_id);
if (r < 0)
return log_warning_errno(r, "Failed to parse _BOOT_ID '%s': %m",
cellescape(buf, sizeof buf, value));
/* store the field in the usual fashion too */
return 0;
}
value = startswith(line, "__");
if (value) {
log_notice("Unknown dunder line __%s, ignoring.", cellescape(buf, sizeof buf, value));
return 1;
}
/* no dunder */
return 0;
}
int journal_importer_process_data(JournalImporter *imp) {
int r;
switch (imp->state) {
case IMPORTER_STATE_LINE: {
char *line, *sep;
size_t n = 0;
assert(imp->data_size == 0);
r = get_line(imp, &line, &n);
if (r < 0)
return r;
if (r == 0) {
imp->state = IMPORTER_STATE_EOF;
return 0;
}
assert(n > 0);
assert(line[n-1] == '\n');
if (n == 1) {
log_trace("Received empty line, event is ready");
return 1;
}
/* MESSAGE=xxx\n
or
COREDUMP\n
LLLLLLLL0011223344...\n
*/
sep = memchr(line, '=', n);
if (sep) {
/* chomp newline */
n--;
if (!journal_field_valid(line, sep - line, true)) {
char buf[64], *t;
t = strndupa_safe(line, sep - line);
log_debug("Ignoring invalid field: \"%s\"",
cellescape(buf, sizeof buf, t));
return 0;
}
line[n] = '\0';
r = process_special_field(imp, line);
if (r != 0)
return r < 0 ? r : 0;
r = iovw_put(&imp->iovw, line, n);
if (r < 0)
return r;
} else {
if (!journal_field_valid(line, n - 1, true)) {
char buf[64], *t;
t = strndupa_safe(line, n - 1);
log_debug("Ignoring invalid field: \"%s\"",
cellescape(buf, sizeof buf, t));
return 0;
}
/* replace \n with = */
line[n-1] = '=';
imp->field_len = n;
imp->state = IMPORTER_STATE_DATA_START;
/* we cannot put the field in iovec until we have all data */
}
log_trace("Received: %.*s (%s)", (int) n, line, sep ? "text" : "binary");
return 0; /* continue */
}
case IMPORTER_STATE_DATA_START:
assert(imp->data_size == 0);
r = get_data_size(imp);
// log_debug("get_data_size() -> %d", r);
if (r < 0)
return r;
if (r == 0) {
imp->state = IMPORTER_STATE_EOF;
return 0;
}
imp->state = imp->data_size > 0 ?
IMPORTER_STATE_DATA : IMPORTER_STATE_DATA_FINISH;
return 0; /* continue */
case IMPORTER_STATE_DATA: {
void *data;
char *field;
assert(imp->data_size > 0);
r = get_data_data(imp, &data);
// log_debug("get_data_data() -> %d", r);
if (r < 0)
return r;
if (r == 0) {
imp->state = IMPORTER_STATE_EOF;
return 0;
}
assert(data);
field = (char*) data - sizeof(uint64_t) - imp->field_len;
memmove(field + sizeof(uint64_t), field, imp->field_len);
r = iovw_put(&imp->iovw, field + sizeof(uint64_t), imp->field_len + imp->data_size);
if (r < 0)
return r;
imp->state = IMPORTER_STATE_DATA_FINISH;
return 0; /* continue */
}
case IMPORTER_STATE_DATA_FINISH:
r = get_data_newline(imp);
// log_debug("get_data_newline() -> %d", r);
if (r < 0)
return r;
if (r == 0) {
imp->state = IMPORTER_STATE_EOF;
return 0;
}
imp->data_size = 0;
imp->state = IMPORTER_STATE_LINE;
return 0; /* continue */
default:
assert_not_reached();
}
}
int journal_importer_push_data(JournalImporter *imp, const char *data, size_t size) {
assert(imp);
assert(imp->state != IMPORTER_STATE_EOF);
if (!realloc_buffer(imp, imp->filled + size))
return log_error_errno(ENOMEM,
"Failed to store received data of size %zu "
"(in addition to existing %zu bytes with %zu filled): %m",
size, MALLOC_SIZEOF_SAFE(imp->buf), imp->filled);
memcpy(imp->buf + imp->filled, data, size);
imp->filled += size;
return 0;
}
void journal_importer_drop_iovw(JournalImporter *imp) {
size_t remain, target;
/* This function drops processed data that along with the iovw that points at it */
iovw_free_contents(&imp->iovw, false);
/* possibly reset buffer position */
remain = imp->filled - imp->offset;
if (remain == 0) /* no brainer */
imp->offset = imp->scanned = imp->filled = 0;
else if (imp->offset > MALLOC_SIZEOF_SAFE(imp->buf) - imp->filled &&
imp->offset > remain) {
memcpy(imp->buf, imp->buf + imp->offset, remain);
imp->offset = imp->scanned = 0;
imp->filled = remain;
}
target = MALLOC_SIZEOF_SAFE(imp->buf);
while (target > 16 * LINE_CHUNK && imp->filled < target / 2)
target /= 2;
if (target < MALLOC_SIZEOF_SAFE(imp->buf)) {
char *tmp;
size_t old_size;
old_size = MALLOC_SIZEOF_SAFE(imp->buf);
tmp = realloc(imp->buf, target);
if (!tmp)
log_warning("Failed to reallocate buffer to (smaller) size %zu",
target);
else {
log_debug("Reallocated buffer from %zu to %zu bytes",
old_size, target);
imp->buf = tmp;
}
}
}
bool journal_importer_eof(const JournalImporter *imp) {
return imp->state == IMPORTER_STATE_EOF;
}
| 16,100 | 32.335404 | 111 |
c
|
null |
systemd-main/src/shared/journal-importer.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stddef.h>
#include <stdbool.h>
#include <sys/uio.h>
#include "sd-id128.h"
#include "io-util.h"
#include "time-util.h"
/* Make sure not to make this smaller than the maximum coredump size.
* See JOURNAL_SIZE_MAX in coredump.c */
#ifndef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
#define ENTRY_SIZE_MAX (1024*1024*770u)
#define DATA_SIZE_MAX (1024*1024*768u)
#else
#define ENTRY_SIZE_MAX (1024*1024*13u)
#define DATA_SIZE_MAX (1024*1024*11u)
#endif
#define LINE_CHUNK 8*1024u
/* The maximum number of fields in an entry */
#define ENTRY_FIELD_COUNT_MAX 1024u
typedef struct JournalImporter {
int fd;
bool passive_fd;
char *name;
char *buf;
size_t offset; /* offset to the beginning of live data in the buffer */
size_t scanned; /* number of bytes since the beginning of data without a newline */
size_t filled; /* total number of bytes in the buffer */
size_t field_len; /* used for binary fields: the field name length */
size_t data_size; /* and the size of the binary data chunk being processed */
struct iovec_wrapper iovw;
int state;
dual_timestamp ts;
sd_id128_t boot_id;
} JournalImporter;
#define JOURNAL_IMPORTER_INIT(_fd) { .fd = (_fd), .iovw = {} }
#define JOURNAL_IMPORTER_MAKE(_fd) (JournalImporter) JOURNAL_IMPORTER_INIT(_fd)
void journal_importer_cleanup(JournalImporter *);
int journal_importer_process_data(JournalImporter *);
int journal_importer_push_data(JournalImporter *, const char *data, size_t size);
void journal_importer_drop_iovw(JournalImporter *);
bool journal_importer_eof(const JournalImporter *);
static inline size_t journal_importer_bytes_remaining(const JournalImporter *imp) {
return imp->filled;
}
| 1,845 | 29.766667 | 94 |
h
|
null |
systemd-main/src/shared/kbd-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "errno-util.h"
#include "kbd-util.h"
#include "log.h"
#include "nulstr-util.h"
#include "path-util.h"
#include "recurse-dir.h"
#include "set.h"
#include "string-util.h"
#include "strv.h"
#include "utf8.h"
struct recurse_dir_userdata {
const char *keymap_name;
Set *keymaps;
};
static int keymap_recurse_dir_callback(
RecurseDirEvent event,
const char *path,
int dir_fd,
int inode_fd,
const struct dirent *de,
const struct statx *sx,
void *userdata) {
struct recurse_dir_userdata *data = userdata;
_cleanup_free_ char *p = NULL;
int r;
assert(de);
/* If 'keymap_name' is non-NULL, return true if keymap 'keymap_name' is found. Otherwise, add all
* keymaps to 'keymaps'. */
if (event != RECURSE_DIR_ENTRY)
return RECURSE_DIR_CONTINUE;
if (!IN_SET(de->d_type, DT_REG, DT_LNK))
return RECURSE_DIR_CONTINUE;
const char *e = endswith(de->d_name, ".map") ?: endswith(de->d_name, ".map.gz");
if (!e)
return RECURSE_DIR_CONTINUE;
p = strndup(de->d_name, e - de->d_name);
if (!p)
return -ENOMEM;
if (data->keymap_name)
return streq(p, data->keymap_name) ? 1 : RECURSE_DIR_CONTINUE;
assert(data->keymaps);
if (!keymap_is_valid(p))
return 0;
r = set_consume(data->keymaps, TAKE_PTR(p));
if (r < 0)
return r;
return RECURSE_DIR_CONTINUE;
}
int get_keymaps(char ***ret) {
_cleanup_set_free_free_ Set *keymaps = NULL;
int r;
keymaps = set_new(&string_hash_ops);
if (!keymaps)
return -ENOMEM;
NULSTR_FOREACH(dir, KBD_KEYMAP_DIRS) {
r = recurse_dir_at(
AT_FDCWD,
dir,
/* statx_mask= */ 0,
/* n_depth_max= */ UINT_MAX,
RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE,
keymap_recurse_dir_callback,
&(struct recurse_dir_userdata) {
.keymaps = keymaps,
});
if (r < 0) {
if (r == -ENOENT)
continue;
if (ERRNO_IS_RESOURCE(r))
return log_warning_errno(r, "Failed to read keymap list from %s: %m", dir);
log_debug_errno(r, "Failed to read keymap list from %s, ignoring: %m", dir);
}
}
_cleanup_strv_free_ char **l = set_get_strv(keymaps);
if (!l)
return -ENOMEM;
keymaps = set_free(keymaps); /* If we got the strv above, then do a set_free() rather than
* set_free_free() since the entries of the set are now owned by the
* strv */
if (strv_isempty(l))
return -ENOENT;
strv_sort(l);
*ret = TAKE_PTR(l);
return 0;
}
bool keymap_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 keymap_exists(const char *name) {
int r = 0;
if (!keymap_is_valid(name))
return -EINVAL;
NULSTR_FOREACH(dir, KBD_KEYMAP_DIRS) {
r = recurse_dir_at(
AT_FDCWD,
dir,
/* statx_mask= */ 0,
/* n_depth_max= */ UINT_MAX,
RECURSE_DIR_IGNORE_DOT|RECURSE_DIR_ENSURE_TYPE,
keymap_recurse_dir_callback,
&(struct recurse_dir_userdata) {
.keymap_name = name,
});
if (r < 0) {
if (r == -ENOENT)
continue;
if (ERRNO_IS_RESOURCE(r))
return r;
log_debug_errno(r, "Failed to read keymap list from %s, ignoring: %m", dir);
continue;
}
if (r > 0)
break;
}
return r > 0;
}
| 4,910 | 29.314815 | 107 |
c
|
null |
systemd-main/src/shared/kbd-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#if HAVE_SPLIT_USR
#define KBD_KEYMAP_DIRS \
"/usr/share/keymaps/\0" \
"/usr/share/kbd/keymaps/\0" \
"/usr/lib/kbd/keymaps/\0" \
"/lib/kbd/keymaps/\0"
#else
#define KBD_KEYMAP_DIRS \
"/usr/share/keymaps/\0" \
"/usr/share/kbd/keymaps/\0" \
"/usr/lib/kbd/keymaps/\0"
#endif
int get_keymaps(char ***l);
bool keymap_is_valid(const char *name);
int keymap_exists(const char *name);
| 637 | 28 | 49 |
h
|
null |
systemd-main/src/shared/kernel-image.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "fd-util.h"
#include "fileio.h"
#include "env-file.h"
#include "kernel-image.h"
#include "os-util.h"
#include "parse-util.h"
#include "pe-header.h"
#include "string-table.h"
#define MAX_SECTIONS 96
static const uint8_t dos_file_magic[2] = "MZ";
static const uint8_t pe_file_magic[4] = "PE\0\0";
static const uint8_t name_osrel[8] = ".osrel";
static const uint8_t name_linux[8] = ".linux";
static const uint8_t name_initrd[8] = ".initrd";
static const uint8_t name_cmdline[8] = ".cmdline";
static const uint8_t name_uname[8] = ".uname";
static const char * const kernel_image_type_table[_KERNEL_IMAGE_TYPE_MAX] = {
[KERNEL_IMAGE_TYPE_UNKNOWN] = "unknown",
[KERNEL_IMAGE_TYPE_UKI] = "uki",
[KERNEL_IMAGE_TYPE_PE] = "pe",
};
DEFINE_STRING_TABLE_LOOKUP_TO_STRING(kernel_image_type, KernelImageType);
static int pe_sections(FILE *f, struct PeSectionHeader **ret, size_t *ret_n) {
_cleanup_free_ struct PeSectionHeader *sections = NULL;
struct DosFileHeader dos;
struct PeHeader pe;
size_t scount;
uint64_t soff, items;
assert(f);
assert(ret);
assert(ret_n);
items = fread(&dos, 1, sizeof(dos), f);
if (items < sizeof(dos.Magic))
return log_error_errno(SYNTHETIC_ERRNO(EIO), "File is smaller than DOS magic (got %"PRIu64" of %zu bytes)",
items, sizeof(dos.Magic));
if (memcmp(dos.Magic, dos_file_magic, sizeof(dos_file_magic)) != 0)
goto no_sections;
if (items != sizeof(dos))
return log_error_errno(SYNTHETIC_ERRNO(EIO), "File is smaller than DOS header (got %"PRIu64" of %zu bytes)",
items, sizeof(dos));
if (fseek(f, le32toh(dos.ExeHeader), SEEK_SET) < 0)
return log_error_errno(errno, "Failed to seek to PE header: %m");
items = fread(&pe, 1, sizeof(pe), f);
if (items != sizeof(pe))
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read PE header.");
if (memcmp(pe.Magic, pe_file_magic, sizeof(pe_file_magic)) != 0)
goto no_sections;
soff = le32toh(dos.ExeHeader) + sizeof(pe) + le16toh(pe.FileHeader.SizeOfOptionalHeader);
if (fseek(f, soff, SEEK_SET) < 0)
return log_error_errno(errno, "Failed to seek to PE section headers: %m");
scount = le16toh(pe.FileHeader.NumberOfSections);
if (scount > MAX_SECTIONS)
goto no_sections;
sections = new(struct PeSectionHeader, scount);
if (!sections)
return log_oom();
items = fread(sections, sizeof(*sections), scount, f);
if (items != scount)
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read PE section header.");
*ret = TAKE_PTR(sections);
*ret_n = scount;
return 0;
no_sections:
*ret = NULL;
*ret_n = 0;
return 0;
}
static bool find_pe_section(
struct PeSectionHeader *sections,
size_t scount,
const uint8_t *name,
size_t namelen,
size_t *ret) {
assert(sections || scount == 0);
assert(name || namelen == 0);
for (size_t s = 0; s < scount; s++)
if (memcmp_nn(sections[s].Name, sizeof(sections[s].Name), name, namelen) == 0) {
if (ret)
*ret = s;
return true;
}
return false;
}
static bool is_uki(struct PeSectionHeader *sections, size_t scount) {
assert(sections || scount == 0);
return
find_pe_section(sections, scount, name_osrel, sizeof(name_osrel), NULL) &&
find_pe_section(sections, scount, name_linux, sizeof(name_linux), NULL) &&
find_pe_section(sections, scount, name_initrd, sizeof(name_initrd), NULL);
}
static int read_pe_section(
FILE *f,
struct PeSectionHeader *sections,
size_t scount,
const uint8_t *name,
size_t name_len,
void **ret,
size_t *ret_n) {
struct PeSectionHeader *section;
_cleanup_free_ void *data = NULL;
uint32_t size, bytes;
uint64_t soff;
size_t idx;
assert(f);
assert(sections || scount == 0);
assert(ret);
if (!find_pe_section(sections, scount, name, name_len, &idx)) {
*ret = NULL;
if (ret_n)
*ret_n = 0;
return 0;
}
section = sections + idx;
soff = le32toh(section->PointerToRawData);
size = le32toh(section->VirtualSize);
if (size > 16 * 1024)
return log_error_errno(SYNTHETIC_ERRNO(E2BIG), "PE section too big.");
if (fseek(f, soff, SEEK_SET) < 0)
return log_error_errno(errno, "Failed to seek to PE section: %m");
data = malloc(size+1);
if (!data)
return log_oom();
((uint8_t*) data)[size] = 0; /* safety NUL byte */
bytes = fread(data, 1, size, f);
if (bytes != size)
return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to read PE section.");
*ret = TAKE_PTR(data);
if (ret_n)
*ret_n = size;
return 1;
}
static int uki_read_pretty_name(
FILE *f,
struct PeSectionHeader *sections,
size_t scount,
char **ret) {
_cleanup_free_ char *pname = NULL, *name = NULL;
_cleanup_fclose_ FILE *s = NULL;
_cleanup_free_ void *osrel = NULL;
size_t osrel_size = 0;
int r;
assert(f);
assert(sections || scount == 0);
assert(ret);
r = read_pe_section(f, sections, scount, name_osrel, sizeof(name_osrel), &osrel, &osrel_size);
if (r < 0)
return r;
if (r == 0) {
*ret = NULL;
return 0;
}
s = fmemopen(osrel, osrel_size, "r");
if (!s)
return log_error_errno(errno, "Failed to open embedded os-release file: %m");
r = parse_env_file(s, NULL,
"PRETTY_NAME", &pname,
"NAME", &name);
if (r < 0)
return log_error_errno(r, "Failed to parse embedded os-release file: %m");
/* follow the same logic as os_release_pretty_name() */
if (!isempty(pname))
*ret = TAKE_PTR(pname);
else if (!isempty(name))
*ret = TAKE_PTR(name);
else {
char *n = strdup("Linux");
if (!n)
return log_oom();
*ret = n;
}
return 0;
}
static int inspect_uki(
FILE *f,
struct PeSectionHeader *sections,
size_t scount,
char **ret_cmdline,
char **ret_uname,
char **ret_pretty_name) {
_cleanup_free_ char *cmdline = NULL, *uname = NULL, *pname = NULL;
int r;
assert(f);
assert(sections || scount == 0);
if (ret_cmdline) {
r = read_pe_section(f, sections, scount, name_cmdline, sizeof(name_cmdline), (void**) &cmdline, NULL);
if (r < 0)
return r;
}
if (ret_uname) {
r = read_pe_section(f, sections, scount, name_uname, sizeof(name_uname), (void**) &uname, NULL);
if (r < 0)
return r;
}
if (ret_pretty_name) {
r = uki_read_pretty_name(f, sections, scount, &pname);
if (r < 0)
return r;
}
if (ret_cmdline)
*ret_cmdline = TAKE_PTR(cmdline);
if (ret_uname)
*ret_uname = TAKE_PTR(uname);
if (ret_pretty_name)
*ret_pretty_name = TAKE_PTR(pname);
return 0;
}
int inspect_kernel(
int dir_fd,
const char *filename,
KernelImageType *ret_type,
char **ret_cmdline,
char **ret_uname,
char **ret_pretty_name) {
_cleanup_fclose_ FILE *f = NULL;
_cleanup_free_ struct PeSectionHeader *sections = NULL;
size_t scount;
KernelImageType t;
int r;
assert(dir_fd >= 0 || dir_fd == AT_FDCWD);
assert(filename);
r = xfopenat(dir_fd, filename, "re", 0, &f);
if (r < 0)
return log_error_errno(r, "Failed to open kernel image file '%s': %m", filename);
r = pe_sections(f, §ions, &scount);
if (r < 0)
return r;
if (!sections)
t = KERNEL_IMAGE_TYPE_UNKNOWN;
else if (is_uki(sections, scount)) {
t = KERNEL_IMAGE_TYPE_UKI;
r = inspect_uki(f, sections, scount, ret_cmdline, ret_uname, ret_pretty_name);
if (r < 0)
return r;
} else
t = KERNEL_IMAGE_TYPE_PE;
if (ret_type)
*ret_type = t;
return 0;
}
| 9,458 | 30.741611 | 124 |
c
|
null |
systemd-main/src/shared/kernel-image.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <errno.h>
#include "macro.h"
typedef enum KernelImageType {
KERNEL_IMAGE_TYPE_UNKNOWN,
KERNEL_IMAGE_TYPE_UKI,
KERNEL_IMAGE_TYPE_PE,
_KERNEL_IMAGE_TYPE_MAX,
_KERNEL_IMAGE_TYPE_INVALID = -EINVAL,
} KernelImageType;
const char* kernel_image_type_to_string(KernelImageType t) _const_;
int inspect_kernel(
int dir_fd,
const char *filename,
KernelImageType *ret_type,
char **ret_cmdline,
char **ret_uname,
char **ret_pretty_name);
| 637 | 24.52 | 67 |
h
|
null |
systemd-main/src/shared/keyring-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "keyring-util.h"
#include "memory-util.h"
#include "missing_syscall.h"
int keyring_read(key_serial_t serial, void **ret, size_t *ret_size) {
size_t m = 100;
for (;;) {
_cleanup_(erase_and_freep) uint8_t *p = NULL;
long n;
p = new(uint8_t, m+1);
if (!p)
return -ENOMEM;
n = keyctl(KEYCTL_READ, (unsigned long) serial, (unsigned long) p, (unsigned long) m, 0);
if (n < 0)
return -errno;
if ((size_t) n <= m) {
p[n] = 0; /* NUL terminate, just in case */
if (ret)
*ret = TAKE_PTR(p);
if (ret_size)
*ret_size = n;
return 0;
}
if (m > (SIZE_MAX-1) / 2) /* overflow check */
return -ENOMEM;
m *= 2;
}
}
| 1,081 | 26.74359 | 105 |
c
|
null |
systemd-main/src/shared/killall.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
/***
Copyright © 2010 ProFUSION embedded systems
***/
#include <errno.h>
#include <signal.h>
#include <sys/wait.h>
#include <unistd.h>
#include "alloc-util.h"
#include "constants.h"
#include "dirent-util.h"
#include "fd-util.h"
#include "format-util.h"
#include "initrd-util.h"
#include "killall.h"
#include "parse-util.h"
#include "process-util.h"
#include "set.h"
#include "stdio-util.h"
#include "string-util.h"
#include "terminal-util.h"
static bool ignore_proc(pid_t pid, bool warn_rootfs) {
_cleanup_fclose_ FILE *f = NULL;
const char *p;
char c = 0;
uid_t uid;
int r;
/* We are PID 1, let's not commit suicide */
if (pid <= 1)
return true;
/* Ignore kernel threads */
r = is_kernel_thread(pid);
if (r != 0)
return true; /* also ignore processes where we can't determine this */
r = get_process_uid(pid, &uid);
if (r < 0)
return true; /* not really, but better safe than sorry */
/* Non-root processes otherwise are always subject to be killed */
if (uid != 0)
return false;
p = procfs_file_alloca(pid, "cmdline");
f = fopen(p, "re");
if (!f)
return true; /* not really, but has the desired effect */
/* Try to read the first character of the command line. If the cmdline is empty (which might be the case for
* kernel threads but potentially also other stuff), this line won't do anything, but we don't care much, as
* actual kernel threads are already filtered out above. */
(void) fread(&c, 1, 1, f);
/* Processes with argv[0][0] = '@' we ignore from the killing spree.
*
* https://systemd.io/ROOT_STORAGE_DAEMONS */
if (c != '@')
return false;
if (warn_rootfs &&
pid_from_same_root_fs(pid) == 0) {
_cleanup_free_ char *comm = NULL;
(void) get_process_comm(pid, &comm);
log_notice("Process " PID_FMT " (%s) has been marked to be excluded from killing. It is "
"running from the root file system, and thus likely to block re-mounting of the "
"root file system to read-only. Please consider moving it into an initrd file "
"system instead.", pid, strna(comm));
}
return true;
}
static void log_children_no_yet_killed(Set *pids) {
_cleanup_free_ char *lst_child = NULL;
void *p;
int r;
SET_FOREACH(p, pids) {
_cleanup_free_ char *s = NULL;
if (get_process_comm(PTR_TO_PID(p), &s) >= 0)
r = strextendf(&lst_child, ", " PID_FMT " (%s)", PTR_TO_PID(p), s);
else
r = strextendf(&lst_child, ", " PID_FMT, PTR_TO_PID(p));
if (r < 0)
return (void) log_oom();
}
if (isempty(lst_child))
return;
log_warning("Waiting for process: %s", lst_child + 2);
}
static int wait_for_children(Set *pids, sigset_t *mask, usec_t timeout) {
usec_t until, date_log_child, n;
assert(mask);
/* Return the number of children remaining in the pids set: That correspond to the number
* of processes still "alive" after the timeout */
if (set_isempty(pids))
return 0;
n = now(CLOCK_MONOTONIC);
until = usec_add(n, timeout);
date_log_child = usec_add(n, 10u * USEC_PER_SEC);
if (date_log_child > until)
date_log_child = usec_add(n, timeout / 2u);
for (;;) {
struct timespec ts;
int k;
void *p;
/* First, let the kernel inform us about killed
* children. Most processes will probably be our
* children, but some are not (might be our
* grandchildren instead...). */
for (;;) {
pid_t pid;
pid = waitpid(-1, NULL, WNOHANG);
if (pid == 0)
break;
if (pid < 0) {
if (errno == ECHILD)
break;
return log_error_errno(errno, "waitpid() failed: %m");
}
(void) set_remove(pids, PID_TO_PTR(pid));
}
/* Now explicitly check who might be remaining, who
* might not be our child. */
SET_FOREACH(p, pids) {
/* kill(pid, 0) sends no signal, but it tells
* us whether the process still exists. */
if (kill(PTR_TO_PID(p), 0) == 0)
continue;
if (errno != ESRCH)
continue;
set_remove(pids, p);
}
if (set_isempty(pids))
return 0;
n = now(CLOCK_MONOTONIC);
if (date_log_child > 0 && n >= date_log_child) {
log_children_no_yet_killed(pids);
/* Log the children not yet killed only once */
date_log_child = 0;
}
if (n >= until)
return set_size(pids);
if (date_log_child > 0)
timespec_store(&ts, MIN(until - n, date_log_child - n));
else
timespec_store(&ts, until - n);
k = sigtimedwait(mask, NULL, &ts);
if (k != SIGCHLD) {
if (k < 0 && errno != EAGAIN)
return log_error_errno(errno, "sigtimedwait() failed: %m");
if (k >= 0)
log_warning("sigtimedwait() returned unexpected signal.");
}
}
}
static int killall(int sig, Set *pids, bool send_sighup) {
_cleanup_closedir_ DIR *dir = NULL;
int n_killed = 0;
/* Send the specified signal to all remaining processes, if not excluded by ignore_proc().
* Returns the number of processes to which the specified signal was sent */
dir = opendir("/proc");
if (!dir)
return log_warning_errno(errno, "opendir(/proc) failed: %m");
FOREACH_DIRENT_ALL(de, dir, break) {
pid_t pid;
int r;
if (!IN_SET(de->d_type, DT_DIR, DT_UNKNOWN))
continue;
if (parse_pid(de->d_name, &pid) < 0)
continue;
if (ignore_proc(pid, sig == SIGKILL && !in_initrd()))
continue;
if (sig == SIGKILL) {
_cleanup_free_ char *s = NULL;
(void) get_process_comm(pid, &s);
log_notice("Sending SIGKILL to PID "PID_FMT" (%s).", pid, strna(s));
}
if (kill(pid, sig) >= 0) {
n_killed++;
if (pids) {
r = set_put(pids, PID_TO_PTR(pid));
if (r < 0)
log_oom();
}
} else if (errno != ENOENT)
log_warning_errno(errno, "Could not kill %d: %m", pid);
if (send_sighup) {
/* Optionally, also send a SIGHUP signal, but
only if the process has a controlling
tty. This is useful to allow handling of
shells which ignore SIGTERM but react to
SIGHUP. We do not send this to processes that
have no controlling TTY since we don't want to
trigger reloads of daemon processes. Also we
make sure to only send this after SIGTERM so
that SIGTERM is always first in the queue. */
if (get_ctty_devnr(pid, NULL) >= 0)
/* it's OK if the process is gone, just ignore the result */
(void) kill(pid, SIGHUP);
}
}
return n_killed;
}
int broadcast_signal(int sig, bool wait_for_exit, bool send_sighup, usec_t timeout) {
int n_children_left;
sigset_t mask, oldmask;
_cleanup_set_free_ Set *pids = NULL;
/* Send the specified signal to all remaining processes, if not excluded by ignore_proc().
* Return:
* - The number of processes still "alive" after the timeout (that should have been killed)
* if the function needs to wait for the end of the processes (wait_for_exit).
* - Otherwise, the number of processes to which the specified signal was sent */
if (wait_for_exit)
pids = set_new(NULL);
assert_se(sigemptyset(&mask) == 0);
assert_se(sigaddset(&mask, SIGCHLD) == 0);
assert_se(sigprocmask(SIG_BLOCK, &mask, &oldmask) == 0);
if (kill(-1, SIGSTOP) < 0 && errno != ESRCH)
log_warning_errno(errno, "kill(-1, SIGSTOP) failed: %m");
n_children_left = killall(sig, pids, send_sighup);
if (kill(-1, SIGCONT) < 0 && errno != ESRCH)
log_warning_errno(errno, "kill(-1, SIGCONT) failed: %m");
if (wait_for_exit && n_children_left > 0)
n_children_left = wait_for_children(pids, &mask, timeout);
assert_se(sigprocmask(SIG_SETMASK, &oldmask, NULL) == 0);
return n_children_left;
}
| 10,044 | 34.369718 | 116 |
c
|
null |
systemd-main/src/shared/label-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <fcntl.h>
#include <stdbool.h>
#include <sys/types.h>
typedef enum LabelFixFlags {
LABEL_IGNORE_ENOENT = 1 << 0,
LABEL_IGNORE_EROFS = 1 << 1,
} LabelFixFlags;
int label_fix_full(int atfd, const char *inode_path, const char *label_path, LabelFixFlags flags);
static inline int label_fix(const char *path, LabelFixFlags flags) {
return label_fix_full(AT_FDCWD, path, path, flags);
}
int symlink_label(const char *old_path, const char *new_path);
int symlink_atomic_full_label(const char *from, const char *to, bool make_relative);
static inline int symlink_atomic_label(const char *from, const char *to) {
return symlink_atomic_full_label(from, to, false);
}
int mknod_label(const char *pathname, mode_t mode, dev_t dev);
int btrfs_subvol_make_label(const char *path);
int mac_init(void);
| 898 | 30 | 98 |
h
|
null |
systemd-main/src/shared/libcrypt-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#if HAVE_CRYPT_H
/* libxcrypt is a replacement for glibc's libcrypt, and libcrypt might be
* removed from glibc at some point. As part of the removal, defines for
* crypt(3) are dropped from unistd.h, and we must include crypt.h instead.
*
* Newer versions of glibc (v2.0+) already ship crypt.h with a definition
* of crypt(3) as well, so we simply include it if it is present. MariaDB,
* MySQL, PostgreSQL, Perl and some other wide-spread packages do it the
* same way since ages without any problems.
*/
# include <crypt.h>
#else
# include <unistd.h>
#endif
#include <errno.h>
#include <stdlib.h>
#include "alloc-util.h"
#include "errno-util.h"
#include "libcrypt-util.h"
#include "log.h"
#include "macro.h"
#include "memory-util.h"
#include "missing_stdlib.h"
#include "random-util.h"
#include "string-util.h"
#include "strv.h"
int make_salt(char **ret) {
#if HAVE_CRYPT_GENSALT_RA
const char *e;
char *salt;
/* If we have crypt_gensalt_ra() we default to the "preferred method" (i.e. usually yescrypt).
* crypt_gensalt_ra() is usually provided by libxcrypt. */
e = secure_getenv("SYSTEMD_CRYPT_PREFIX");
if (!e)
#if HAVE_CRYPT_PREFERRED_METHOD
e = crypt_preferred_method();
#else
e = "$6$";
#endif
log_debug("Generating salt for hash prefix: %s", e);
salt = crypt_gensalt_ra(e, 0, NULL, 0);
if (!salt)
return -errno;
*ret = salt;
return 0;
#else
/* If crypt_gensalt_ra() is not available, we use SHA512 and generate the salt on our own. */
static const char table[] =
"abcdefghijklmnopqrstuvwxyz"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"0123456789"
"./";
uint8_t raw[16];
char *salt, *j;
size_t i;
int r;
/* This is a bit like crypt_gensalt_ra(), but doesn't require libcrypt, and doesn't do anything but
* SHA512, i.e. is legacy-free and minimizes our deps. */
assert_cc(sizeof(table) == 64U + 1U);
log_debug("Generating fallback salt for hash prefix: $6$");
/* Insist on the best randomness by setting RANDOM_BLOCK, this is about keeping passwords secret after all. */
r = crypto_random_bytes(raw, sizeof(raw));
if (r < 0)
return r;
salt = new(char, 3+sizeof(raw)+1+1);
if (!salt)
return -ENOMEM;
/* We only bother with SHA512 hashed passwords, the rest is legacy, and we don't do legacy. */
j = stpcpy(salt, "$6$");
for (i = 0; i < sizeof(raw); i++)
j[i] = table[raw[i] & 63];
j[i++] = '$';
j[i] = 0;
*ret = salt;
return 0;
#endif
}
#if HAVE_CRYPT_RA
# define CRYPT_RA_NAME "crypt_ra"
#else
# define CRYPT_RA_NAME "crypt_r"
/* Provide a poor man's fallback that uses a fixed size buffer. */
static char* systemd_crypt_ra(const char *phrase, const char *setting, void **data, int *size) {
assert(data);
assert(size);
/* We allocate the buffer because crypt(3) says: struct crypt_data may be quite large (32kB in this
* implementation of libcrypt; over 128kB in some other implementations). This is large enough that
* it may be unwise to allocate it on the stack. */
if (!*data) {
*data = new0(struct crypt_data, 1);
if (!*data) {
errno = -ENOMEM;
return NULL;
}
*size = (int) (sizeof(struct crypt_data));
}
char *t = crypt_r(phrase, setting, *data);
if (!t)
return NULL;
/* crypt_r may return a pointer to an invalid hashed password on error. Our callers expect NULL on
* error, so let's just return that. */
if (t[0] == '*')
return NULL;
return t;
}
#define crypt_ra systemd_crypt_ra
#endif
int hash_password_full(const char *password, void **cd_data, int *cd_size, char **ret) {
_cleanup_free_ char *salt = NULL;
_cleanup_(erase_and_freep) void *_cd_data = NULL;
char *p;
int r, _cd_size = 0;
assert(!!cd_data == !!cd_size);
r = make_salt(&salt);
if (r < 0)
return log_debug_errno(r, "Failed to generate salt: %m");
errno = 0;
p = crypt_ra(password, salt, cd_data ?: &_cd_data, cd_size ?: &_cd_size);
if (!p)
return log_debug_errno(errno_or_else(SYNTHETIC_ERRNO(EINVAL)),
CRYPT_RA_NAME "() failed: %m");
p = strdup(p);
if (!p)
return -ENOMEM;
*ret = p;
return 0;
}
bool looks_like_hashed_password(const char *s) {
/* Returns false if the specified string is certainly not a hashed UNIX password. crypt(5) lists
* various hashing methods. We only reject (return false) strings which are documented to have
* different meanings.
*
* In particular, we allow locked passwords, i.e. strings starting with "!", including just "!",
* i.e. the locked empty password. See also fc58c0c7bf7e4f525b916e3e5be0de2307fef04e.
*/
if (!s)
return false;
s += strspn(s, "!"); /* Skip (possibly duplicated) locking prefix */
return !STR_IN_SET(s, "x", "*");
}
int test_password_one(const char *hashed_password, const char *password) {
_cleanup_(erase_and_freep) void *cd_data = NULL;
int cd_size = 0;
const char *k;
errno = 0;
k = crypt_ra(password, hashed_password, &cd_data, &cd_size);
if (!k) {
if (errno == ENOMEM)
return -ENOMEM;
/* Unknown or unavailable hashing method or string too short */
return 0;
}
return streq(k, hashed_password);
}
int test_password_many(char **hashed_password, const char *password) {
int r;
STRV_FOREACH(hpw, hashed_password) {
r = test_password_one(*hpw, password);
if (r < 0)
return r;
if (r > 0)
return true;
}
return false;
}
| 6,391 | 29.150943 | 118 |
c
|
null |
systemd-main/src/shared/libcrypt-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
int make_salt(char **ret);
int hash_password_full(const char *password, void **cd_data, int *cd_size, char **ret);
static inline int hash_password(const char *password, char **ret) {
return hash_password_full(password, NULL, NULL, ret);
}
bool looks_like_hashed_password(const char *s);
int test_password_one(const char *hashed_password, const char *password);
int test_password_many(char **hashed_password, const char *password);
| 524 | 36.5 | 87 |
h
|
null |
systemd-main/src/shared/libfido2-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "macro.h"
typedef enum Fido2EnrollFlags {
FIDO2ENROLL_PIN = 1 << 0,
FIDO2ENROLL_UP = 1 << 1, /* User presence (ie: touching token) */
FIDO2ENROLL_UV = 1 << 2, /* User verification (ie: fingerprint) */
FIDO2ENROLL_PIN_IF_NEEDED = 1 << 3, /* If auth doesn't work without PIN ask for one, as in systemd 248 */
FIDO2ENROLL_UP_IF_NEEDED = 1 << 4, /* If auth doesn't work without UP, enable it, as in systemd 248 */
FIDO2ENROLL_UV_OMIT = 1 << 5, /* Leave "uv" untouched, as in systemd 248 */
_FIDO2ENROLL_TYPE_MAX,
_FIDO2ENROLL_TYPE_INVALID = -EINVAL,
} Fido2EnrollFlags;
#if HAVE_LIBFIDO2
#include <fido.h>
extern int (*sym_fido_assert_allow_cred)(fido_assert_t *, const unsigned char *, size_t);
extern void (*sym_fido_assert_free)(fido_assert_t **);
extern size_t (*sym_fido_assert_hmac_secret_len)(const fido_assert_t *, size_t);
extern const unsigned char* (*sym_fido_assert_hmac_secret_ptr)(const fido_assert_t *, size_t);
extern fido_assert_t* (*sym_fido_assert_new)(void);
extern int (*sym_fido_assert_set_clientdata_hash)(fido_assert_t *, const unsigned char *, size_t);
extern int (*sym_fido_assert_set_extensions)(fido_assert_t *, int);
extern int (*sym_fido_assert_set_hmac_salt)(fido_assert_t *, const unsigned char *, size_t);
extern int (*sym_fido_assert_set_rp)(fido_assert_t *, const char *);
extern int (*sym_fido_assert_set_up)(fido_assert_t *, fido_opt_t);
extern int (*sym_fido_assert_set_uv)(fido_assert_t *, fido_opt_t);
extern size_t (*sym_fido_cbor_info_extensions_len)(const fido_cbor_info_t *);
extern char **(*sym_fido_cbor_info_extensions_ptr)(const fido_cbor_info_t *);
extern void (*sym_fido_cbor_info_free)(fido_cbor_info_t **);
extern fido_cbor_info_t* (*sym_fido_cbor_info_new)(void);
extern size_t (*sym_fido_cbor_info_options_len)(const fido_cbor_info_t *);
extern char** (*sym_fido_cbor_info_options_name_ptr)(const fido_cbor_info_t *);
extern const bool* (*sym_fido_cbor_info_options_value_ptr)(const fido_cbor_info_t *);
extern void (*sym_fido_cred_free)(fido_cred_t **);
extern size_t (*sym_fido_cred_id_len)(const fido_cred_t *);
extern const unsigned char* (*sym_fido_cred_id_ptr)(const fido_cred_t *);
extern fido_cred_t* (*sym_fido_cred_new)(void);
extern int (*sym_fido_cred_set_clientdata_hash)(fido_cred_t *, const unsigned char *, size_t);
extern int (*sym_fido_cred_set_extensions)(fido_cred_t *, int);
extern int (*sym_fido_cred_set_rk)(fido_cred_t *, fido_opt_t);
extern int (*sym_fido_cred_set_rp)(fido_cred_t *, const char *, const char *);
extern int (*sym_fido_cred_set_type)(fido_cred_t *, int);
extern int (*sym_fido_cred_set_user)(fido_cred_t *, const unsigned char *, size_t, const char *, const char *, const char *);
extern int (*sym_fido_cred_set_uv)(fido_cred_t *, fido_opt_t);
extern void (*sym_fido_dev_free)(fido_dev_t **);
extern int (*sym_fido_dev_get_assert)(fido_dev_t *, fido_assert_t *, const char *);
extern int (*sym_fido_dev_get_cbor_info)(fido_dev_t *, fido_cbor_info_t *);
extern void (*sym_fido_dev_info_free)(fido_dev_info_t **, size_t);
extern int (*sym_fido_dev_info_manifest)(fido_dev_info_t *, size_t, size_t *);
extern const char* (*sym_fido_dev_info_manufacturer_string)(const fido_dev_info_t *);
extern const char* (*sym_fido_dev_info_product_string)(const fido_dev_info_t *);
extern fido_dev_info_t* (*sym_fido_dev_info_new)(size_t);
extern const char* (*sym_fido_dev_info_path)(const fido_dev_info_t *);
extern const fido_dev_info_t* (*sym_fido_dev_info_ptr)(const fido_dev_info_t *, size_t);
extern bool (*sym_fido_dev_is_fido2)(const fido_dev_t *);
extern int (*sym_fido_dev_make_cred)(fido_dev_t *, fido_cred_t *, const char *);
extern fido_dev_t* (*sym_fido_dev_new)(void);
extern int (*sym_fido_dev_open)(fido_dev_t *, const char *);
extern int (*sym_fido_dev_close)(fido_dev_t *);
extern const char* (*sym_fido_strerr)(int);
int dlopen_libfido2(void);
static inline void fido_cbor_info_free_wrapper(fido_cbor_info_t **p) {
if (*p)
sym_fido_cbor_info_free(p);
}
static inline void fido_assert_free_wrapper(fido_assert_t **p) {
if (*p)
sym_fido_assert_free(p);
}
static inline void fido_dev_free_wrapper(fido_dev_t **p) {
if (*p) {
sym_fido_dev_close(*p);
sym_fido_dev_free(p);
}
}
static inline void fido_cred_free_wrapper(fido_cred_t **p) {
if (*p)
sym_fido_cred_free(p);
}
int fido2_use_hmac_hash(
const char *device,
const char *rp_id,
const void *salt,
size_t salt_size,
const void *cid,
size_t cid_size,
char **pins,
Fido2EnrollFlags required,
void **ret_hmac,
size_t *ret_hmac_size);
int fido2_generate_hmac_hash(
const char *device,
const char *rp_id,
const char *rp_name,
const void *user_id, size_t user_id_len,
const char *user_name,
const char *user_display_name,
const char *user_icon,
const char *askpw_icon_name,
Fido2EnrollFlags lock_with,
int cred_alg,
void **ret_cid, size_t *ret_cid_size,
void **ret_salt, size_t *ret_salt_size,
void **ret_secret, size_t *ret_secret_size,
char **ret_usedpin,
Fido2EnrollFlags *ret_locked_with);
int parse_fido2_algorithm(const char *s, int *ret);
#else
static inline int parse_fido2_algorithm(const char *s, int *ret) {
return -EOPNOTSUPP;
}
#endif
int fido2_list_devices(void);
int fido2_find_device_auto(char **ret);
int fido2_have_device(const char *device);
| 5,917 | 44.523077 | 125 |
h
|
null |
systemd-main/src/shared/libmount-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <stdio.h>
#include "libmount-util.h"
int libmount_parse(
const char *path,
FILE *source,
struct libmnt_table **ret_table,
struct libmnt_iter **ret_iter) {
_cleanup_(mnt_free_tablep) struct libmnt_table *table = NULL;
_cleanup_(mnt_free_iterp) struct libmnt_iter *iter = NULL;
int r;
/* Older libmount seems to require this. */
assert(!source || path);
table = mnt_new_table();
iter = mnt_new_iter(MNT_ITER_FORWARD);
if (!table || !iter)
return -ENOMEM;
/* If source or path are specified, we use on the functions which ignore utab.
* Only if both are empty, we use mnt_table_parse_mtab(). */
if (source)
r = mnt_table_parse_stream(table, source, path);
else if (path)
r = mnt_table_parse_file(table, path);
else
r = mnt_table_parse_mtab(table, NULL);
if (r < 0)
return r;
*ret_table = TAKE_PTR(table);
*ret_iter = TAKE_PTR(iter);
return 0;
}
int libmount_is_leaf(
struct libmnt_table *table,
struct libmnt_fs *fs) {
int r;
_cleanup_(mnt_free_iterp) struct libmnt_iter *iter_children = NULL;
iter_children = mnt_new_iter(MNT_ITER_FORWARD);
if (!iter_children)
return log_oom();
/* We care only whether it exists, it is unused */
_unused_ struct libmnt_fs *child;
r = mnt_table_next_child_fs(table, iter_children, fs, &child);
if (r < 0)
return r;
return r == 1;
}
| 1,751 | 28.2 | 86 |
c
|
null |
systemd-main/src/shared/libmount-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
/* This needs to be after sys/mount.h */
#include <libmount.h>
#include "macro.h"
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct libmnt_table*, mnt_free_table, NULL);
DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct libmnt_iter*, mnt_free_iter, NULL);
int libmount_parse(
const char *path,
FILE *source,
struct libmnt_table **ret_table,
struct libmnt_iter **ret_iter);
int libmount_is_leaf(
struct libmnt_table *table,
struct libmnt_fs *fs);
| 589 | 27.095238 | 77 |
h
|
null |
systemd-main/src/shared/local-addresses.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <net/if_arp.h>
#include "sd-netlink.h"
#include "alloc-util.h"
#include "fd-util.h"
#include "local-addresses.h"
#include "macro.h"
#include "netlink-util.h"
#include "sort-util.h"
static int address_compare(const struct local_address *a, const struct local_address *b) {
int r;
/* Order lowest scope first, IPv4 before IPv6, lowest interface index first */
if (a->family == AF_INET && b->family == AF_INET6)
return -1;
if (a->family == AF_INET6 && b->family == AF_INET)
return 1;
r = CMP(a->scope, b->scope);
if (r != 0)
return r;
r = CMP(a->metric, b->metric);
if (r != 0)
return r;
r = CMP(a->ifindex, b->ifindex);
if (r != 0)
return r;
return memcmp(&a->address, &b->address, FAMILY_ADDRESS_SIZE(a->family));
}
static void suppress_duplicates(struct local_address *list, size_t *n_list) {
size_t old_size, new_size;
/* Removes duplicate entries, assumes the list of addresses is already sorted. Updates in-place. */
if (*n_list < 2) /* list with less than two entries can't have duplicates */
return;
old_size = *n_list;
new_size = 1;
for (size_t i = 1; i < old_size; i++) {
if (address_compare(list + i, list + new_size - 1) == 0)
continue;
list[new_size++] = list[i];
}
*n_list = new_size;
}
int local_addresses(
sd_netlink *context,
int ifindex,
int af,
struct local_address **ret) {
_cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL, *reply = NULL;
_cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
_cleanup_free_ struct local_address *list = NULL;
size_t n_list = 0;
int r;
if (context)
rtnl = sd_netlink_ref(context);
else {
r = sd_netlink_open(&rtnl);
if (r < 0)
return r;
}
r = sd_rtnl_message_new_addr(rtnl, &req, RTM_GETADDR, ifindex, af);
if (r < 0)
return r;
r = sd_netlink_message_set_request_dump(req, true);
if (r < 0)
return r;
r = sd_netlink_call(rtnl, req, 0, &reply);
if (r < 0)
return r;
for (sd_netlink_message *m = reply; m; m = sd_netlink_message_next(m)) {
struct local_address *a;
unsigned char flags;
uint16_t type;
int ifi, family;
r = sd_netlink_message_get_errno(m);
if (r < 0)
return r;
r = sd_netlink_message_get_type(m, &type);
if (r < 0)
return r;
if (type != RTM_NEWADDR)
continue;
r = sd_rtnl_message_addr_get_ifindex(m, &ifi);
if (r < 0)
return r;
if (ifindex > 0 && ifi != ifindex)
continue;
r = sd_rtnl_message_addr_get_family(m, &family);
if (r < 0)
return r;
if (af != AF_UNSPEC && af != family)
continue;
r = sd_rtnl_message_addr_get_flags(m, &flags);
if (r < 0)
return r;
if (flags & IFA_F_DEPRECATED)
continue;
if (!GREEDY_REALLOC0(list, n_list+1))
return -ENOMEM;
a = list + n_list;
r = sd_rtnl_message_addr_get_scope(m, &a->scope);
if (r < 0)
return r;
if (ifindex == 0 && IN_SET(a->scope, RT_SCOPE_HOST, RT_SCOPE_NOWHERE))
continue;
switch (family) {
case AF_INET:
r = sd_netlink_message_read_in_addr(m, IFA_LOCAL, &a->address.in);
if (r < 0) {
r = sd_netlink_message_read_in_addr(m, IFA_ADDRESS, &a->address.in);
if (r < 0)
continue;
}
break;
case AF_INET6:
r = sd_netlink_message_read_in6_addr(m, IFA_LOCAL, &a->address.in6);
if (r < 0) {
r = sd_netlink_message_read_in6_addr(m, IFA_ADDRESS, &a->address.in6);
if (r < 0)
continue;
}
break;
default:
continue;
}
a->ifindex = ifi;
a->family = family;
n_list++;
};
if (ret) {
typesafe_qsort(list, n_list, address_compare);
suppress_duplicates(list, &n_list);
*ret = TAKE_PTR(list);
}
return (int) n_list;
}
static int add_local_gateway(
struct local_address **list,
size_t *n_list,
int af,
int ifindex,
uint32_t metric,
const RouteVia *via) {
assert(list);
assert(n_list);
assert(via);
if (af != AF_UNSPEC && af != via->family)
return 0;
if (!GREEDY_REALLOC(*list, *n_list + 1))
return -ENOMEM;
(*list)[(*n_list)++] = (struct local_address) {
.ifindex = ifindex,
.metric = metric,
.family = via->family,
.address = via->address,
};
return 0;
}
int local_gateways(
sd_netlink *context,
int ifindex,
int af,
struct local_address **ret) {
_cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL, *reply = NULL;
_cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
_cleanup_free_ struct local_address *list = NULL;
size_t n_list = 0;
int r;
if (context)
rtnl = sd_netlink_ref(context);
else {
r = sd_netlink_open(&rtnl);
if (r < 0)
return r;
}
r = sd_rtnl_message_new_route(rtnl, &req, RTM_GETROUTE, af, RTPROT_UNSPEC);
if (r < 0)
return r;
r = sd_rtnl_message_route_set_type(req, RTN_UNICAST);
if (r < 0)
return r;
r = sd_rtnl_message_route_set_table(req, RT_TABLE_MAIN);
if (r < 0)
return r;
r = sd_netlink_message_set_request_dump(req, true);
if (r < 0)
return r;
r = sd_netlink_call(rtnl, req, 0, &reply);
if (r < 0)
return r;
for (sd_netlink_message *m = reply; m; m = sd_netlink_message_next(m)) {
_cleanup_ordered_set_free_free_ OrderedSet *multipath_routes = NULL;
_cleanup_free_ void *rta_multipath = NULL;
union in_addr_union gateway;
uint16_t type;
unsigned char dst_len, src_len, table;
uint32_t ifi = 0, metric = 0;
size_t rta_len;
int family;
RouteVia via;
r = sd_netlink_message_get_errno(m);
if (r < 0)
return r;
r = sd_netlink_message_get_type(m, &type);
if (r < 0)
return r;
if (type != RTM_NEWROUTE)
continue;
/* We only care for default routes */
r = sd_rtnl_message_route_get_dst_prefixlen(m, &dst_len);
if (r < 0)
return r;
if (dst_len != 0)
continue;
r = sd_rtnl_message_route_get_src_prefixlen(m, &src_len);
if (r < 0)
return r;
if (src_len != 0)
continue;
r = sd_rtnl_message_route_get_table(m, &table);
if (r < 0)
return r;
if (table != RT_TABLE_MAIN)
continue;
r = sd_netlink_message_read_u32(m, RTA_PRIORITY, &metric);
if (r < 0 && r != -ENODATA)
return r;
r = sd_rtnl_message_route_get_family(m, &family);
if (r < 0)
return r;
if (!IN_SET(family, AF_INET, AF_INET6))
continue;
r = sd_netlink_message_read_u32(m, RTA_OIF, &ifi);
if (r < 0 && r != -ENODATA)
return r;
if (r >= 0) {
if (ifi <= 0)
return -EINVAL;
if (ifindex > 0 && (int) ifi != ifindex)
continue;
r = netlink_message_read_in_addr_union(m, RTA_GATEWAY, family, &gateway);
if (r < 0 && r != -ENODATA)
return r;
if (r >= 0) {
via.family = family;
via.address = gateway;
r = add_local_gateway(&list, &n_list, af, ifi, metric, &via);
if (r < 0)
return r;
continue;
}
if (family != AF_INET)
continue;
r = sd_netlink_message_read(m, RTA_VIA, sizeof(via), &via);
if (r < 0 && r != -ENODATA)
return r;
if (r >= 0) {
r = add_local_gateway(&list, &n_list, af, ifi, metric, &via);
if (r < 0)
return r;
continue;
}
}
r = sd_netlink_message_read_data(m, RTA_MULTIPATH, &rta_len, &rta_multipath);
if (r < 0 && r != -ENODATA)
return r;
if (r >= 0) {
MultipathRoute *mr;
r = rtattr_read_nexthop(rta_multipath, rta_len, family, &multipath_routes);
if (r < 0)
return r;
ORDERED_SET_FOREACH(mr, multipath_routes) {
if (ifindex > 0 && mr->ifindex != ifindex)
continue;
r = add_local_gateway(&list, &n_list, af, ifi, metric, &mr->gateway);
if (r < 0)
return r;
}
}
}
if (ret) {
typesafe_qsort(list, n_list, address_compare);
suppress_duplicates(list, &n_list);
*ret = TAKE_PTR(list);
}
return (int) n_list;
}
int local_outbounds(
sd_netlink *context,
int ifindex,
int af,
struct local_address **ret) {
_cleanup_free_ struct local_address *list = NULL, *gateways = NULL;
size_t n_list = 0;
int r, n_gateways;
/* Determines our default outbound addresses, i.e. the "primary" local addresses we use to talk to IP
* addresses behind the default routes. This is still an address of the local host (i.e. this doesn't
* resolve NAT or so), but it's the set of addresses the local IP stack most likely uses to talk to
* other hosts.
*
* This works by connect()ing a SOCK_DGRAM socket to the local gateways, and then reading the IP
* address off the socket that was chosen for the routing decision. */
n_gateways = local_gateways(context, ifindex, af, &gateways);
if (n_gateways < 0)
return n_gateways;
if (n_gateways == 0) {
/* No gateways? Then we have no outbound addresses either. */
if (ret)
*ret = NULL;
return 0;
}
for (int i = 0; i < n_gateways; i++) {
_cleanup_close_ int fd = -EBADF;
union sockaddr_union sa;
socklen_t salen;
fd = socket(gateways[i].family, SOCK_DGRAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0);
if (fd < 0)
return -errno;
switch (gateways[i].family) {
case AF_INET:
sa.in = (struct sockaddr_in) {
.sin_family = AF_INET,
.sin_addr = gateways[i].address.in,
.sin_port = htobe16(53), /* doesn't really matter which port we pick —
* we just care about the routing decision */
};
break;
case AF_INET6:
sa.in6 = (struct sockaddr_in6) {
.sin6_family = AF_INET6,
.sin6_addr = gateways[i].address.in6,
.sin6_port = htobe16(53),
.sin6_scope_id = gateways[i].ifindex,
};
break;
default:
assert_not_reached();
}
/* So ideally we'd just use IP_UNICAST_IF here to pass the ifindex info to the kernel before
* connect()ing, sot that it influences the routing decision. However, on current kernels
* IP_UNICAST_IF doesn't actually influence the routing decision for UDP — which I think
* should probably just be considered a bug. Once that bug is fixed this is the best API to
* use, since it is the most lightweight. */
r = socket_set_unicast_if(fd, gateways[i].family, gateways[i].ifindex);
if (r < 0)
log_debug_errno(r, "Failed to set unicast interface index %i, ignoring: %m", gateways[i].ifindex);
/* We'll also use SO_BINDTOINDEX. This requires CAP_NET_RAW on old kernels, hence there's a
* good chance this fails. Since 5.7 this restriction was dropped and the first
* SO_BINDTOINDEX on a socket may be done without privileges. This one has the benefit of
* really influencing the routing decision, i.e. this one definitely works for us — as long
* as we have the privileges for it. */
r = socket_bind_to_ifindex(fd, gateways[i].ifindex);
if (r < 0)
log_debug_errno(r, "Failed to bind socket to interface %i, ignoring: %m", gateways[i].ifindex);
/* Let's now connect() to the UDP socket, forcing the kernel to make a routing decision and
* auto-bind the socket. We ignore failures on this, since that failure might happen for a
* multitude of reasons (policy/firewall issues, who knows?) and some of them might be
* *after* the routing decision and the auto-binding already took place. If so we can still
* make use of the binding and return it. Hence, let's not unnecessarily fail early here: we
* can still easily detect if the auto-binding worked or not, by comparing the bound IP
* address with zero — which we do below. */
if (connect(fd, &sa.sa, SOCKADDR_LEN(sa)) < 0)
log_debug_errno(errno, "Failed to connect SOCK_DGRAM socket to gateway, ignoring: %m");
/* Let's now read the socket address of the socket. A routing decision should have been
* made. Let's verify that and use the data. */
salen = SOCKADDR_LEN(sa);
if (getsockname(fd, &sa.sa, &salen) < 0)
return -errno;
assert(sa.sa.sa_family == gateways[i].family);
assert(salen == SOCKADDR_LEN(sa));
switch (gateways[i].family) {
case AF_INET:
if (in4_addr_is_null(&sa.in.sin_addr)) /* Auto-binding didn't work. :-( */
continue;
if (!GREEDY_REALLOC(list, n_list+1))
return -ENOMEM;
list[n_list++] = (struct local_address) {
.family = gateways[i].family,
.ifindex = gateways[i].ifindex,
.address.in = sa.in.sin_addr,
};
break;
case AF_INET6:
if (in6_addr_is_null(&sa.in6.sin6_addr))
continue;
if (!GREEDY_REALLOC(list, n_list+1))
return -ENOMEM;
list[n_list++] = (struct local_address) {
.family = gateways[i].family,
.ifindex = gateways[i].ifindex,
.address.in6 = sa.in6.sin6_addr,
};
break;
default:
assert_not_reached();
}
}
if (ret) {
typesafe_qsort(list, n_list, address_compare);
suppress_duplicates(list, &n_list);
*ret = TAKE_PTR(list);
}
return (int) n_list;
}
| 18,423 | 35.33925 | 122 |
c
|
null |
systemd-main/src/shared/local-addresses.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "sd-netlink.h"
#include "in-addr-util.h"
struct local_address {
int family, ifindex;
unsigned char scope;
uint32_t metric;
union in_addr_union address;
};
int local_addresses(sd_netlink *rtnl, int ifindex, int af, struct local_address **ret);
int local_gateways(sd_netlink *rtnl, int ifindex, int af, struct local_address **ret);
int local_outbounds(sd_netlink *rtnl, int ifindex, int af, struct local_address **ret);
| 527 | 25.4 | 87 |
h
|
null |
systemd-main/src/shared/locale-setup.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <sys/stat.h>
#include "env-file-label.h"
#include "env-file.h"
#include "env-util.h"
#include "errno-util.h"
#include "fd-util.h"
#include "locale-setup.h"
#include "proc-cmdline.h"
#include "stat-util.h"
#include "strv.h"
void locale_context_clear(LocaleContext *c) {
assert(c);
c->st = (struct stat) {};
for (LocaleVariable i = 0; i < _VARIABLE_LC_MAX; i++)
c->locale[i] = mfree(c->locale[i]);
}
static int locale_context_load_proc(LocaleContext *c, LocaleLoadFlag flag) {
int r;
assert(c);
if (!FLAGS_SET(flag, LOCALE_LOAD_PROC_CMDLINE))
return 0;
locale_context_clear(c);
r = proc_cmdline_get_key_many(PROC_CMDLINE_STRIP_RD_PREFIX,
"locale.LANG", &c->locale[VARIABLE_LANG],
"locale.LANGUAGE", &c->locale[VARIABLE_LANGUAGE],
"locale.LC_CTYPE", &c->locale[VARIABLE_LC_CTYPE],
"locale.LC_NUMERIC", &c->locale[VARIABLE_LC_NUMERIC],
"locale.LC_TIME", &c->locale[VARIABLE_LC_TIME],
"locale.LC_COLLATE", &c->locale[VARIABLE_LC_COLLATE],
"locale.LC_MONETARY", &c->locale[VARIABLE_LC_MONETARY],
"locale.LC_MESSAGES", &c->locale[VARIABLE_LC_MESSAGES],
"locale.LC_PAPER", &c->locale[VARIABLE_LC_PAPER],
"locale.LC_NAME", &c->locale[VARIABLE_LC_NAME],
"locale.LC_ADDRESS", &c->locale[VARIABLE_LC_ADDRESS],
"locale.LC_TELEPHONE", &c->locale[VARIABLE_LC_TELEPHONE],
"locale.LC_MEASUREMENT", &c->locale[VARIABLE_LC_MEASUREMENT],
"locale.LC_IDENTIFICATION", &c->locale[VARIABLE_LC_IDENTIFICATION]);
if (r == -ENOENT)
return 0;
if (r < 0)
return log_debug_errno(r, "Failed to read /proc/cmdline: %m");
return r;
}
static int locale_context_load_conf(LocaleContext *c, LocaleLoadFlag flag) {
_cleanup_close_ int fd = -EBADF;
struct stat st;
int r;
assert(c);
if (!FLAGS_SET(flag, LOCALE_LOAD_LOCALE_CONF))
return 0;
fd = RET_NERRNO(open("/etc/locale.conf", O_CLOEXEC | O_PATH));
if (fd == -ENOENT)
return 0;
if (fd < 0)
return log_debug_errno(errno, "Failed to open /etc/locale.conf: %m");
if (fstat(fd, &st) < 0)
return log_debug_errno(errno, "Failed to stat /etc/locale.conf: %m");
/* If the file is not changed, then we do not need to re-read the file. */
if (stat_inode_unmodified(&c->st, &st))
return 0;
c->st = st;
locale_context_clear(c);
r = parse_env_file_fd(fd, "/etc/locale.conf",
"LANG", &c->locale[VARIABLE_LANG],
"LANGUAGE", &c->locale[VARIABLE_LANGUAGE],
"LC_CTYPE", &c->locale[VARIABLE_LC_CTYPE],
"LC_NUMERIC", &c->locale[VARIABLE_LC_NUMERIC],
"LC_TIME", &c->locale[VARIABLE_LC_TIME],
"LC_COLLATE", &c->locale[VARIABLE_LC_COLLATE],
"LC_MONETARY", &c->locale[VARIABLE_LC_MONETARY],
"LC_MESSAGES", &c->locale[VARIABLE_LC_MESSAGES],
"LC_PAPER", &c->locale[VARIABLE_LC_PAPER],
"LC_NAME", &c->locale[VARIABLE_LC_NAME],
"LC_ADDRESS", &c->locale[VARIABLE_LC_ADDRESS],
"LC_TELEPHONE", &c->locale[VARIABLE_LC_TELEPHONE],
"LC_MEASUREMENT", &c->locale[VARIABLE_LC_MEASUREMENT],
"LC_IDENTIFICATION", &c->locale[VARIABLE_LC_IDENTIFICATION]);
if (r < 0)
return log_debug_errno(r, "Failed to read /etc/locale.conf: %m");
return 1; /* loaded */
}
static int locale_context_load_env(LocaleContext *c, LocaleLoadFlag flag) {
int r;
assert(c);
if (!FLAGS_SET(flag, LOCALE_LOAD_ENVIRONMENT))
return 0;
locale_context_clear(c);
/* Fill in what we got passed from systemd. */
for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++) {
const char *name = ASSERT_PTR(locale_variable_to_string(p));
r = free_and_strdup(&c->locale[p], empty_to_null(getenv(name)));
if (r < 0)
return log_oom_debug();
}
return 1; /* loaded */
}
int locale_context_load(LocaleContext *c, LocaleLoadFlag flag) {
int r;
assert(c);
r = locale_context_load_proc(c, flag);
if (r > 0)
goto finalize;
r = locale_context_load_conf(c, flag);
if (r != 0)
goto finalize;
r = locale_context_load_env(c, flag);
finalize:
if (r <= 0) {
/* Nothing loaded, or error. */
locale_context_clear(c);
return r;
}
if (FLAGS_SET(flag, LOCALE_LOAD_SIMPLIFY))
locale_variables_simplify(c->locale);
return 0;
}
int locale_context_build_env(const LocaleContext *c, char ***ret_set, char ***ret_unset) {
_cleanup_strv_free_ char **set = NULL, **unset = NULL;
int r;
assert(c);
if (!ret_set && !ret_unset)
return 0;
for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++) {
const char *name = ASSERT_PTR(locale_variable_to_string(p));
if (isempty(c->locale[p])) {
if (!ret_unset)
continue;
r = strv_extend(&unset, name);
} else {
if (!ret_set)
continue;
r = strv_env_assign(&set, name, c->locale[p]);
}
if (r < 0)
return r;
}
if (ret_set)
*ret_set = TAKE_PTR(set);
if (ret_unset)
*ret_unset = TAKE_PTR(unset);
return 0;
}
int locale_context_save(LocaleContext *c, char ***ret_set, char ***ret_unset) {
_cleanup_strv_free_ char **set = NULL, **unset = NULL;
int r;
assert(c);
/* Set values will be returned as strv in *ret on success. */
r = locale_context_build_env(c, &set, ret_unset ? &unset : NULL);
if (r < 0)
return r;
if (strv_isempty(set)) {
if (unlink("/etc/locale.conf") < 0)
return errno == ENOENT ? 0 : -errno;
c->st = (struct stat) {};
if (ret_set)
*ret_set = NULL;
if (ret_unset)
*ret_unset = NULL;
return 0;
}
r = write_env_file_label("/etc/locale.conf", set);
if (r < 0)
return r;
if (stat("/etc/locale.conf", &c->st) < 0)
return -errno;
if (ret_set)
*ret_set = TAKE_PTR(set);
if (ret_unset)
*ret_unset = TAKE_PTR(unset);
return 0;
}
int locale_context_merge(const LocaleContext *c, char *l[_VARIABLE_LC_MAX]) {
assert(c);
assert(l);
for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++)
if (!isempty(c->locale[p]) && isempty(l[p])) {
l[p] = strdup(c->locale[p]);
if (!l[p])
return -ENOMEM;
}
return 0;
}
void locale_context_take(LocaleContext *c, char *l[_VARIABLE_LC_MAX]) {
assert(c);
assert(l);
for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++)
free_and_replace(c->locale[p], l[p]);
}
bool locale_context_equal(const LocaleContext *c, char *l[_VARIABLE_LC_MAX]) {
assert(c);
assert(l);
for (LocaleVariable p = 0; p < _VARIABLE_LC_MAX; p++)
if (!streq_ptr(c->locale[p], l[p]))
return false;
return true;
}
int locale_setup(char ***environment) {
_cleanup_(locale_context_clear) LocaleContext c = {};
_cleanup_strv_free_ char **add = NULL;
int r;
assert(environment);
r = locale_context_load(&c, LOCALE_LOAD_PROC_CMDLINE | LOCALE_LOAD_LOCALE_CONF);
if (r < 0)
return r;
r = locale_context_build_env(&c, &add, NULL);
if (r < 0)
return r;
if (strv_isempty(add)) {
/* If no locale is configured then default to compile-time default. */
add = strv_new("LANG=" SYSTEMD_DEFAULT_LOCALE);
if (!add)
return -ENOMEM;
}
if (strv_isempty(*environment))
strv_free_and_replace(*environment, add);
else {
char **merged;
merged = strv_env_merge(*environment, add);
if (!merged)
return -ENOMEM;
strv_free_and_replace(*environment, merged);
}
return 0;
}
| 9,895 | 32.545763 | 106 |
c
|
null |
systemd-main/src/shared/locale-setup.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <sys/stat.h>
#include "locale-util.h"
typedef struct LocaleContext {
struct stat st;
char *locale[_VARIABLE_LC_MAX];
} LocaleContext;
typedef enum LocaleLoadFlag {
LOCALE_LOAD_PROC_CMDLINE = 1 << 0,
LOCALE_LOAD_LOCALE_CONF = 1 << 1,
LOCALE_LOAD_ENVIRONMENT = 1 << 2,
LOCALE_LOAD_SIMPLIFY = 1 << 3,
} LocaleLoadFlag;
void locale_context_clear(LocaleContext *c);
int locale_context_load(LocaleContext *c, LocaleLoadFlag flag);
int locale_context_build_env(const LocaleContext *c, char ***ret_set, char ***ret_unset);
int locale_context_save(LocaleContext *c, char ***ret_set, char ***ret_unset);
int locale_context_merge(const LocaleContext *c, char *l[_VARIABLE_LC_MAX]);
void locale_context_take(LocaleContext *c, char *l[_VARIABLE_LC_MAX]);
bool locale_context_equal(const LocaleContext *c, char *l[_VARIABLE_LC_MAX]);
int locale_setup(char ***environment);
| 991 | 32.066667 | 89 |
h
|
null |
systemd-main/src/shared/logs-show.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 "sd-id128.h"
#include "sd-journal.h"
#include "macro.h"
#include "output-mode.h"
#include "time-util.h"
int show_journal_entry(
FILE *f,
sd_journal *j,
OutputMode mode,
unsigned n_columns,
OutputFlags flags,
Set *output_fields,
const size_t highlight[2],
bool *ellipsized,
dual_timestamp *previous_display_ts,
sd_id128_t *previous_boot_id);
int show_journal(
FILE *f,
sd_journal *j,
OutputMode mode,
unsigned n_columns,
usec_t not_before,
unsigned how_many,
OutputFlags flags,
bool *ellipsized);
int add_match_boot_id(sd_journal *j, sd_id128_t id);
int add_match_this_boot(sd_journal *j, const char *machine);
int add_matches_for_unit(
sd_journal *j,
const char *unit);
int add_matches_for_user_unit(
sd_journal *j,
const char *unit,
uid_t uid);
int show_journal_by_unit(
FILE *f,
const char *unit,
const char *namespace,
OutputMode mode,
unsigned n_columns,
usec_t not_before,
unsigned how_many,
uid_t uid,
OutputFlags flags,
int journal_open_flags,
bool system_unit,
bool *ellipsized);
void json_escape(
FILE *f,
const char* p,
size_t l,
OutputFlags flags);
| 1,847 | 26.176471 | 60 |
h
|
null |
systemd-main/src/shared/loopback-setup.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <net/if.h>
#include <stdlib.h>
#include "sd-netlink.h"
#include "loopback-setup.h"
#include "missing_network.h"
#include "netlink-util.h"
#include "time-util.h"
#define LOOPBACK_SETUP_TIMEOUT_USEC (5 * USEC_PER_SEC)
struct state {
unsigned n_messages;
int rcode;
const char *error_message;
const char *success_message;
const char *eexist_message;
};
static int generic_handler(sd_netlink *rtnl, sd_netlink_message *m, void *userdata) {
struct state *s = ASSERT_PTR(userdata);
int r;
assert(s->n_messages > 0);
s->n_messages--;
errno = 0;
r = sd_netlink_message_get_errno(m);
if (r == -EEXIST && s->eexist_message)
log_debug_errno(r, "%s", s->eexist_message);
else if (r < 0)
log_debug_errno(r, "%s: %m", s->error_message);
else
log_debug("%s", s->success_message);
s->rcode = r;
return 0;
}
static int start_loopback(sd_netlink *rtnl, struct state *s) {
_cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
int r;
assert(rtnl);
assert(s);
r = sd_rtnl_message_new_link(rtnl, &req, RTM_SETLINK, LOOPBACK_IFINDEX);
if (r < 0)
return r;
r = sd_rtnl_message_link_set_flags(req, IFF_UP, IFF_UP);
if (r < 0)
return r;
r = sd_netlink_call_async(rtnl, NULL, req, generic_handler, NULL, s, LOOPBACK_SETUP_TIMEOUT_USEC, "systemd-start-loopback");
if (r < 0)
return r;
s->n_messages ++;
return 0;
}
static int add_ipv4_address(sd_netlink *rtnl, struct state *s) {
_cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
int r;
assert(rtnl);
assert(s);
r = sd_rtnl_message_new_addr(rtnl, &req, RTM_NEWADDR, LOOPBACK_IFINDEX, AF_INET);
if (r < 0)
return r;
r = sd_rtnl_message_addr_set_prefixlen(req, 8);
if (r < 0)
return r;
r = sd_rtnl_message_addr_set_flags(req, IFA_F_PERMANENT);
if (r < 0)
return r;
r = sd_rtnl_message_addr_set_scope(req, RT_SCOPE_HOST);
if (r < 0)
return r;
r = sd_netlink_message_append_in_addr(req, IFA_LOCAL, &(struct in_addr) { .s_addr = htobe32(INADDR_LOOPBACK) } );
if (r < 0)
return r;
r = sd_netlink_call_async(rtnl, NULL, req, generic_handler, NULL, s, USEC_INFINITY, "systemd-loopback-ipv4");
if (r < 0)
return r;
s->n_messages ++;
return 0;
}
static int add_ipv6_address(sd_netlink *rtnl, struct state *s) {
_cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL;
int r;
assert(rtnl);
assert(s);
r = sd_rtnl_message_new_addr(rtnl, &req, RTM_NEWADDR, LOOPBACK_IFINDEX, AF_INET6);
if (r < 0)
return r;
r = sd_rtnl_message_addr_set_prefixlen(req, 128);
if (r < 0)
return r;
uint32_t flags = IFA_F_PERMANENT|IFA_F_NOPREFIXROUTE;
r = sd_rtnl_message_addr_set_flags(req, flags & 0xffu); /* rtnetlink wants low 8 bit of flags via regular flags field… */
if (r < 0)
return r;
if ((flags & ~0xffu) != 0) {
r = sd_netlink_message_append_u32(req, IFA_FLAGS, flags); /* …and the rest of the flags via IFA_FLAGS */
if (r < 0)
return r;
}
r = sd_rtnl_message_addr_set_scope(req, RT_SCOPE_HOST);
if (r < 0)
return r;
r = sd_netlink_message_append_in6_addr(req, IFA_LOCAL, &in6addr_loopback);
if (r < 0)
return r;
r = sd_netlink_call_async(rtnl, NULL, req, generic_handler, NULL, s, USEC_INFINITY, "systemd-loopback-ipv6");
if (r < 0)
return r;
s->n_messages ++;
return 0;
}
static int check_loopback(sd_netlink *rtnl) {
_cleanup_(sd_netlink_message_unrefp) sd_netlink_message *req = NULL, *reply = NULL;
unsigned flags;
int r;
r = sd_rtnl_message_new_link(rtnl, &req, RTM_GETLINK, LOOPBACK_IFINDEX);
if (r < 0)
return r;
r = sd_netlink_call(rtnl, req, USEC_INFINITY, &reply);
if (r < 0)
return r;
r = sd_rtnl_message_link_get_flags(reply, &flags);
if (r < 0)
return r;
return flags & IFF_UP;
}
int loopback_setup(void) {
_cleanup_(sd_netlink_unrefp) sd_netlink *rtnl = NULL;
struct state state_4 = {
.error_message = "Failed to add address 127.0.0.1 to loopback interface",
.success_message = "Successfully added address 127.0.0.1 to loopback interface",
.eexist_message = "127.0.0.1 has already been added to loopback interface",
}, state_6 = {
.error_message = "Failed to add address ::1 to loopback interface",
.success_message = "Successfully added address ::1 to loopback interface",
.eexist_message = "::1 has already been added to loopback interface",
}, state_up = {
.error_message = "Failed to bring loopback interface up",
.success_message = "Successfully brought loopback interface up",
};
int r;
/* Note, we, generally assume callers ignore the return code here (except test cases), hence only log add LOG_WARN level. */
r = sd_netlink_open(&rtnl);
if (r < 0)
return log_warning_errno(r, "Failed to open netlink, ignoring: %m");
/* Note that we add the IP addresses here explicitly even though the kernel does that too implicitly when
* setting up the loopback device. The reason we do this here a second time (and possibly race against the
* kernel) is that we want to synchronously wait until the IP addresses are set up correctly, see
*
* https://github.com/systemd/systemd/issues/5641 */
r = add_ipv4_address(rtnl, &state_4);
if (r < 0)
return log_warning_errno(r, "Failed to enqueue IPv4 loopback address add request, ignoring: %m");
r = add_ipv6_address(rtnl, &state_6);
if (r < 0)
return log_warning_errno(r, "Failed to enqueue IPv6 loopback address add request, ignoring: %m");
r = start_loopback(rtnl, &state_up);
if (r < 0)
return log_warning_errno(r, "Failed to enqueue loopback interface start request, ignoring: %m");
while (state_4.n_messages + state_6.n_messages + state_up.n_messages > 0) {
r = sd_netlink_wait(rtnl, LOOPBACK_SETUP_TIMEOUT_USEC);
if (r < 0)
return log_warning_errno(r, "Failed to wait for netlink event, ignoring: %m");
r = sd_netlink_process(rtnl, NULL);
if (r < 0)
return log_warning_errno(r, "Failed to process netlink event, ignoring: %m");
}
/* Note that we don't really care whether the addresses could be added or not */
if (state_up.rcode != 0) {
/* If we lack the permissions to configure the loopback device, but we find it to be already
* configured, let's exit cleanly, in order to supported unprivileged containers. */
if (ERRNO_IS_PRIVILEGE(state_up.rcode)) {
r = check_loopback(rtnl);
if (r < 0)
log_debug_errno(r, "Failed to check if loopback device might already be up, ignoring: %m");
else if (r > 0) {
log_debug("Configuring loopback failed, but device is already up, suppressing failure.");
return 0;
}
}
return log_warning_errno(state_up.rcode, "Failed to configure loopback network device, ignoring: %m");
}
return 0;
}
| 8,242 | 34.377682 | 132 |
c
|
null |
systemd-main/src/shared/lsm-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "extract-word.h"
#include "fileio.h"
#include "lsm-util.h"
#include "string-util.h"
int lsm_supported(const char *name) {
_cleanup_free_ char *lsm_list = NULL;
int r;
assert(name);
r = read_one_line_file("/sys/kernel/security/lsm", &lsm_list);
if (r == -ENOENT) /* LSM support not available at all? */
return false;
if (r < 0)
return log_debug_errno(r, "Failed to read /sys/kernel/security/lsm: %m");
for (const char *p = lsm_list;;) {
_cleanup_free_ char *word = NULL;
r = extract_first_word(&p, &word, ",", 0);
if (r == 0)
return false;
if (r < 0)
return log_debug_errno(r, "Failed to parse /sys/kernel/security/lsm: %m");
if (streq(word, name))
return true;
}
}
| 1,002 | 28.5 | 98 |
c
|
null |
systemd-main/src/shared/machine-pool.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include "btrfs-util.h"
#include "label-util.h"
#include "machine-pool.h"
#include "missing_magic.h"
#include "stat-util.h"
static int check_btrfs(void) {
struct statfs sfs;
if (statfs("/var/lib/machines", &sfs) < 0) {
if (errno != ENOENT)
return -errno;
if (statfs("/var/lib", &sfs) < 0)
return -errno;
}
return F_TYPE_EQUAL(sfs.f_type, BTRFS_SUPER_MAGIC);
}
int setup_machine_directory(sd_bus_error *error, bool use_btrfs_subvol, bool use_btrfs_quota) {
int r;
r = check_btrfs();
if (r < 0)
return sd_bus_error_set_errnof(error, r, "Failed to determine whether /var/lib/machines is located on btrfs: %m");
if (r == 0)
return 0;
if (!use_btrfs_subvol)
return 0;
(void) btrfs_subvol_make_label("/var/lib/machines");
if (!use_btrfs_quota)
return 0;
r = btrfs_quota_enable("/var/lib/machines", true);
if (r < 0)
log_warning_errno(r, "Failed to enable quota for /var/lib/machines, ignoring: %m");
r = btrfs_subvol_auto_qgroup("/var/lib/machines", 0, true);
if (r < 0)
log_warning_errno(r, "Failed to set up default quota hierarchy for /var/lib/machines, ignoring: %m");
return 0;
}
| 1,465 | 27.192308 | 130 |
c
|
null |
systemd-main/src/shared/macvlan-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "conf-parser.h"
#include "macvlan-util.h"
#include "string-table.h"
static const char* const macvlan_mode_table[_NETDEV_MACVLAN_MODE_MAX] = {
[NETDEV_MACVLAN_MODE_PRIVATE] = "private",
[NETDEV_MACVLAN_MODE_VEPA] = "vepa",
[NETDEV_MACVLAN_MODE_BRIDGE] = "bridge",
[NETDEV_MACVLAN_MODE_PASSTHRU] = "passthru",
[NETDEV_MACVLAN_MODE_SOURCE] = "source",
};
DEFINE_STRING_TABLE_LOOKUP(macvlan_mode, MacVlanMode);
| 508 | 30.8125 | 73 |
c
|
null |
systemd-main/src/shared/macvlan-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/if_link.h>
typedef enum MacVlanMode {
NETDEV_MACVLAN_MODE_PRIVATE = MACVLAN_MODE_PRIVATE,
NETDEV_MACVLAN_MODE_VEPA = MACVLAN_MODE_VEPA,
NETDEV_MACVLAN_MODE_BRIDGE = MACVLAN_MODE_BRIDGE,
NETDEV_MACVLAN_MODE_PASSTHRU = MACVLAN_MODE_PASSTHRU,
NETDEV_MACVLAN_MODE_SOURCE = MACVLAN_MODE_SOURCE,
_NETDEV_MACVLAN_MODE_MAX,
_NETDEV_MACVLAN_MODE_INVALID = -EINVAL,
} MacVlanMode;
const char *macvlan_mode_to_string(MacVlanMode d) _const_;
MacVlanMode macvlan_mode_from_string(const char *d) _pure_;
| 627 | 33.888889 | 61 |
h
|
null |
systemd-main/src/shared/main-func.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdlib.h>
#include "sd-daemon.h"
#include "argv-util.h"
#include "pager.h"
#include "selinux-util.h"
#include "spawn-ask-password-agent.h"
#include "spawn-polkit-agent.h"
#include "static-destruct.h"
#define _DEFINE_MAIN_FUNCTION(intro, impl, ret) \
int main(int argc, char *argv[]) { \
int r; \
assert_se(argc > 0 && !isempty(argv[0])); \
save_argc_argv(argc, argv); \
intro; \
r = impl; \
if (r < 0) \
(void) sd_notifyf(0, "ERRNO=%i", -r); \
(void) sd_notifyf(0, "EXIT_STATUS=%i", ret); \
ask_password_agent_close(); \
polkit_agent_close(); \
pager_close(); \
mac_selinux_finish(); \
static_destruct(); \
return ret; \
}
/* Negative return values from impl are mapped to EXIT_FAILURE, and
* everything else means success! */
#define DEFINE_MAIN_FUNCTION(impl) \
_DEFINE_MAIN_FUNCTION(,impl(argc, argv), r < 0 ? EXIT_FAILURE : EXIT_SUCCESS)
/* Zero is mapped to EXIT_SUCCESS, negative values are mapped to EXIT_FAILURE,
* and positive values are propagated.
* Note: "true" means failure! */
#define DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(impl) \
_DEFINE_MAIN_FUNCTION(,impl(argc, argv), r < 0 ? EXIT_FAILURE : r)
| 2,038 | 46.418605 | 85 |
h
|
null |
systemd-main/src/shared/mkdir-label.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <sys/stat.h>
#include "errno-util.h"
#include "mkdir-label.h"
#include "selinux-util.h"
#include "smack-util.h"
#include "user-util.h"
int mkdirat_label(int dirfd, const char *path, mode_t mode) {
int r;
assert(path);
r = mac_selinux_create_file_prepare_at(dirfd, path, S_IFDIR);
if (r < 0)
return r;
r = RET_NERRNO(mkdirat(dirfd, path, mode));
mac_selinux_create_file_clear();
if (r < 0)
return r;
return mac_smack_fix_full(dirfd, path, NULL, 0);
}
int mkdirat_safe_label(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags) {
return mkdirat_safe_internal(dir_fd, path, mode, uid, gid, flags, mkdirat_label);
}
int mkdirat_parents_label(int dir_fd, const char *path, mode_t mode) {
return mkdirat_parents_internal(dir_fd, path, mode, UID_INVALID, UID_INVALID, 0, mkdirat_label);
}
int mkdir_parents_safe_label(const char *prefix, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags) {
return mkdir_parents_internal(prefix, path, mode, uid, gid, flags, mkdirat_label);
}
int mkdir_p_label(const char *path, mode_t mode) {
return mkdir_p_internal(NULL, path, mode, UID_INVALID, UID_INVALID, 0, mkdirat_label);
}
| 1,356 | 30.55814 | 121 |
c
|
null |
systemd-main/src/shared/mkdir-label.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <fcntl.h>
#include <sys/types.h>
#include "mkdir.h"
int mkdirat_label(int dirfd, const char *path, mode_t mode);
static inline int mkdir_label(const char *path, mode_t mode) {
return mkdirat_label(AT_FDCWD, path, mode);
}
int mkdirat_safe_label(int dir_fd, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags);
static inline int mkdir_safe_label(const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags) {
return mkdirat_safe_label(AT_FDCWD, path, mode, uid, gid, flags);
}
int mkdirat_parents_label(int dir_fd, const char *path, mode_t mod);
static inline int mkdir_parents_label(const char *path, mode_t mod) {
return mkdirat_parents_label(AT_FDCWD, path, mod);
}
int mkdir_parents_safe_label(const char *prefix, const char *path, mode_t mode, uid_t uid, gid_t gid, MkdirFlags flags);
int mkdir_p_label(const char *path, mode_t mode);
| 970 | 34.962963 | 120 |
h
|
null |
systemd-main/src/shared/mkfs-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <stdbool.h>
#include "sd-id128.h"
#include "strv.h"
int mkfs_exists(const char *fstype);
int mkfs_supports_root_option(const char *fstype);
int make_filesystem(
const char *node,
const char *fstype,
const char *label,
const char *root,
sd_id128_t uuid,
bool discard,
bool quiet,
uint64_t sector_size,
char * const *extra_mkfs_args);
int mkfs_options_from_env(const char *component, const char *fstype, char ***ret);
| 638 | 23.576923 | 82 |
h
|
null |
systemd-main/src/shared/module-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include "module-util.h"
#include "proc-cmdline.h"
#include "strv.h"
static int denylist_modules(const char *p, char ***denylist) {
_cleanup_strv_free_ char **k = NULL;
assert(p);
assert(denylist);
k = strv_split(p, ",");
if (!k)
return -ENOMEM;
if (strv_extend_strv(denylist, k, true) < 0)
return -ENOMEM;
return 0;
}
static int parse_proc_cmdline_item(const char *key, const char *value, void *data) {
int r;
if (proc_cmdline_key_streq(key, "module_blacklist")) {
if (proc_cmdline_value_missing(key, value))
return 0;
r = denylist_modules(value, data);
if (r < 0)
return r;
}
return 0;
}
int module_load_and_warn(struct kmod_ctx *ctx, const char *module, bool verbose) {
const int probe_flags = KMOD_PROBE_APPLY_BLACKLIST;
struct kmod_list *itr;
_cleanup_(kmod_module_unref_listp) struct kmod_list *modlist = NULL;
_cleanup_strv_free_ char **denylist = NULL;
bool denylist_parsed = false;
int r;
/* verbose==true means we should log at non-debug level if we
* fail to find or load the module. */
log_debug("Loading module: %s", module);
r = kmod_module_new_from_lookup(ctx, module, &modlist);
if (r < 0)
return log_full_errno(verbose ? LOG_ERR : LOG_DEBUG, r,
"Failed to look up module alias '%s': %m", module);
if (!modlist)
return log_full_errno(verbose ? LOG_ERR : LOG_DEBUG,
SYNTHETIC_ERRNO(ENOENT),
"Failed to find module '%s'", module);
kmod_list_foreach(itr, modlist) {
_cleanup_(kmod_module_unrefp) struct kmod_module *mod = NULL;
int state, err;
mod = kmod_module_get_module(itr);
state = kmod_module_get_initstate(mod);
switch (state) {
case KMOD_MODULE_BUILTIN:
log_full(verbose ? LOG_INFO : LOG_DEBUG,
"Module '%s' is built in", kmod_module_get_name(mod));
break;
case KMOD_MODULE_LIVE:
log_debug("Module '%s' is already loaded", kmod_module_get_name(mod));
break;
default:
err = kmod_module_probe_insert_module(mod, probe_flags,
NULL, NULL, NULL, NULL);
if (err == 0)
log_full(verbose ? LOG_INFO : LOG_DEBUG,
"Inserted module '%s'", kmod_module_get_name(mod));
else if (err == KMOD_PROBE_APPLY_BLACKLIST)
log_full(verbose ? LOG_INFO : LOG_DEBUG,
"Module '%s' is deny-listed (by kmod)", kmod_module_get_name(mod));
else {
assert(err < 0);
if (err == -EPERM) {
if (!denylist_parsed) {
r = proc_cmdline_parse(parse_proc_cmdline_item, &denylist, 0);
if (r < 0)
log_full_errno(!verbose ? LOG_DEBUG : LOG_WARNING,
r,
"Failed to parse kernel command line, ignoring: %m");
denylist_parsed = true;
}
if (strv_contains(denylist, kmod_module_get_name(mod))) {
log_full(verbose ? LOG_INFO : LOG_DEBUG,
"Module '%s' is deny-listed (by kernel)", kmod_module_get_name(mod));
continue;
}
}
log_full_errno(!verbose ? LOG_DEBUG :
err == -ENODEV ? LOG_NOTICE :
err == -ENOENT ? LOG_WARNING :
LOG_ERR,
err,
"Failed to insert module '%s': %m",
kmod_module_get_name(mod));
if (!IN_SET(err, -ENODEV, -ENOENT))
r = err;
}
}
}
return r;
}
| 5,161 | 40.296 | 126 |
c
|
null |
systemd-main/src/shared/net-condition.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <netinet/ether.h>
#include "condition.h"
#include "env-util.h"
#include "log.h"
#include "net-condition.h"
#include "netif-util.h"
#include "network-util.h"
#include "socket-util.h"
#include "string-table.h"
#include "strv.h"
#include "wifi-util.h"
void net_match_clear(NetMatch *match) {
if (!match)
return;
match->hw_addr = set_free(match->hw_addr);
match->permanent_hw_addr = set_free(match->permanent_hw_addr);
match->path = strv_free(match->path);
match->driver = strv_free(match->driver);
match->iftype = strv_free(match->iftype);
match->kind = strv_free(match->kind);
match->ifname = strv_free(match->ifname);
match->property = strv_free(match->property);
match->wlan_iftype = strv_free(match->wlan_iftype);
match->ssid = strv_free(match->ssid);
match->bssid = set_free(match->bssid);
}
bool net_match_is_empty(const NetMatch *match) {
assert(match);
return
set_isempty(match->hw_addr) &&
set_isempty(match->permanent_hw_addr) &&
strv_isempty(match->path) &&
strv_isempty(match->driver) &&
strv_isempty(match->iftype) &&
strv_isempty(match->kind) &&
strv_isempty(match->ifname) &&
strv_isempty(match->property) &&
strv_isempty(match->wlan_iftype) &&
strv_isempty(match->ssid) &&
set_isempty(match->bssid);
}
static bool net_condition_test_strv(char * const *patterns, const char *string) {
bool match = false, has_positive_rule = false;
if (strv_isempty(patterns))
return true;
STRV_FOREACH(p, patterns) {
const char *q = *p;
bool invert;
invert = *q == '!';
q += invert;
if (!invert)
has_positive_rule = true;
if (string && fnmatch(q, string, 0) == 0) {
if (invert)
return false;
else
match = true;
}
}
return has_positive_rule ? match : true;
}
static bool net_condition_test_ifname(char * const *patterns, const char *ifname, char * const *alternative_names) {
if (net_condition_test_strv(patterns, ifname))
return true;
STRV_FOREACH(p, alternative_names)
if (net_condition_test_strv(patterns, *p))
return true;
return false;
}
static int net_condition_test_property(char * const *match_property, sd_device *device) {
if (strv_isempty(match_property))
return true;
STRV_FOREACH(p, match_property) {
_cleanup_free_ char *key = NULL;
const char *val, *dev_val;
bool invert, v;
invert = **p == '!';
val = strchr(*p + invert, '=');
if (!val)
return -EINVAL;
key = strndup(*p + invert, val - *p - invert);
if (!key)
return -ENOMEM;
val++;
v = device &&
sd_device_get_property_value(device, key, &dev_val) >= 0 &&
fnmatch(val, dev_val, 0) == 0;
if (invert ? v : !v)
return false;
}
return true;
}
int net_match_config(
const NetMatch *match,
sd_device *device,
const struct hw_addr_data *hw_addr,
const struct hw_addr_data *permanent_hw_addr,
const char *driver,
unsigned short iftype,
const char *kind,
const char *ifname,
char * const *alternative_names,
enum nl80211_iftype wlan_iftype,
const char *ssid,
const struct ether_addr *bssid) {
_cleanup_free_ char *iftype_str = NULL;
const char *path = NULL;
assert(match);
if (net_get_type_string(device, iftype, &iftype_str) == -ENOMEM)
return -ENOMEM;
if (device)
(void) sd_device_get_property_value(device, "ID_PATH", &path);
if (match->hw_addr && (!hw_addr || !set_contains(match->hw_addr, hw_addr)))
return false;
if (match->permanent_hw_addr &&
(!permanent_hw_addr ||
!set_contains(match->permanent_hw_addr, permanent_hw_addr)))
return false;
if (!net_condition_test_strv(match->path, path))
return false;
if (!net_condition_test_strv(match->driver, driver))
return false;
if (!net_condition_test_strv(match->iftype, iftype_str))
return false;
if (!net_condition_test_strv(match->kind, kind))
return false;
if (!net_condition_test_ifname(match->ifname, ifname, alternative_names))
return false;
if (!net_condition_test_property(match->property, device))
return false;
if (!net_condition_test_strv(match->wlan_iftype, nl80211_iftype_to_string(wlan_iftype)))
return false;
if (!net_condition_test_strv(match->ssid, ssid))
return false;
if (match->bssid && (!bssid || !set_contains(match->bssid, bssid)))
return false;
return true;
}
int config_parse_net_condition(
const char *unit,
const char *filename,
unsigned line,
const char *section,
unsigned section_line,
const char *lvalue,
int ltype,
const char *rvalue,
void *data,
void *userdata) {
ConditionType cond = ltype;
Condition **list = data, *c;
bool negate;
assert(filename);
assert(lvalue);
assert(rvalue);
assert(data);
if (isempty(rvalue)) {
*list = condition_free_list_type(*list, cond);
return 0;
}
negate = rvalue[0] == '!';
if (negate)
rvalue++;
c = condition_new(cond, rvalue, false, negate);
if (!c)
return log_oom();
/* Drop previous assignment. */
*list = condition_free_list_type(*list, cond);
LIST_PREPEND(conditions, *list, c);
return 0;
}
int config_parse_match_strv(
const char *unit,
const char *filename,
unsigned line,
const char *section,
unsigned section_line,
const char *lvalue,
int ltype,
const char *rvalue,
void *data,
void *userdata) {
const char *p = ASSERT_PTR(rvalue);
char ***sv = ASSERT_PTR(data);
bool invert;
int r;
assert(filename);
assert(lvalue);
if (isempty(rvalue)) {
*sv = strv_free(*sv);
return 0;
}
invert = *p == '!';
p += invert;
for (;;) {
_cleanup_free_ char *word = NULL, *k = NULL;
r = extract_first_word(&p, &word, NULL, EXTRACT_UNQUOTE|EXTRACT_RETAIN_ESCAPE);
if (r == 0)
return 0;
if (r == -ENOMEM)
return log_oom();
if (r < 0) {
log_syntax(unit, LOG_WARNING, filename, line, r,
"Invalid syntax, ignoring: %s", rvalue);
return 0;
}
if (invert) {
k = strjoin("!", word);
if (!k)
return log_oom();
} else
k = TAKE_PTR(word);
r = strv_consume(sv, TAKE_PTR(k));
if (r < 0)
return log_oom();
}
}
int config_parse_match_ifnames(
const char *unit,
const char *filename,
unsigned line,
const char *section,
unsigned section_line,
const char *lvalue,
int ltype,
const char *rvalue,
void *data,
void *userdata) {
const char *p = ASSERT_PTR(rvalue);
char ***sv = ASSERT_PTR(data);
bool invert;
int r;
assert(filename);
assert(lvalue);
if (isempty(rvalue)) {
*sv = strv_free(*sv);
return 0;
}
invert = *p == '!';
p += invert;
for (;;) {
_cleanup_free_ char *word = NULL, *k = NULL;
r = extract_first_word(&p, &word, NULL, 0);
if (r == 0)
return 0;
if (r == -ENOMEM)
return log_oom();
if (r < 0) {
log_syntax(unit, LOG_WARNING, filename, line, 0,
"Failed to parse interface name list, ignoring: %s", rvalue);
return 0;
}
if (!ifname_valid_full(word, ltype)) {
log_syntax(unit, LOG_WARNING, filename, line, 0,
"Interface name is not valid or too long, ignoring assignment: %s", word);
continue;
}
if (invert) {
k = strjoin("!", word);
if (!k)
return log_oom();
} else
k = TAKE_PTR(word);
r = strv_consume(sv, TAKE_PTR(k));
if (r < 0)
return log_oom();
}
}
int config_parse_match_property(
const char *unit,
const char *filename,
unsigned line,
const char *section,
unsigned section_line,
const char *lvalue,
int ltype,
const char *rvalue,
void *data,
void *userdata) {
const char *p = ASSERT_PTR(rvalue);
char ***sv = ASSERT_PTR(data);
bool invert;
int r;
assert(filename);
assert(lvalue);
if (isempty(rvalue)) {
*sv = strv_free(*sv);
return 0;
}
invert = *p == '!';
p += invert;
for (;;) {
_cleanup_free_ char *word = NULL, *k = NULL;
r = extract_first_word(&p, &word, NULL, EXTRACT_CUNESCAPE|EXTRACT_UNQUOTE);
if (r == 0)
return 0;
if (r == -ENOMEM)
return log_oom();
if (r < 0) {
log_syntax(unit, LOG_WARNING, filename, line, 0,
"Invalid syntax, ignoring: %s", rvalue);
return 0;
}
if (!env_assignment_is_valid(word)) {
log_syntax(unit, LOG_WARNING, filename, line, 0,
"Invalid property or value, ignoring assignment: %s", word);
continue;
}
if (invert) {
k = strjoin("!", word);
if (!k)
return log_oom();
} else
k = TAKE_PTR(word);
r = strv_consume(sv, TAKE_PTR(k));
if (r < 0)
return log_oom();
}
}
| 12,096 | 29.2425 | 116 |
c
|
null |
systemd-main/src/shared/net-condition.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/nl80211.h>
#include <stdbool.h>
#include "sd-device.h"
#include "conf-parser.h"
#include "ether-addr-util.h"
#include "set.h"
typedef struct NetMatch {
Set *hw_addr;
Set *permanent_hw_addr;
char **path;
char **driver;
char **iftype; /* udev's DEVTYPE field or ARPHRD_XXX, e.g. ether, wlan. */
char **kind; /* IFLA_INFO_KIND attribute, e.g. gre, gretap, erspan. */
char **ifname;
char **property;
char **wlan_iftype;
char **ssid;
Set *bssid;
} NetMatch;
void net_match_clear(NetMatch *match);
bool net_match_is_empty(const NetMatch *match);
int net_match_config(
const NetMatch *match,
sd_device *device,
const struct hw_addr_data *hw_addr,
const struct hw_addr_data *permanent_hw_addr,
const char *driver,
unsigned short iftype,
const char *kind,
const char *ifname,
char * const *alternative_names,
enum nl80211_iftype wlan_iftype,
const char *ssid,
const struct ether_addr *bssid);
CONFIG_PARSER_PROTOTYPE(config_parse_net_condition);
CONFIG_PARSER_PROTOTYPE(config_parse_match_strv);
CONFIG_PARSER_PROTOTYPE(config_parse_match_ifnames);
CONFIG_PARSER_PROTOTYPE(config_parse_match_property);
| 1,461 | 29.458333 | 82 |
h
|
null |
systemd-main/src/shared/netif-naming-scheme.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include "alloc-util.h"
#include "netif-naming-scheme.h"
#include "proc-cmdline.h"
#include "string-util.h"
#include "string-table.h"
#ifdef _DEFAULT_NET_NAMING_SCHEME_TEST
/* The primary purpose of this check is to verify that _DEFAULT_NET_NAMING_SCHEME_TEST
* is a valid identifier. If an invalid name is given during configuration, this will
* fail with a name error. */
assert_cc(_DEFAULT_NET_NAMING_SCHEME_TEST >= 0);
#endif
static const NamingScheme naming_schemes[] = {
{ "v238", NAMING_V238 },
{ "v239", NAMING_V239 },
{ "v240", NAMING_V240 },
{ "v241", NAMING_V241 },
{ "v243", NAMING_V243 },
{ "v245", NAMING_V245 },
{ "v247", NAMING_V247 },
{ "v249", NAMING_V249 },
{ "v250", NAMING_V250 },
{ "v251", NAMING_V251 },
{ "v252", NAMING_V252 },
{ "v253", NAMING_V253 },
/* … add more schemes here, as the logic to name devices is updated … */
EXTRA_NET_NAMING_MAP
};
const NamingScheme* naming_scheme_from_name(const char *name) {
/* "latest" may either be defined explicitly by the extra map, in which case we will find it in
* the table like any other name. After iterating through the table, we check for "latest" again,
* which means that if not mapped explicitly, it maps to the last defined entry, whatever that is. */
for (size_t i = 0; i < ELEMENTSOF(naming_schemes); i++)
if (streq(naming_schemes[i].name, name))
return naming_schemes + i;
if (streq(name, "latest"))
return naming_schemes + ELEMENTSOF(naming_schemes) - 1;
return NULL;
}
const NamingScheme* naming_scheme(void) {
static const NamingScheme *cache = NULL;
_cleanup_free_ char *buffer = NULL;
const char *e, *k;
if (cache)
return cache;
/* Acquire setting from the kernel command line */
(void) proc_cmdline_get_key("net.naming-scheme", 0, &buffer);
/* Also acquire it from an env var */
e = getenv("NET_NAMING_SCHEME");
if (e) {
if (*e == ':') {
/* If prefixed with ':' the kernel cmdline takes precedence */
k = buffer ?: e + 1;
} else
k = e; /* Otherwise the env var takes precedence */
} else
k = buffer;
if (k) {
cache = naming_scheme_from_name(k);
if (cache) {
log_info("Using interface naming scheme '%s'.", cache->name);
return cache;
}
log_warning("Unknown interface naming scheme '%s' requested, ignoring.", k);
}
cache = naming_scheme_from_name(DEFAULT_NET_NAMING_SCHEME);
assert(cache);
log_info("Using default interface naming scheme '%s'.", cache->name);
return cache;
}
static const char* const name_policy_table[_NAMEPOLICY_MAX] = {
[NAMEPOLICY_KERNEL] = "kernel",
[NAMEPOLICY_KEEP] = "keep",
[NAMEPOLICY_DATABASE] = "database",
[NAMEPOLICY_ONBOARD] = "onboard",
[NAMEPOLICY_SLOT] = "slot",
[NAMEPOLICY_PATH] = "path",
[NAMEPOLICY_MAC] = "mac",
};
DEFINE_STRING_TABLE_LOOKUP(name_policy, NamePolicy);
static const char* const alternative_names_policy_table[_NAMEPOLICY_MAX] = {
[NAMEPOLICY_DATABASE] = "database",
[NAMEPOLICY_ONBOARD] = "onboard",
[NAMEPOLICY_SLOT] = "slot",
[NAMEPOLICY_PATH] = "path",
[NAMEPOLICY_MAC] = "mac",
};
DEFINE_STRING_TABLE_LOOKUP(alternative_names_policy, NamePolicy);
| 3,756 | 33.46789 | 109 |
c
|
null |
systemd-main/src/shared/netif-sriov.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <linux/if_link.h>
#include "sd-device.h"
#include "conf-parser.h"
#include "ether-addr-util.h"
#include "hashmap.h"
typedef enum SRIOVLinkState {
SR_IOV_LINK_STATE_AUTO = IFLA_VF_LINK_STATE_AUTO,
SR_IOV_LINK_STATE_ENABLE = IFLA_VF_LINK_STATE_ENABLE,
SR_IOV_LINK_STATE_DISABLE = IFLA_VF_LINK_STATE_DISABLE,
_SR_IOV_LINK_STATE_MAX,
_SR_IOV_LINK_STATE_INVALID = -EINVAL,
} SRIOVLinkState;
typedef struct SRIOV {
ConfigSection *section;
OrderedHashmap *sr_iov_by_section;
uint32_t vf; /* 0 - 2147483646 */
uint32_t vlan; /* 0 - 4095, 0 disables VLAN filter */
uint32_t qos;
uint16_t vlan_proto; /* ETH_P_8021Q or ETH_P_8021AD */
int vf_spoof_check_setting;
int query_rss;
int trust;
SRIOVLinkState link_state;
struct ether_addr mac;
} SRIOV;
SRIOV *sr_iov_free(SRIOV *sr_iov);
void sr_iov_hash_func(const SRIOV *sr_iov, struct siphash *state);
int sr_iov_compare_func(const SRIOV *s1, const SRIOV *s2);
int sr_iov_set_netlink_message(SRIOV *sr_iov, sd_netlink_message *req);
int sr_iov_get_num_vfs(sd_device *device, uint32_t *ret);
int sr_iov_set_num_vfs(sd_device *device, uint32_t num_vfs, OrderedHashmap *sr_iov_by_section);
int sr_iov_drop_invalid_sections(uint32_t num_vfs, OrderedHashmap *sr_iov_by_section);
DEFINE_SECTION_CLEANUP_FUNCTIONS(SRIOV, sr_iov_free);
CONFIG_PARSER_PROTOTYPE(config_parse_sr_iov_uint32);
CONFIG_PARSER_PROTOTYPE(config_parse_sr_iov_boolean);
CONFIG_PARSER_PROTOTYPE(config_parse_sr_iov_link_state);
CONFIG_PARSER_PROTOTYPE(config_parse_sr_iov_vlan_proto);
CONFIG_PARSER_PROTOTYPE(config_parse_sr_iov_mac);
CONFIG_PARSER_PROTOTYPE(config_parse_sr_iov_num_vfs);
| 1,801 | 34.333333 | 95 |
h
|
null |
systemd-main/src/shared/netif-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include <inttypes.h>
#include <stdbool.h>
#include "sd-device.h"
#include "sd-id128.h"
#include "ether-addr-util.h"
bool netif_has_carrier(uint8_t operstate, unsigned flags);
int net_get_type_string(sd_device *device, uint16_t iftype, char **ret);
const char *net_get_persistent_name(sd_device *device);
int net_get_unique_predictable_data(sd_device *device, bool use_sysname, uint64_t *ret);
int net_get_unique_predictable_data_from_name(const char *name, const sd_id128_t *key, uint64_t *ret);
int net_verify_hardware_address(
const char *ifname,
bool is_static,
uint16_t iftype,
const struct hw_addr_data *ib_hw_addr,
struct hw_addr_data *new_hw_addr);
| 803 | 33.956522 | 102 |
h
|
null |
systemd-main/src/shared/nsflags.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include "alloc-util.h"
#include "extract-word.h"
#include "namespace-util.h"
#include "nsflags.h"
#include "string-util.h"
int namespace_flags_from_string(const char *name, unsigned long *ret) {
unsigned long flags = 0;
int r;
assert_se(ret);
for (;;) {
_cleanup_free_ char *word = NULL;
unsigned long f = 0;
unsigned i;
r = extract_first_word(&name, &word, NULL, 0);
if (r < 0)
return r;
if (r == 0)
break;
for (i = 0; namespace_info[i].proc_name; i++)
if (streq(word, namespace_info[i].proc_name)) {
f = namespace_info[i].clone_flag;
break;
}
if (f == 0)
return -EINVAL;
flags |= f;
}
*ret = flags;
return 0;
}
int namespace_flags_to_string(unsigned long flags, char **ret) {
_cleanup_free_ char *s = NULL;
unsigned i;
for (i = 0; namespace_info[i].proc_name; i++) {
if ((flags & namespace_info[i].clone_flag) != namespace_info[i].clone_flag)
continue;
if (!strextend_with_separator(&s, " ", namespace_info[i].proc_name))
return -ENOMEM;
}
*ret = TAKE_PTR(s);
return 0;
}
const char *namespace_single_flag_to_string(unsigned long flag) {
for (unsigned i = 0; namespace_info[i].proc_name; i++)
if (namespace_info[i].clone_flag == flag)
return namespace_info[i].proc_name;
return NULL;
}
| 1,844 | 26.132353 | 91 |
c
|
null |
systemd-main/src/shared/nsflags.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "missing_sched.h"
/* The combination of all namespace flags defined by the kernel. The right type for this isn't clear. setns() and
* unshare() expect these flags to be passed as (signed) "int", while clone() wants them as "unsigned long". The latter
* is definitely more appropriate for a flags parameter, and also the larger type of the two, hence let's stick to that
* here. */
#define NAMESPACE_FLAGS_ALL \
((unsigned long) (CLONE_NEWCGROUP| \
CLONE_NEWIPC| \
CLONE_NEWNET| \
CLONE_NEWNS| \
CLONE_NEWPID| \
CLONE_NEWUSER| \
CLONE_NEWUTS))
#define NAMESPACE_FLAGS_INITIAL ULONG_MAX
int namespace_flags_from_string(const char *name, unsigned long *ret);
int namespace_flags_to_string(unsigned long flags, char **ret);
const char *namespace_single_flag_to_string(unsigned long flag);
| 1,261 | 51.583333 | 119 |
h
|
null |
systemd-main/src/shared/numa-util.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <errno.h>
#include <sched.h>
#include "alloc-util.h"
#include "cpu-set-util.h"
#include "dirent-util.h"
#include "fd-util.h"
#include "fileio.h"
#include "macro.h"
#include "missing_syscall.h"
#include "numa-util.h"
#include "stdio-util.h"
#include "string-table.h"
bool numa_policy_is_valid(const NUMAPolicy *policy) {
assert(policy);
if (!mpol_is_valid(numa_policy_get_type(policy)))
return false;
if (!policy->nodes.set &&
!IN_SET(numa_policy_get_type(policy), MPOL_DEFAULT, MPOL_LOCAL, MPOL_PREFERRED))
return false;
if (policy->nodes.set &&
numa_policy_get_type(policy) == MPOL_PREFERRED &&
CPU_COUNT_S(policy->nodes.allocated, policy->nodes.set) != 1)
return false;
return true;
}
static int numa_policy_to_mempolicy(const NUMAPolicy *policy, unsigned long *ret_maxnode, unsigned long **ret_nodes) {
unsigned node, bits = 0, ulong_bits;
_cleanup_free_ unsigned long *out = NULL;
assert(policy);
assert(ret_maxnode);
assert(ret_nodes);
if (IN_SET(numa_policy_get_type(policy), MPOL_DEFAULT, MPOL_LOCAL) ||
(numa_policy_get_type(policy) == MPOL_PREFERRED && !policy->nodes.set)) {
*ret_nodes = NULL;
*ret_maxnode = 0;
return 0;
}
bits = policy->nodes.allocated * 8;
ulong_bits = sizeof(unsigned long) * 8;
out = new0(unsigned long, DIV_ROUND_UP(policy->nodes.allocated, sizeof(unsigned long)));
if (!out)
return -ENOMEM;
/* We don't make any assumptions about internal type libc is using to store NUMA node mask.
Hence we need to convert the node mask to the representation expected by set_mempolicy() */
for (node = 0; node < bits; node++)
if (CPU_ISSET_S(node, policy->nodes.allocated, policy->nodes.set))
out[node / ulong_bits] |= 1ul << (node % ulong_bits);
*ret_nodes = TAKE_PTR(out);
*ret_maxnode = bits + 1;
return 0;
}
int apply_numa_policy(const NUMAPolicy *policy) {
int r;
_cleanup_free_ unsigned long *nodes = NULL;
unsigned long maxnode;
assert(policy);
if (get_mempolicy(NULL, NULL, 0, 0, 0) < 0 && errno == ENOSYS)
return -EOPNOTSUPP;
if (!numa_policy_is_valid(policy))
return -EINVAL;
r = numa_policy_to_mempolicy(policy, &maxnode, &nodes);
if (r < 0)
return r;
r = set_mempolicy(numa_policy_get_type(policy), nodes, maxnode);
if (r < 0)
return -errno;
return 0;
}
int numa_to_cpu_set(const NUMAPolicy *policy, CPUSet *ret) {
int r;
size_t i;
_cleanup_(cpu_set_reset) CPUSet s = {};
assert(policy);
assert(ret);
for (i = 0; i < policy->nodes.allocated * 8; i++) {
_cleanup_free_ char *l = NULL;
char p[STRLEN("/sys/devices/system/node/node//cpulist") + DECIMAL_STR_MAX(size_t) + 1];
_cleanup_(cpu_set_reset) CPUSet part = {};
if (!CPU_ISSET_S(i, policy->nodes.allocated, policy->nodes.set))
continue;
xsprintf(p, "/sys/devices/system/node/node%zu/cpulist", i);
r = read_one_line_file(p, &l);
if (r < 0)
return r;
r = parse_cpu_set(l, &part);
if (r < 0)
return r;
r = cpu_set_add_all(&s, &part);
if (r < 0)
return r;
}
*ret = TAKE_STRUCT(s);
return 0;
}
static int numa_max_node(void) {
_cleanup_closedir_ DIR *d = NULL;
int r, max_node = 0;
d = opendir("/sys/devices/system/node");
if (!d)
return -errno;
FOREACH_DIRENT(de, d, break) {
int node;
const char *n;
if (de->d_type != DT_DIR)
continue;
n = startswith(de->d_name, "node");
if (!n)
continue;
r = safe_atoi(n, &node);
if (r < 0)
continue;
if (node > max_node)
max_node = node;
}
return max_node;
}
int numa_mask_add_all(CPUSet *mask) {
int m;
assert(mask);
m = numa_max_node();
if (m < 0) {
log_debug_errno(m, "Failed to determine maximum NUMA node index, assuming 1023: %m");
m = 1023; /* CONFIG_NODES_SHIFT is set to 10 on x86_64, i.e. 1024 NUMA nodes in total */
}
for (int i = 0; i <= m; i++) {
int r;
r = cpu_set_add(mask, i);
if (r < 0)
return r;
}
return 0;
}
static const char* const mpol_table[] = {
[MPOL_DEFAULT] = "default",
[MPOL_PREFERRED] = "preferred",
[MPOL_BIND] = "bind",
[MPOL_INTERLEAVE] = "interleave",
[MPOL_LOCAL] = "local",
};
DEFINE_STRING_TABLE_LOOKUP(mpol, int);
| 5,368 | 27.407407 | 118 |
c
|
null |
systemd-main/src/shared/numa-util.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "cpu-set-util.h"
#include "missing_syscall.h"
static inline bool mpol_is_valid(int t) {
return t >= MPOL_DEFAULT && t <= MPOL_LOCAL;
}
typedef struct NUMAPolicy {
/* Always use numa_policy_get_type() to read the value */
int type;
CPUSet nodes;
} NUMAPolicy;
bool numa_policy_is_valid(const NUMAPolicy *p);
static inline int numa_policy_get_type(const NUMAPolicy *p) {
return p->type < 0 ? (p->nodes.set ? MPOL_PREFERRED : -1) : p->type;
}
static inline void numa_policy_reset(NUMAPolicy *p) {
assert(p);
cpu_set_reset(&p->nodes);
p->type = -1;
}
int apply_numa_policy(const NUMAPolicy *policy);
int numa_to_cpu_set(const NUMAPolicy *policy, CPUSet *set);
int numa_mask_add_all(CPUSet *mask);
const char* mpol_to_string(int i) _const_;
int mpol_from_string(const char *s) _pure_;
| 924 | 24.694444 | 76 |
h
|
null |
systemd-main/src/shared/open-file.c
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include "escape.h"
#include "extract-word.h"
#include "fd-util.h"
#include "open-file.h"
#include "path-util.h"
#include "string-table.h"
#include "string-util.h"
int open_file_parse(const char *v, OpenFile **ret) {
_cleanup_free_ char *options = NULL;
_cleanup_(open_file_freep) OpenFile *of = NULL;
int r;
assert(v);
assert(ret);
of = new0(OpenFile, 1);
if (!of)
return -ENOMEM;
r = extract_many_words(&v, ":", EXTRACT_DONT_COALESCE_SEPARATORS|EXTRACT_CUNESCAPE, &of->path, &of->fdname, &options, NULL);
if (r < 0)
return r;
if (r == 0)
return -EINVAL;
/* Enforce that at most 3 colon-separated words are present */
if (!isempty(v))
return -EINVAL;
for (const char *p = options;;) {
OpenFileFlag flag;
_cleanup_free_ char *word = NULL;
r = extract_first_word(&p, &word, ",", 0);
if (r < 0)
return r;
if (r == 0)
break;
flag = open_file_flags_from_string(word);
if (flag < 0)
return flag;
if ((flag & of->flags) != 0)
return -EINVAL;
of->flags |= flag;
}
if (isempty(of->fdname)) {
of->fdname = mfree(of->fdname);
r = path_extract_filename(of->path, &of->fdname);
if (r < 0)
return r;
}
r = open_file_validate(of);
if (r < 0)
return r;
*ret = TAKE_PTR(of);
return 0;
}
int open_file_validate(const OpenFile *of) {
assert(of);
if (!path_is_valid(of->path) || !path_is_absolute(of->path))
return -EINVAL;
if (!fdname_is_valid(of->fdname))
return -EINVAL;
if ((FLAGS_SET(of->flags, OPENFILE_READ_ONLY) + FLAGS_SET(of->flags, OPENFILE_APPEND) +
FLAGS_SET(of->flags, OPENFILE_TRUNCATE)) > 1)
return -EINVAL;
if ((of->flags & ~_OPENFILE_MASK_PUBLIC) != 0)
return -EINVAL;
return 0;
}
int open_file_to_string(const OpenFile *of, char **ret) {
_cleanup_free_ char *options = NULL, *fname = NULL, *s = NULL;
bool has_fdname = false;
int r;
assert(of);
assert(ret);
s = shell_escape(of->path, ":");
if (!s)
return -ENOMEM;
r = path_extract_filename(of->path, &fname);
if (r < 0)
return r;
has_fdname = !streq(fname, of->fdname);
if (has_fdname)
if (!strextend(&s, ":", of->fdname))
return -ENOMEM;
for (OpenFileFlag flag = OPENFILE_READ_ONLY; flag < _OPENFILE_MAX; flag <<= 1)
if (FLAGS_SET(of->flags, flag) && !strextend_with_separator(&options, ",", open_file_flags_to_string(flag)))
return -ENOMEM;
if (options)
if (!(has_fdname ? strextend(&s, ":", options) : strextend(&s, "::", options)))
return -ENOMEM;
*ret = TAKE_PTR(s);
return 0;
}
OpenFile *open_file_free(OpenFile *of) {
if (!of)
return NULL;
free(of->path);
free(of->fdname);
return mfree(of);
}
void open_file_free_many(OpenFile **head) {
OpenFile *of;
while ((of = *head)) {
LIST_REMOVE(open_files, *head, of);
of = open_file_free(of);
}
}
static const char * const open_file_flags_table[_OPENFILE_MAX] = {
[OPENFILE_READ_ONLY] = "read-only",
[OPENFILE_APPEND] = "append",
[OPENFILE_TRUNCATE] = "truncate",
[OPENFILE_GRACEFUL] = "graceful",
};
DEFINE_STRING_TABLE_LOOKUP(open_file_flags, OpenFileFlag);
| 4,057 | 25.874172 | 132 |
c
|
null |
systemd-main/src/shared/open-file.h
|
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#pragma once
#include "list.h"
typedef enum OpenFileFlag {
OPENFILE_READ_ONLY = 1 << 0,
OPENFILE_APPEND = 1 << 1,
OPENFILE_TRUNCATE = 1 << 2,
OPENFILE_GRACEFUL = 1 << 3,
_OPENFILE_MAX,
_OPENFILE_INVALID = -EINVAL,
_OPENFILE_MASK_PUBLIC = OPENFILE_READ_ONLY | OPENFILE_APPEND | OPENFILE_TRUNCATE | OPENFILE_GRACEFUL,
} OpenFileFlag;
typedef struct OpenFile {
char *path;
char *fdname;
OpenFileFlag flags;
LIST_FIELDS(struct OpenFile, open_files);
} OpenFile;
int open_file_parse(const char *v, OpenFile **ret);
int open_file_validate(const OpenFile *of);
int open_file_to_string(const OpenFile *of, char **ret);
OpenFile *open_file_free(OpenFile *of);
DEFINE_TRIVIAL_CLEANUP_FUNC(OpenFile*, open_file_free);
void open_file_free_many(OpenFile **head);
const char *open_file_flags_to_string(OpenFileFlag t) _const_;
OpenFileFlag open_file_flags_from_string(const char *t) _pure_;
| 1,030 | 26.864865 | 109 |
h
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.