repo
stringlengths
1
152
file
stringlengths
14
221
code
stringlengths
501
25k
file_length
int64
501
25k
avg_line_length
float64
20
99.5
max_line_length
int64
21
134
extension_type
stringclasses
2 values
null
systemd-main/src/basic/static-destruct.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "alloc-util.h" #include "macro.h" #include "memory-util.h" /* A framework for registering static variables that shall be freed on shutdown of a process. It's a bit like gcc's * destructor attribute, but allows us to precisely schedule when we want to free the variables. This is supposed to * feel a bit like the gcc cleanup attribute, but for static variables. Note that this does not work for static * variables declared in .so's, as the list is private to the same linking unit. But maybe that's a good thing. */ #define _common_static_destruct_attrs_ \ /* Older compilers don't know "retain" attribute. */ \ _Pragma("GCC diagnostic ignored \"-Wattributes\"") \ /* The actual destructor structure we place in a special section to find it. */ \ _section_("SYSTEMD_STATIC_DESTRUCT") \ /* Use pointer alignment, since that is apparently what gcc does for static variables. */ \ _alignptr_ \ /* Make sure this is not dropped from the image despite not being explicitly referenced. */ \ _used_ \ /* Prevent garbage collection by the linker. */ \ _retain_ \ /* Make sure that AddressSanitizer doesn't pad this variable: we want everything in this section * packed next to each other so that we can enumerate it. */ \ _variable_no_sanitize_address_ typedef enum StaticDestructorType { STATIC_DESTRUCTOR_SIMPLE, STATIC_DESTRUCTOR_ARRAY, _STATIC_DESTRUCTOR_TYPE_MAX, _STATIC_DESTRUCTOR_INVALID = -EINVAL, } StaticDestructorType; typedef struct SimpleCleanup { void *data; free_func_t destroy; } SimpleCleanup; typedef struct StaticDestructor { StaticDestructorType type; union { SimpleCleanup simple; ArrayCleanup array; }; } StaticDestructor; #define STATIC_DESTRUCTOR_REGISTER(variable, func) \ _STATIC_DESTRUCTOR_REGISTER(UNIQ, variable, func) #define _STATIC_DESTRUCTOR_REGISTER(uq, variable, func) \ /* Type-safe destructor */ \ static void UNIQ_T(static_destructor_wrapper, uq)(void *p) { \ typeof(variable) *q = p; \ func(q); \ } \ _common_static_destruct_attrs_ \ static const StaticDestructor UNIQ_T(static_destructor_entry, uq) = { \ .type = STATIC_DESTRUCTOR_SIMPLE, \ .simple.data = &(variable), \ .simple.destroy = UNIQ_T(static_destructor_wrapper, uq), \ } #define STATIC_ARRAY_DESTRUCTOR_REGISTER(a, n, func) \ _STATIC_ARRAY_DESTRUCTOR_REGISTER(UNIQ, a, n, func) #define _STATIC_ARRAY_DESTRUCTOR_REGISTER(uq, a, n, func) \ /* Type-safety check */ \ _unused_ static void (* UNIQ_T(static_destructor_wrapper, uq))(typeof(a[0]) *x, size_t y) = (func); \ _common_static_destruct_attrs_ \ static const StaticDestructor UNIQ_T(static_destructor_entry, uq) = { \ .type = STATIC_DESTRUCTOR_ARRAY, \ .array.parray = (void**) &(a), \ .array.pn = &(n), \ .array.pfunc = (free_array_func_t) (func), \ }; /* Beginning and end of our section listing the destructors. We define these as weak as we want this to work * even if no destructors are defined and the section is missing. */ extern const StaticDestructor _weak_ __start_SYSTEMD_STATIC_DESTRUCT[]; extern const StaticDestructor _weak_ __stop_SYSTEMD_STATIC_DESTRUCT[]; /* The function to destroy everything. (Note that this must be static inline, as it's key that it remains in * the same linking unit as the variables we want to destroy.) */ static inline void static_destruct(void) { if (!__start_SYSTEMD_STATIC_DESTRUCT) return; for (const StaticDestructor *d = ALIGN_PTR(__start_SYSTEMD_STATIC_DESTRUCT); d < __stop_SYSTEMD_STATIC_DESTRUCT; d = ALIGN_PTR(d + 1)) switch (d->type) { case STATIC_DESTRUCTOR_SIMPLE: d->simple.destroy(d->simple.data); break; case STATIC_DESTRUCTOR_ARRAY: array_cleanup(&d->array); break; default: assert_not_reached(); } }
5,160
47.688679
116
h
null
systemd-main/src/basic/stdio-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <printf.h> #include <stdarg.h> #include <stdio.h> #include <sys/types.h> #include "macro.h" _printf_(3, 4) static inline char *snprintf_ok(char *buf, size_t len, const char *format, ...) { va_list ap; int r; va_start(ap, format); DISABLE_WARNING_FORMAT_NONLITERAL; r = vsnprintf(buf, len, format, ap); REENABLE_WARNING; va_end(ap); return r >= 0 && (size_t) r < len ? buf : NULL; } #define xsprintf(buf, fmt, ...) \ assert_message_se(snprintf_ok(buf, ELEMENTSOF(buf), fmt, ##__VA_ARGS__), "xsprintf: " #buf "[] must be big enough") #define VA_FORMAT_ADVANCE(format, ap) \ do { \ int _argtypes[128]; \ size_t _i, _k; \ /* See https://github.com/google/sanitizers/issues/992 */ \ if (HAS_FEATURE_MEMORY_SANITIZER) \ memset(_argtypes, 0, sizeof(_argtypes)); \ _k = parse_printf_format((format), ELEMENTSOF(_argtypes), _argtypes); \ assert(_k < ELEMENTSOF(_argtypes)); \ for (_i = 0; _i < _k; _i++) { \ if (_argtypes[_i] & PA_FLAG_PTR) { \ (void) va_arg(ap, void*); \ continue; \ } \ \ switch (_argtypes[_i]) { \ case PA_INT: \ case PA_INT|PA_FLAG_SHORT: \ case PA_CHAR: \ (void) va_arg(ap, int); \ break; \ case PA_INT|PA_FLAG_LONG: \ (void) va_arg(ap, long int); \ break; \ case PA_INT|PA_FLAG_LONG_LONG: \ (void) va_arg(ap, long long int); \ break; \ case PA_WCHAR: \ (void) va_arg(ap, wchar_t); \ break; \ case PA_WSTRING: \ case PA_STRING: \ case PA_POINTER: \ (void) va_arg(ap, void*); \ break; \ case PA_FLOAT: \ case PA_DOUBLE: \ (void) va_arg(ap, double); \ break; \ case PA_DOUBLE|PA_FLAG_LONG_DOUBLE: \ (void) va_arg(ap, long double); \ break; \ default: \ assert_not_reached(); \ } \ } \ } while (false)
4,108
53.786667
123
h
null
systemd-main/src/basic/strbuf.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <stdlib.h> #include <string.h> #include "alloc-util.h" #include "sort-util.h" #include "strbuf.h" /* * Strbuf stores given strings in a single continuous allocated memory * area. Identical strings are de-duplicated and return the same offset * as the first string stored. If the tail of a string already exists * in the buffer, the tail is returned. * * A trie (http://en.wikipedia.org/wiki/Trie) is used to maintain the * information about the stored strings. * * Example of udev rules: * $ ./udevadm test . * ... * read rules file: /usr/lib/udev/rules.d/99-systemd.rules * rules contain 196608 bytes tokens (16384 * 12 bytes), 39742 bytes strings * 23939 strings (207859 bytes), 20404 de-duplicated (171653 bytes), 3536 trie nodes used * ... */ struct strbuf* strbuf_new(void) { struct strbuf *str; str = new(struct strbuf, 1); if (!str) return NULL; *str = (struct strbuf) { .buf = new0(char, 1), .root = new0(struct strbuf_node, 1), .len = 1, .nodes_count = 1, }; if (!str->buf || !str->root) { free(str->buf); free(str->root); return mfree(str); } return str; } static struct strbuf_node* strbuf_node_cleanup(struct strbuf_node *node) { size_t i; for (i = 0; i < node->children_count; i++) strbuf_node_cleanup(node->children[i].child); free(node->children); return mfree(node); } /* clean up trie data, leave only the string buffer */ void strbuf_complete(struct strbuf *str) { if (!str) return; if (str->root) str->root = strbuf_node_cleanup(str->root); } /* clean up everything */ struct strbuf* strbuf_free(struct strbuf *str) { if (!str) return NULL; strbuf_complete(str); free(str->buf); return mfree(str); } static int strbuf_children_cmp(const struct strbuf_child_entry *n1, const struct strbuf_child_entry *n2) { return n1->c - n2->c; } static void bubbleinsert(struct strbuf_node *node, uint8_t c, struct strbuf_node *node_child) { struct strbuf_child_entry new = { .c = c, .child = node_child, }; int left = 0, right = node->children_count; while (right > left) { int middle = (right + left) / 2 ; if (strbuf_children_cmp(&node->children[middle], &new) <= 0) left = middle + 1; else right = middle; } memmove(node->children + left + 1, node->children + left, sizeof(struct strbuf_child_entry) * (node->children_count - left)); node->children[left] = new; node->children_count++; } /* add string, return the index/offset into the buffer */ ssize_t strbuf_add_string(struct strbuf *str, const char *s, size_t len) { uint8_t c; char *buf_new; struct strbuf_child_entry *child; struct strbuf_node *node; ssize_t off; if (!str->root) return -EINVAL; /* search string; start from last character to find possibly matching tails */ str->in_count++; if (len == 0) { str->dedup_count++; return 0; } str->in_len += len; node = str->root; for (size_t depth = 0; depth <= len; depth++) { struct strbuf_child_entry search; /* match against current node */ off = node->value_off + node->value_len - len; if (depth == len || (node->value_len >= len && memcmp(str->buf + off, s, len) == 0)) { str->dedup_len += len; str->dedup_count++; return off; } c = s[len - 1 - depth]; /* lookup child node */ search.c = c; child = typesafe_bsearch(&search, node->children, node->children_count, strbuf_children_cmp); if (!child) break; node = child->child; } /* add new string */ buf_new = realloc(str->buf, str->len + len+1); if (!buf_new) return -ENOMEM; str->buf = buf_new; off = str->len; memcpy(str->buf + off, s, len); str->len += len; str->buf[str->len++] = '\0'; /* new node */ _cleanup_free_ struct strbuf_node *node_child = NULL; node_child = new(struct strbuf_node, 1); if (!node_child) return -ENOMEM; *node_child = (struct strbuf_node) { .value_off = off, .value_len = len, }; /* extend array, add new entry, sort for bisection */ child = reallocarray(node->children, node->children_count + 1, sizeof(struct strbuf_child_entry)); if (!child) return -ENOMEM; str->nodes_count++; node->children = child; bubbleinsert(node, c, TAKE_PTR(node_child)); return off; }
5,411
28.736264
109
c
null
systemd-main/src/basic/strbuf.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stddef.h> #include <stdint.h> #include <sys/types.h> #include "macro.h" struct strbuf { char *buf; size_t len; struct strbuf_node *root; size_t nodes_count; size_t in_count; size_t in_len; size_t dedup_len; size_t dedup_count; }; struct strbuf_node { size_t value_off; size_t value_len; struct strbuf_child_entry *children; uint8_t children_count; }; struct strbuf_child_entry { uint8_t c; struct strbuf_node *child; }; struct strbuf* strbuf_new(void); ssize_t strbuf_add_string(struct strbuf *str, const char *s, size_t len); void strbuf_complete(struct strbuf *str); struct strbuf* strbuf_free(struct strbuf *str); DEFINE_TRIVIAL_CLEANUP_FUNC(struct strbuf*, strbuf_free);
867
20.7
73
h
null
systemd-main/src/basic/string-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <stddef.h> #include <string.h> #include "alloc-util.h" #include "macro.h" #include "string-util-fundamental.h" /* What is interpreted as whitespace? */ #define WHITESPACE " \t\n\r" #define NEWLINE "\n\r" #define QUOTES "\"\'" #define COMMENTS "#;" #define GLOB_CHARS "*?[" #define DIGITS "0123456789" #define LOWERCASE_LETTERS "abcdefghijklmnopqrstuvwxyz" #define UPPERCASE_LETTERS "ABCDEFGHIJKLMNOPQRSTUVWXYZ" #define LETTERS LOWERCASE_LETTERS UPPERCASE_LETTERS #define ALPHANUMERICAL LETTERS DIGITS #define HEXDIGITS DIGITS "abcdefABCDEF" #define LOWERCASE_HEXDIGITS DIGITS "abcdef" #define URI_RESERVED ":/?#[]@!$&'()*+;=" /* [RFC3986] */ #define URI_UNRESERVED ALPHANUMERICAL "-._~" /* [RFC3986] */ #define URI_VALID URI_RESERVED URI_UNRESERVED /* [RFC3986] */ static inline char* strstr_ptr(const char *haystack, const char *needle) { if (!haystack || !needle) return NULL; return strstr(haystack, needle); } static inline char *strstrafter(const char *haystack, const char *needle) { char *p; /* Returns NULL if not found, or pointer to first character after needle if found */ p = strstr_ptr(haystack, needle); if (!p) return NULL; return p + strlen(needle); } static inline const char* strnull(const char *s) { return s ?: "(null)"; } static inline const char *strna(const char *s) { return s ?: "n/a"; } static inline const char* true_false(bool b) { return b ? "true" : "false"; } static inline const char* plus_minus(bool b) { return b ? "+" : "-"; } static inline const char* one_zero(bool b) { return b ? "1" : "0"; } static inline const char* enable_disable(bool b) { return b ? "enable" : "disable"; } /* This macro's return pointer will have the "const" qualifier set or unset the same way as the input * pointer. */ #define empty_to_null(p) \ ({ \ const char *_p = (p); \ (typeof(p)) (isempty(_p) ? NULL : _p); \ }) static inline const char *empty_to_na(const char *p) { return isempty(p) ? "n/a" : p; } static inline const char *empty_to_dash(const char *str) { return isempty(str) ? "-" : str; } static inline bool empty_or_dash(const char *str) { return !str || str[0] == 0 || (str[0] == '-' && str[1] == 0); } static inline const char *empty_or_dash_to_null(const char *p) { return empty_or_dash(p) ? NULL : p; } #define empty_or_dash_to_null(p) \ ({ \ const char *_p = (p); \ (typeof(p)) (empty_or_dash(_p) ? NULL : _p); \ }) char *first_word(const char *s, const char *word) _pure_; char *strnappend(const char *s, const char *suffix, size_t length); char *strjoin_real(const char *x, ...) _sentinel_; #define strjoin(a, ...) strjoin_real((a), __VA_ARGS__, NULL) #define strjoina(a, ...) \ ({ \ const char *_appendees_[] = { a, __VA_ARGS__ }; \ char *_d_, *_p_; \ size_t _len_ = 0; \ size_t _i_; \ for (_i_ = 0; _i_ < ELEMENTSOF(_appendees_) && _appendees_[_i_]; _i_++) \ _len_ += strlen(_appendees_[_i_]); \ _p_ = _d_ = newa(char, _len_ + 1); \ for (_i_ = 0; _i_ < ELEMENTSOF(_appendees_) && _appendees_[_i_]; _i_++) \ _p_ = stpcpy(_p_, _appendees_[_i_]); \ *_p_ = 0; \ _d_; \ }) char *strstrip(char *s); char *delete_chars(char *s, const char *bad); char *delete_trailing_chars(char *s, const char *bad); char *truncate_nl_full(char *s, size_t *ret_len); static inline char *truncate_nl(char *s) { return truncate_nl_full(s, NULL); } static inline char *skip_leading_chars(const char *s, const char *bad) { if (!s) return NULL; if (!bad) bad = WHITESPACE; return (char*) s + strspn(s, bad); } char ascii_tolower(char x); char *ascii_strlower(char *s); char *ascii_strlower_n(char *s, size_t n); char ascii_toupper(char x); char *ascii_strupper(char *s); int ascii_strcasecmp_n(const char *a, const char *b, size_t n); int ascii_strcasecmp_nn(const char *a, size_t n, const char *b, size_t m); bool chars_intersect(const char *a, const char *b) _pure_; static inline bool _pure_ in_charset(const char *s, const char* charset) { assert(s); assert(charset); return s[strspn(s, charset)] == '\0'; } static inline bool char_is_cc(char p) { /* char is unsigned on some architectures, e.g. aarch64. So, compiler may warn the condition * p >= 0 is always true. See #19543. Hence, let's cast to unsigned before the comparison. Note * that the cast in the right hand side is redundant, as according to the C standard, compilers * automatically cast a signed value to unsigned when comparing with an unsigned variable. Just * for safety and readability. */ return (uint8_t) p < (uint8_t) ' ' || p == 127; } bool string_has_cc(const char *p, const char *ok) _pure_; char *ellipsize_mem(const char *s, size_t old_length_bytes, size_t new_length_columns, unsigned percent); static inline char *ellipsize(const char *s, size_t length, unsigned percent) { return ellipsize_mem(s, strlen(s), length, percent); } char *cellescape(char *buf, size_t len, const char *s); /* This limit is arbitrary, enough to give some idea what the string contains */ #define CELLESCAPE_DEFAULT_LENGTH 64 char* strshorten(char *s, size_t l); int strgrowpad0(char **s, size_t l); char *strreplace(const char *text, const char *old_string, const char *new_string); char *strip_tab_ansi(char **ibuf, size_t *_isz, size_t highlight[2]); char *strextend_with_separator_internal(char **x, const char *separator, ...) _sentinel_; #define strextend_with_separator(x, separator, ...) strextend_with_separator_internal(x, separator, __VA_ARGS__, NULL) #define strextend(x, ...) strextend_with_separator_internal(x, NULL, __VA_ARGS__, NULL) char *strextendn(char **x, const char *s, size_t l); int strextendf_with_separator(char **x, const char *separator, const char *format, ...) _printf_(3,4); #define strextendf(x, ...) strextendf_with_separator(x, NULL, __VA_ARGS__) char *strrep(const char *s, unsigned n); int split_pair(const char *s, const char *sep, char **l, char **r); int free_and_strdup(char **p, const char *s); static inline int free_and_strdup_warn(char **p, const char *s) { int r; r = free_and_strdup(p, s); if (r < 0) return log_oom(); return r; } int free_and_strndup(char **p, const char *s, size_t l); bool string_is_safe(const char *p) _pure_; DISABLE_WARNING_STRINGOP_TRUNCATION; static inline void strncpy_exact(char *buf, const char *src, size_t buf_len) { strncpy(buf, src, buf_len); } REENABLE_WARNING; /* Like startswith_no_case(), but operates on arbitrary memory blocks. * It works only for ASCII strings. */ static inline void *memory_startswith_no_case(const void *p, size_t sz, const char *token) { assert(token); size_t n = strlen(token); if (sz < n) return NULL; assert(p); for (size_t i = 0; i < n; i++) if (ascii_tolower(((char *)p)[i]) != ascii_tolower(token[i])) return NULL; return (uint8_t*) p + n; } static inline char* str_realloc(char *p) { /* Reallocate *p to actual size. Ignore failure, and return the original string on error. */ if (!p) return NULL; return realloc(p, strlen(p) + 1) ?: p; } char* string_erase(char *x); int string_truncate_lines(const char *s, size_t n_lines, char **ret); int string_extract_line(const char *s, size_t i, char **ret); int string_contains_word_strv(const char *string, const char *separators, char **words, const char **ret_word); static inline int string_contains_word(const char *string, const char *separators, const char *word) { return string_contains_word_strv(string, separators, STRV_MAKE(word), NULL); } bool streq_skip_trailing_chars(const char *s1, const char *s2, const char *ok); char *string_replace_char(char *str, char old_char, char new_char); typedef enum MakeCStringMode { MAKE_CSTRING_REFUSE_TRAILING_NUL, MAKE_CSTRING_ALLOW_TRAILING_NUL, MAKE_CSTRING_REQUIRE_TRAILING_NUL, _MAKE_CSTRING_MODE_MAX, _MAKE_CSTRING_MODE_INVALID = -1, } MakeCStringMode; int make_cstring(const char *s, size_t n, MakeCStringMode mode, char **ret); size_t strspn_from_end(const char *str, const char *accept); char *strdupspn(const char *a, const char *accept); char *strdupcspn(const char *a, const char *reject); char *find_line_startswith(const char *haystack, const char *needle); char *startswith_strv(const char *string, char **strv); #define STARTSWITH_SET(p, ...) \ startswith_strv(p, STRV_MAKE(__VA_ARGS__)) bool version_is_valid(const char *s);
9,942
33.887719
118
h
null
systemd-main/src/basic/strv.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fnmatch.h> #include <stdarg.h> #include <stdio.h> #include <stdlib.h> #include "alloc-util.h" #include "env-util.h" #include "escape.h" #include "extract-word.h" #include "fileio.h" #include "memory-util.h" #include "nulstr-util.h" #include "sort-util.h" #include "string-util.h" #include "strv.h" char* strv_find(char * const *l, const char *name) { assert(name); STRV_FOREACH(i, l) if (streq(*i, name)) return *i; return NULL; } char* strv_find_case(char * const *l, const char *name) { assert(name); STRV_FOREACH(i, l) if (strcaseeq(*i, name)) return *i; return NULL; } char* strv_find_prefix(char * const *l, const char *name) { assert(name); STRV_FOREACH(i, l) if (startswith(*i, name)) return *i; return NULL; } char* strv_find_startswith(char * const *l, const char *name) { assert(name); /* Like strv_find_prefix, but actually returns only the * suffix, not the whole item */ STRV_FOREACH(i, l) { char *e; e = startswith(*i, name); if (e) return e; } return NULL; } char* strv_find_first_field(char * const *needles, char * const *haystack) { STRV_FOREACH(k, needles) { char *value = strv_env_pairs_get((char **)haystack, *k); if (value) return value; } return NULL; } char** strv_free(char **l) { STRV_FOREACH(k, l) free(*k); return mfree(l); } char** strv_free_erase(char **l) { STRV_FOREACH(i, l) erase_and_freep(i); return mfree(l); } char** strv_copy_n(char * const *l, size_t m) { _cleanup_strv_free_ char **result = NULL; char **k; result = new(char*, MIN(strv_length(l), m) + 1); if (!result) return NULL; k = result; STRV_FOREACH(i, l) { if (m == 0) break; *k = strdup(*i); if (!*k) return NULL; k++; if (m != SIZE_MAX) m--; } *k = NULL; return TAKE_PTR(result); } size_t strv_length(char * const *l) { size_t n = 0; STRV_FOREACH(i, l) n++; return n; } char** strv_new_ap(const char *x, va_list ap) { _cleanup_strv_free_ char **a = NULL; size_t n = 0, i = 0; va_list aq; /* As a special trick we ignore all listed strings that equal * STRV_IGNORE. This is supposed to be used with the * STRV_IFNOTNULL() macro to include possibly NULL strings in * the string list. */ va_copy(aq, ap); for (const char *s = x; s; s = va_arg(aq, const char*)) { if (s == STRV_IGNORE) continue; n++; } va_end(aq); a = new(char*, n+1); if (!a) return NULL; for (const char *s = x; s; s = va_arg(ap, const char*)) { if (s == STRV_IGNORE) continue; a[i] = strdup(s); if (!a[i]) return NULL; i++; } a[i] = NULL; return TAKE_PTR(a); } char** strv_new_internal(const char *x, ...) { char **r; va_list ap; va_start(ap, x); r = strv_new_ap(x, ap); va_end(ap); return r; } int strv_extend_strv(char ***a, char * const *b, bool filter_duplicates) { size_t p, q, i = 0; char **t; assert(a); if (strv_isempty(b)) return 0; p = strv_length(*a); q = strv_length(b); if (p >= SIZE_MAX - q) return -ENOMEM; t = reallocarray(*a, GREEDY_ALLOC_ROUND_UP(p + q + 1), sizeof(char *)); if (!t) return -ENOMEM; t[p] = NULL; *a = t; STRV_FOREACH(s, b) { if (filter_duplicates && strv_contains(t, *s)) continue; t[p+i] = strdup(*s); if (!t[p+i]) goto rollback; i++; t[p+i] = NULL; } assert(i <= q); return (int) i; rollback: for (size_t j = 0; j < i; j++) free(t[p + j]); t[p] = NULL; return -ENOMEM; } int strv_extend_strv_concat(char ***a, char * const *b, const char *suffix) { int r; STRV_FOREACH(s, b) { char *v; v = strjoin(*s, suffix); if (!v) return -ENOMEM; r = strv_push(a, v); if (r < 0) { free(v); return r; } } return 0; } int strv_split_newlines_full(char ***ret, const char *s, ExtractFlags flags) { _cleanup_strv_free_ char **l = NULL; size_t n; int r; assert(s); /* Special version of strv_split_full() that splits on newlines and * suppresses an empty string at the end. */ r = strv_split_full(&l, s, NEWLINE, flags); if (r < 0) return r; n = strv_length(l); if (n > 0 && isempty(l[n - 1])) { l[n - 1] = mfree(l[n - 1]); n--; } *ret = TAKE_PTR(l); return n; } int strv_split_full(char ***t, const char *s, const char *separators, ExtractFlags flags) { _cleanup_strv_free_ char **l = NULL; size_t n = 0; int r; assert(t); assert(s); for (;;) { _cleanup_free_ char *word = NULL; r = extract_first_word(&s, &word, separators, flags); if (r < 0) return r; if (r == 0) break; if (!GREEDY_REALLOC(l, n + 2)) return -ENOMEM; l[n++] = TAKE_PTR(word); l[n] = NULL; } if (!l) { l = new0(char*, 1); if (!l) return -ENOMEM; } *t = TAKE_PTR(l); return (int) n; } int strv_split_and_extend_full(char ***t, const char *s, const char *separators, bool filter_duplicates, ExtractFlags flags) { _cleanup_strv_free_ char **l = NULL; int r; assert(t); assert(s); r = strv_split_full(&l, s, separators, flags); if (r < 0) return r; r = strv_extend_strv(t, l, filter_duplicates); if (r < 0) return r; return (int) strv_length(*t); } int strv_split_colon_pairs(char ***t, const char *s) { _cleanup_strv_free_ char **l = NULL; size_t n = 0; int r; assert(t); assert(s); for (;;) { _cleanup_free_ char *first = NULL, *second = NULL, *tuple = NULL, *second_or_empty = NULL; r = extract_first_word(&s, &tuple, NULL, EXTRACT_UNQUOTE|EXTRACT_RETAIN_ESCAPE); if (r < 0) return r; if (r == 0) break; const char *p = tuple; r = extract_many_words(&p, ":", EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS, &first, &second, NULL); if (r < 0) return r; if (r == 0) continue; /* Enforce that at most 2 colon-separated words are contained in each group */ if (!isempty(p)) return -EINVAL; second_or_empty = strdup(strempty(second)); if (!second_or_empty) return -ENOMEM; if (!GREEDY_REALLOC(l, n + 3)) return -ENOMEM; l[n++] = TAKE_PTR(first); l[n++] = TAKE_PTR(second_or_empty); l[n] = NULL; } if (!l) { l = new0(char*, 1); if (!l) return -ENOMEM; } *t = TAKE_PTR(l); return (int) n; } char* strv_join_full(char * const *l, const char *separator, const char *prefix, bool escape_separator) { char *r, *e; size_t n, k, m; if (!separator) separator = " "; k = strlen(separator); m = strlen_ptr(prefix); if (escape_separator) /* If the separator was multi-char, we wouldn't know how to escape it. */ assert(k == 1); n = 0; STRV_FOREACH(s, l) { if (s != l) n += k; bool needs_escaping = escape_separator && strchr(*s, *separator); n += m + strlen(*s) * (1 + needs_escaping); } r = new(char, n+1); if (!r) return NULL; e = r; STRV_FOREACH(s, l) { if (s != l) e = stpcpy(e, separator); if (prefix) e = stpcpy(e, prefix); bool needs_escaping = escape_separator && strchr(*s, *separator); if (needs_escaping) for (size_t i = 0; (*s)[i]; i++) { if ((*s)[i] == *separator) *(e++) = '\\'; *(e++) = (*s)[i]; } else e = stpcpy(e, *s); } *e = 0; return r; } int strv_push_with_size(char ***l, size_t *n, char *value) { /* n is a pointer to a variable to store the size of l. * If not given (i.e. n is NULL or *n is SIZE_MAX), size will be calculated using strv_length(). * If n is not NULL, the size after the push will be returned. * If value is empty, no action is taken and *n is not set. */ if (!value) return 0; size_t size = n ? *n : SIZE_MAX; if (size == SIZE_MAX) size = strv_length(*l); /* Check for overflow */ if (size > SIZE_MAX-2) return -ENOMEM; char **c = reallocarray(*l, GREEDY_ALLOC_ROUND_UP(size + 2), sizeof(char*)); if (!c) return -ENOMEM; c[size] = value; c[size+1] = NULL; *l = c; if (n) *n = size + 1; return 0; } int strv_push_pair(char ***l, char *a, char *b) { char **c; size_t n; if (!a && !b) return 0; n = strv_length(*l); /* Check for overflow */ if (n > SIZE_MAX-3) return -ENOMEM; /* increase and check for overflow */ c = reallocarray(*l, GREEDY_ALLOC_ROUND_UP(n + !!a + !!b + 1), sizeof(char*)); if (!c) return -ENOMEM; if (a) c[n++] = a; if (b) c[n++] = b; c[n] = NULL; *l = c; return 0; } int strv_insert(char ***l, size_t position, char *value) { char **c; size_t n, m; if (!value) return 0; n = strv_length(*l); position = MIN(position, n); /* increase and check for overflow */ m = n + 2; if (m < n) return -ENOMEM; c = new(char*, m); if (!c) return -ENOMEM; for (size_t i = 0; i < position; i++) c[i] = (*l)[i]; c[position] = value; for (size_t i = position; i < n; i++) c[i+1] = (*l)[i]; c[n+1] = NULL; return free_and_replace(*l, c); } int strv_consume_with_size(char ***l, size_t *n, char *value) { int r; r = strv_push_with_size(l, n, value); if (r < 0) free(value); return r; } int strv_consume_pair(char ***l, char *a, char *b) { int r; r = strv_push_pair(l, a, b); if (r < 0) { free(a); free(b); } return r; } int strv_consume_prepend(char ***l, char *value) { int r; r = strv_push_prepend(l, value); if (r < 0) free(value); return r; } int strv_prepend(char ***l, const char *value) { char *v; if (!value) return 0; v = strdup(value); if (!v) return -ENOMEM; return strv_consume_prepend(l, v); } int strv_extend_with_size(char ***l, size_t *n, const char *value) { char *v; if (!value) return 0; v = strdup(value); if (!v) return -ENOMEM; return strv_consume_with_size(l, n, v); } int strv_extend_front(char ***l, const char *value) { size_t n, m; char *v, **c; assert(l); /* Like strv_extend(), but prepends rather than appends the new entry */ if (!value) return 0; n = strv_length(*l); /* Increase and overflow check. */ m = n + 2; if (m < n) return -ENOMEM; v = strdup(value); if (!v) return -ENOMEM; c = reallocarray(*l, m, sizeof(char*)); if (!c) { free(v); return -ENOMEM; } memmove(c+1, c, n * sizeof(char*)); c[0] = v; c[n+1] = NULL; *l = c; return 0; } char** strv_uniq(char **l) { /* Drops duplicate entries. The first identical string will be * kept, the others dropped */ STRV_FOREACH(i, l) strv_remove(i+1, *i); return l; } bool strv_is_uniq(char * const *l) { STRV_FOREACH(i, l) if (strv_contains(i+1, *i)) return false; return true; } char** strv_remove(char **l, const char *s) { char **f, **t; if (!l) return NULL; assert(s); /* Drops every occurrence of s in the string list, edits * in-place. */ for (f = t = l; *f; f++) if (streq(*f, s)) free(*f); else *(t++) = *f; *t = NULL; return l; } bool strv_overlap(char * const *a, char * const *b) { STRV_FOREACH(i, a) if (strv_contains(b, *i)) return true; return false; } static int str_compare(char * const *a, char * const *b) { return strcmp(*a, *b); } char** strv_sort(char **l) { typesafe_qsort(l, strv_length(l), str_compare); return l; } int strv_compare(char * const *a, char * const *b) { int r; if (strv_isempty(a)) { if (strv_isempty(b)) return 0; else return -1; } if (strv_isempty(b)) return 1; for ( ; *a || *b; ++a, ++b) { r = strcmp_ptr(*a, *b); if (r != 0) return r; } return 0; } void strv_print_full(char * const *l, const char *prefix) { STRV_FOREACH(s, l) printf("%s%s\n", strempty(prefix), *s); } int strv_extendf(char ***l, const char *format, ...) { va_list ap; char *x; int r; va_start(ap, format); r = vasprintf(&x, format, ap); va_end(ap); if (r < 0) return -ENOMEM; return strv_consume(l, x); } char** strv_reverse(char **l) { size_t n; n = strv_length(l); if (n <= 1) return l; for (size_t i = 0; i < n / 2; i++) SWAP_TWO(l[i], l[n-1-i]); return l; } char** strv_shell_escape(char **l, const char *bad) { /* Escapes every character in every string in l that is in bad, * edits in-place, does not roll-back on error. */ STRV_FOREACH(s, l) { char *v; v = shell_escape(*s, bad); if (!v) return NULL; free_and_replace(*s, v); } return l; } bool strv_fnmatch_full( char* const* patterns, const char *s, int flags, size_t *ret_matched_pos) { assert(s); if (patterns) for (size_t i = 0; patterns[i]; i++) /* NB: We treat all fnmatch() errors as equivalent to FNM_NOMATCH, i.e. if fnmatch() fails to * process the pattern for some reason we'll consider this equivalent to non-matching. */ if (fnmatch(patterns[i], s, flags) == 0) { if (ret_matched_pos) *ret_matched_pos = i; return true; } if (ret_matched_pos) *ret_matched_pos = SIZE_MAX; return false; } char** strv_skip(char **l, size_t n) { while (n > 0) { if (strv_isempty(l)) return l; l++, n--; } return l; } int strv_extend_n(char ***l, const char *value, size_t n) { size_t i, k; char **nl; assert(l); if (!value) return 0; if (n == 0) return 0; /* Adds the value n times to l */ k = strv_length(*l); if (n >= SIZE_MAX - k) return -ENOMEM; nl = reallocarray(*l, GREEDY_ALLOC_ROUND_UP(k + n + 1), sizeof(char *)); if (!nl) return -ENOMEM; *l = nl; for (i = k; i < k + n; i++) { nl[i] = strdup(value); if (!nl[i]) goto rollback; } nl[i] = NULL; return 0; rollback: for (size_t j = k; j < i; j++) free(nl[j]); nl[k] = NULL; return -ENOMEM; } int strv_extend_assignment(char ***l, const char *lhs, const char *rhs) { char *j; assert(l); assert(lhs); if (!rhs) /* value is optional, in which case we suppress the field */ return 0; j = strjoin(lhs, "=", rhs); if (!j) return -ENOMEM; return strv_consume(l, j); } int fputstrv(FILE *f, char * const *l, const char *separator, bool *space) { bool b = false; int r; /* Like fputs(), but for strv, and with a less stupid argument order */ if (!space) space = &b; STRV_FOREACH(s, l) { r = fputs_with_space(f, *s, separator, space); if (r < 0) return r; } return 0; } static int string_strv_hashmap_put_internal(Hashmap *h, const char *key, const char *value) { char **l; int r; l = hashmap_get(h, key); if (l) { /* A list for this key already exists, let's append to it if it is not listed yet */ if (strv_contains(l, value)) return 0; r = strv_extend(&l, value); if (r < 0) return r; assert_se(hashmap_update(h, key, l) >= 0); } else { /* No list for this key exists yet, create one */ _cleanup_strv_free_ char **l2 = NULL; _cleanup_free_ char *t = NULL; t = strdup(key); if (!t) return -ENOMEM; r = strv_extend(&l2, value); if (r < 0) return r; r = hashmap_put(h, t, l2); if (r < 0) return r; TAKE_PTR(t); TAKE_PTR(l2); } return 1; } int _string_strv_hashmap_put(Hashmap **h, const char *key, const char *value HASHMAP_DEBUG_PARAMS) { int r; r = _hashmap_ensure_allocated(h, &string_strv_hash_ops HASHMAP_DEBUG_PASS_ARGS); if (r < 0) return r; return string_strv_hashmap_put_internal(*h, key, value); } int _string_strv_ordered_hashmap_put(OrderedHashmap **h, const char *key, const char *value HASHMAP_DEBUG_PARAMS) { int r; r = _ordered_hashmap_ensure_allocated(h, &string_strv_hash_ops HASHMAP_DEBUG_PASS_ARGS); if (r < 0) return r; return string_strv_hashmap_put_internal(PLAIN_HASHMAP(*h), key, value); } DEFINE_HASH_OPS_FULL(string_strv_hash_ops, char, string_hash_func, string_compare_func, free, char*, strv_free);
21,342
22.688124
126
c
null
systemd-main/src/basic/strv.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <fnmatch.h> #include <stdarg.h> #include <stdbool.h> #include <stddef.h> #include <stdio.h> #include "alloc-util.h" #include "extract-word.h" #include "hashmap.h" #include "macro.h" #include "string-util.h" char* strv_find(char * const *l, const char *name) _pure_; char* strv_find_case(char * const *l, const char *name) _pure_; char* strv_find_prefix(char * const *l, const char *name) _pure_; char* strv_find_startswith(char * const *l, const char *name) _pure_; /* Given two vectors, the first a list of keys and the second a list of key-value pairs, returns the value * of the first key from the first vector that is found in the second vector. */ char* strv_find_first_field(char * const *needles, char * const *haystack) _pure_; #define strv_contains(l, s) (!!strv_find((l), (s))) #define strv_contains_case(l, s) (!!strv_find_case((l), (s))) char** strv_free(char **l); DEFINE_TRIVIAL_CLEANUP_FUNC(char**, strv_free); #define _cleanup_strv_free_ _cleanup_(strv_freep) char** strv_free_erase(char **l); DEFINE_TRIVIAL_CLEANUP_FUNC(char**, strv_free_erase); #define _cleanup_strv_free_erase_ _cleanup_(strv_free_erasep) char** strv_copy_n(char * const *l, size_t n); static inline char** strv_copy(char * const *l) { return strv_copy_n(l, SIZE_MAX); } size_t strv_length(char * const *l) _pure_; int strv_extend_strv(char ***a, char * const *b, bool filter_duplicates); int strv_extend_strv_concat(char ***a, char * const *b, const char *suffix); int strv_prepend(char ***l, const char *value); /* _with_size() are lower-level functions where the size can be provided externally, * which allows us to skip iterating over the strv to find the end, which saves * a bit of time and reduces the complexity of appending from O(n²) to O(n). */ int strv_extend_with_size(char ***l, size_t *n, const char *value); static inline int strv_extend(char ***l, const char *value) { return strv_extend_with_size(l, NULL, value); } int strv_extendf(char ***l, const char *format, ...) _printf_(2,3); int strv_extend_front(char ***l, const char *value); int strv_push_with_size(char ***l, size_t *n, char *value); static inline int strv_push(char ***l, char *value) { return strv_push_with_size(l, NULL, value); } int strv_push_pair(char ***l, char *a, char *b); int strv_insert(char ***l, size_t position, char *value); static inline int strv_push_prepend(char ***l, char *value) { return strv_insert(l, 0, value); } int strv_consume_with_size(char ***l, size_t *n, char *value); static inline int strv_consume(char ***l, char *value) { return strv_consume_with_size(l, NULL, value); } int strv_consume_pair(char ***l, char *a, char *b); int strv_consume_prepend(char ***l, char *value); char** strv_remove(char **l, const char *s); char** strv_uniq(char **l); bool strv_is_uniq(char * const *l); int strv_compare(char * const *a, char * const *b); static inline bool strv_equal(char * const *a, char * const *b) { return strv_compare(a, b) == 0; } char** strv_new_internal(const char *x, ...) _sentinel_; char** strv_new_ap(const char *x, va_list ap); #define strv_new(...) strv_new_internal(__VA_ARGS__, NULL) #define STRV_IGNORE ((const char *) POINTER_MAX) static inline const char* STRV_IFNOTNULL(const char *x) { return x ?: STRV_IGNORE; } static inline bool strv_isempty(char * const *l) { return !l || !*l; } int strv_split_full(char ***t, const char *s, const char *separators, ExtractFlags flags); static inline char** strv_split(const char *s, const char *separators) { char **ret; if (strv_split_full(&ret, s, separators, EXTRACT_RETAIN_ESCAPE) < 0) return NULL; return ret; } int strv_split_and_extend_full(char ***t, const char *s, const char *separators, bool filter_duplicates, ExtractFlags flags); #define strv_split_and_extend(t, s, sep, dup) strv_split_and_extend_full(t, s, sep, dup, 0) int strv_split_newlines_full(char ***ret, const char *s, ExtractFlags flags); static inline char** strv_split_newlines(const char *s) { char **ret; if (strv_split_newlines_full(&ret, s, 0) < 0) return NULL; return ret; } /* Given a string containing white-space separated tuples of words themselves separated by ':', * returns a vector of strings. If the second element in a tuple is missing, the corresponding * string in the vector is an empty string. */ int strv_split_colon_pairs(char ***t, const char *s); char* strv_join_full(char * const *l, const char *separator, const char *prefix, bool escape_separator); static inline char *strv_join(char * const *l, const char *separator) { return strv_join_full(l, separator, NULL, false); } bool strv_overlap(char * const *a, char * const *b) _pure_; #define _STRV_FOREACH_BACKWARDS(s, l, h, i) \ for (typeof(*(l)) *s, *h = (l), *i = ({ \ size_t _len = strv_length(h); \ _len > 0 ? h + _len - 1 : NULL; \ }); \ (s = i); \ i = PTR_SUB1(i, h)) #define STRV_FOREACH_BACKWARDS(s, l) \ _STRV_FOREACH_BACKWARDS(s, l, UNIQ_T(h, UNIQ), UNIQ_T(i, UNIQ)) #define _STRV_FOREACH_PAIR(x, y, l, i) \ for (typeof(*l) *x, *y, *i = (l); \ i && *(x = i) && *(y = i + 1); \ i += 2) #define STRV_FOREACH_PAIR(x, y, l) \ _STRV_FOREACH_PAIR(x, y, l, UNIQ_T(i, UNIQ)) char** strv_sort(char **l); void strv_print_full(char * const *l, const char *prefix); static inline void strv_print(char * const *l) { strv_print_full(l, NULL); } #define strv_from_stdarg_alloca(first) \ ({ \ char **_l; \ \ if (!first) \ _l = (char**) &first; \ else { \ size_t _n; \ va_list _ap; \ \ _n = 1; \ va_start(_ap, first); \ while (va_arg(_ap, char*)) \ _n++; \ va_end(_ap); \ \ _l = newa(char*, _n+1); \ _l[_n = 0] = (char*) first; \ va_start(_ap, first); \ for (;;) { \ _l[++_n] = va_arg(_ap, char*); \ if (!_l[_n]) \ break; \ } \ va_end(_ap); \ } \ _l; \ }) #define STR_IN_SET(x, ...) strv_contains(STRV_MAKE(__VA_ARGS__), x) #define STRPTR_IN_SET(x, ...) \ ({ \ const char* _x = (x); \ _x && strv_contains(STRV_MAKE(__VA_ARGS__), _x); \ }) #define STRCASE_IN_SET(x, ...) strv_contains_case(STRV_MAKE(__VA_ARGS__), x) #define STRCASEPTR_IN_SET(x, ...) \ ({ \ const char* _x = (x); \ _x && strv_contains_case(STRV_MAKE(__VA_ARGS__), _x); \ }) #define ENDSWITH_SET(p, ...) \ ({ \ const char *_p = (p); \ char *_found = NULL; \ STRV_FOREACH(_i, STRV_MAKE(__VA_ARGS__)) { \ _found = endswith(_p, *_i); \ if (_found) \ break; \ } \ _found; \ }) #define _FOREACH_STRING(uniq, x, y, ...) \ for (const char *x, * const*UNIQ_T(l, uniq) = STRV_MAKE_CONST(({ x = y; }), ##__VA_ARGS__); \ x; \ x = *(++UNIQ_T(l, uniq))) #define FOREACH_STRING(x, y, ...) \ _FOREACH_STRING(UNIQ, x, y, ##__VA_ARGS__) char** strv_reverse(char **l); char** strv_shell_escape(char **l, const char *bad); bool strv_fnmatch_full(char* const* patterns, const char *s, int flags, size_t *ret_matched_pos); static inline bool strv_fnmatch(char* const* patterns, const char *s) { return strv_fnmatch_full(patterns, s, 0, NULL); } static inline bool strv_fnmatch_or_empty(char* const* patterns, const char *s, int flags) { assert(s); return strv_isempty(patterns) || strv_fnmatch_full(patterns, s, flags, NULL); } char** strv_skip(char **l, size_t n); int strv_extend_n(char ***l, const char *value, size_t n); int strv_extend_assignment(char ***l, const char *lhs, const char *rhs); int fputstrv(FILE *f, char * const *l, const char *separator, bool *space); #define strv_free_and_replace(a, b) \ free_and_replace_full(a, b, strv_free) extern const struct hash_ops string_strv_hash_ops; int _string_strv_hashmap_put(Hashmap **h, const char *key, const char *value HASHMAP_DEBUG_PARAMS); int _string_strv_ordered_hashmap_put(OrderedHashmap **h, const char *key, const char *value HASHMAP_DEBUG_PARAMS); #define string_strv_hashmap_put(h, k, v) _string_strv_hashmap_put(h, k, v HASHMAP_DEBUG_SRC_ARGS) #define string_strv_ordered_hashmap_put(h, k, v) _string_strv_ordered_hashmap_put(h, k, v HASHMAP_DEBUG_SRC_ARGS)
10,927
42.193676
125
h
null
systemd-main/src/basic/strxcpyx.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Concatenates/copies strings. In any case, terminates in all cases * with '\0' and moves the @dest pointer forward to the added '\0'. * Returns the remaining size, and 0 if the string was truncated. * * Due to the intended usage, these helpers silently noop invocations * having zero size. This is technically an exception to the above * statement "terminates in all cases". It's unexpected for such calls to * occur outside of a loop where this is the preferred behavior. */ #include <stdarg.h> #include <stdio.h> #include <string.h> #include "string-util.h" #include "strxcpyx.h" size_t strnpcpy_full(char **dest, size_t size, const char *src, size_t len, bool *ret_truncated) { bool truncated = false; assert(dest); assert(src); if (size == 0) { if (ret_truncated) *ret_truncated = len > 0; return 0; } if (len >= size) { if (size > 1) *dest = mempcpy(*dest, src, size-1); size = 0; truncated = true; } else if (len > 0) { *dest = mempcpy(*dest, src, len); size -= len; } if (ret_truncated) *ret_truncated = truncated; *dest[0] = '\0'; return size; } size_t strpcpy_full(char **dest, size_t size, const char *src, bool *ret_truncated) { assert(dest); assert(src); return strnpcpy_full(dest, size, src, strlen(src), ret_truncated); } size_t strpcpyf_full(char **dest, size_t size, bool *ret_truncated, const char *src, ...) { bool truncated = false; va_list va; int i; assert(dest); assert(src); va_start(va, src); i = vsnprintf(*dest, size, src, va); va_end(va); if (i < (int) size) { *dest += i; size -= i; } else { size = 0; truncated = i > 0; } if (ret_truncated) *ret_truncated = truncated; return size; } size_t strpcpyl_full(char **dest, size_t size, bool *ret_truncated, const char *src, ...) { bool truncated = false; va_list va; assert(dest); assert(src); va_start(va, src); do { bool t; size = strpcpy_full(dest, size, src, &t); truncated = truncated || t; src = va_arg(va, char *); } while (src); va_end(va); if (ret_truncated) *ret_truncated = truncated; return size; } size_t strnscpy_full(char *dest, size_t size, const char *src, size_t len, bool *ret_truncated) { char *s; assert(dest); assert(src); s = dest; return strnpcpy_full(&s, size, src, len, ret_truncated); } size_t strscpy_full(char *dest, size_t size, const char *src, bool *ret_truncated) { assert(dest); assert(src); return strnscpy_full(dest, size, src, strlen(src), ret_truncated); } size_t strscpyl_full(char *dest, size_t size, bool *ret_truncated, const char *src, ...) { bool truncated = false; va_list va; char *s; assert(dest); assert(src); va_start(va, src); s = dest; do { bool t; size = strpcpy_full(&s, size, src, &t); truncated = truncated || t; src = va_arg(va, char *); } while (src); va_end(va); if (ret_truncated) *ret_truncated = truncated; return size; }
3,726
24.527397
98
c
null
systemd-main/src/basic/strxcpyx.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <stddef.h> #include "macro.h" size_t strnpcpy_full(char **dest, size_t size, const char *src, size_t len, bool *ret_truncated); static inline size_t strnpcpy(char **dest, size_t size, const char *src, size_t len) { return strnpcpy_full(dest, size, src, len, NULL); } size_t strpcpy_full(char **dest, size_t size, const char *src, bool *ret_truncated); static inline size_t strpcpy(char **dest, size_t size, const char *src) { return strpcpy_full(dest, size, src, NULL); } size_t strpcpyf_full(char **dest, size_t size, bool *ret_truncated, const char *src, ...) _printf_(4, 5); #define strpcpyf(dest, size, src, ...) \ strpcpyf_full((dest), (size), NULL, (src), ##__VA_ARGS__) size_t strpcpyl_full(char **dest, size_t size, bool *ret_truncated, const char *src, ...) _sentinel_; #define strpcpyl(dest, size, src, ...) \ strpcpyl_full((dest), (size), NULL, (src), ##__VA_ARGS__) size_t strnscpy_full(char *dest, size_t size, const char *src, size_t len, bool *ret_truncated); static inline size_t strnscpy(char *dest, size_t size, const char *src, size_t len) { return strnscpy_full(dest, size, src, len, NULL); } size_t strscpy_full(char *dest, size_t size, const char *src, bool *ret_truncated); static inline size_t strscpy(char *dest, size_t size, const char *src) { return strscpy_full(dest, size, src, NULL); } size_t strscpyl_full(char *dest, size_t size, bool *ret_truncated, const char *src, ...) _sentinel_; #define strscpyl(dest, size, src, ...) \ strscpyl_full(dest, size, NULL, src, ##__VA_ARGS__)
1,661
47.882353
105
h
null
systemd-main/src/basic/sync-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <sys/stat.h> #include "fd-util.h" #include "fs-util.h" #include "path-util.h" #include "sync-util.h" int fsync_directory_of_file(int fd) { _cleanup_close_ int dfd = -EBADF; struct stat st; int r; assert(fd >= 0); /* We only reasonably can do this for regular files and directories, or for O_PATH fds, hence check * for the inode type first */ if (fstat(fd, &st) < 0) return -errno; if (S_ISDIR(st.st_mode)) { dfd = openat(fd, "..", O_RDONLY|O_DIRECTORY|O_CLOEXEC, 0); if (dfd < 0) return -errno; } else if (!S_ISREG(st.st_mode)) { /* Regular files are OK regardless if O_PATH or not, for all other * types check O_PATH flag */ r = fd_is_opath(fd); if (r < 0) return r; if (!r) /* If O_PATH this refers to the inode in the fs, in which case we can sensibly do * what is requested. Otherwise this refers to a socket, fifo or device node, where * the concept of a containing directory doesn't make too much sense. */ return -ENOTTY; } if (dfd < 0) { _cleanup_free_ char *path = NULL; r = fd_get_path(fd, &path); if (r < 0) { log_debug_errno(r, "Failed to query /proc/self/fd/%d%s: %m", fd, r == -ENOSYS ? ", ignoring" : ""); if (r == -ENOSYS) /* If /proc is not available, we're most likely running in some * chroot environment, and syncing the directory is not very * important in that case. Let's just silently do nothing. */ return 0; return r; } if (!path_is_absolute(path)) return -EINVAL; dfd = open_parent(path, O_CLOEXEC|O_NOFOLLOW, 0); if (dfd < 0) return dfd; } return RET_NERRNO(fsync(dfd)); } int fsync_full(int fd) { int r, q; /* Sync both the file and the directory */ r = RET_NERRNO(fsync(fd)); q = fsync_directory_of_file(fd); if (r < 0) /* Return earlier error */ return r; if (q == -ENOTTY) /* Ignore if the 'fd' refers to a block device or so which doesn't really have a * parent dir */ return 0; return q; } int fsync_path_at(int at_fd, const char *path) { _cleanup_close_ int opened_fd = -EBADF; int fd; if (isempty(path)) { if (at_fd == AT_FDCWD) { opened_fd = open(".", O_RDONLY|O_DIRECTORY|O_CLOEXEC); if (opened_fd < 0) return -errno; fd = opened_fd; } else fd = at_fd; } else { opened_fd = openat(at_fd, path, O_RDONLY|O_CLOEXEC|O_NONBLOCK); if (opened_fd < 0) return -errno; fd = opened_fd; } return RET_NERRNO(fsync(fd)); } int fsync_parent_at(int at_fd, const char *path) { _cleanup_close_ int opened_fd = -EBADF; if (isempty(path)) { if (at_fd != AT_FDCWD) return fsync_directory_of_file(at_fd); opened_fd = open("..", O_RDONLY|O_DIRECTORY|O_CLOEXEC); if (opened_fd < 0) return -errno; return RET_NERRNO(fsync(opened_fd)); } opened_fd = openat(at_fd, path, O_PATH|O_CLOEXEC|O_NOFOLLOW); if (opened_fd < 0) return -errno; return fsync_directory_of_file(opened_fd); } int fsync_path_and_parent_at(int at_fd, const char *path) { _cleanup_close_ int opened_fd = -EBADF; if (isempty(path)) { if (at_fd != AT_FDCWD) return fsync_full(at_fd); opened_fd = open(".", O_RDONLY|O_DIRECTORY|O_CLOEXEC); } else opened_fd = openat(at_fd, path, O_RDONLY|O_NOFOLLOW|O_NONBLOCK|O_CLOEXEC); if (opened_fd < 0) return -errno; return fsync_full(opened_fd); } int syncfs_path(int at_fd, const char *path) { _cleanup_close_ int fd = -EBADF; if (isempty(path)) { if (at_fd != AT_FDCWD) return RET_NERRNO(syncfs(at_fd)); fd = open(".", O_RDONLY|O_DIRECTORY|O_CLOEXEC); } else fd = openat(at_fd, path, O_RDONLY|O_CLOEXEC|O_NONBLOCK); if (fd < 0) return -errno; return RET_NERRNO(syncfs(fd)); }
5,146
31.16875
109
c
null
systemd-main/src/basic/sysctl-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <stdint.h> #include "macro.h" #include "stdio-util.h" #include "string-util.h" char *sysctl_normalize(char *s); int sysctl_read(const char *property, char **value); int sysctl_write(const char *property, const char *value); int sysctl_writef(const char *property, const char *format, ...) _printf_(2, 3); int sysctl_read_ip_property(int af, const char *ifname, const char *property, char **ret); int sysctl_write_ip_property(int af, const char *ifname, const char *property, const char *value); static inline int sysctl_write_ip_property_boolean(int af, const char *ifname, const char *property, bool value) { return sysctl_write_ip_property(af, ifname, property, one_zero(value)); } #define DEFINE_SYSCTL_WRITE_IP_PROPERTY(name, type, format) \ static inline int sysctl_write_ip_property_##name(int af, const char *ifname, const char *property, type value) { \ char buf[DECIMAL_STR_MAX(type)]; \ xsprintf(buf, format, value); \ return sysctl_write_ip_property(af, ifname, property, buf); \ } DEFINE_SYSCTL_WRITE_IP_PROPERTY(int, int, "%i"); DEFINE_SYSCTL_WRITE_IP_PROPERTY(uint32, uint32_t, "%" PRIu32);
1,334
42.064516
123
h
null
systemd-main/src/basic/syslog-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <syslog.h> #include "sd-id128.h" #include "glob-util.h" #include "hexdecoct.h" #include "macro.h" #include "path-util.h" #include "string-table.h" #include "syslog-util.h" #include "unit-name.h" int syslog_parse_priority(const char **p, int *priority, bool with_facility) { int a = 0, b = 0, c = 0; const char *end; size_t k; assert(p); assert(*p); assert(priority); if ((*p)[0] != '<') return 0; end = strchr(*p, '>'); if (!end) return 0; k = end - *p; assert(k > 0); if (k == 2) c = undecchar((*p)[1]); else if (k == 3) { b = undecchar((*p)[1]); c = undecchar((*p)[2]); } else if (k == 4) { a = undecchar((*p)[1]); b = undecchar((*p)[2]); c = undecchar((*p)[3]); } else return 0; if (a < 0 || b < 0 || c < 0 || (!with_facility && (a || b || c > 7))) return 0; if (with_facility) *priority = a*100 + b*10 + c; else *priority = (*priority & LOG_FACMASK) | c; *p += k + 1; return 1; } static const char *const log_facility_unshifted_table[LOG_NFACILITIES] = { [LOG_FAC(LOG_KERN)] = "kern", [LOG_FAC(LOG_USER)] = "user", [LOG_FAC(LOG_MAIL)] = "mail", [LOG_FAC(LOG_DAEMON)] = "daemon", [LOG_FAC(LOG_AUTH)] = "auth", [LOG_FAC(LOG_SYSLOG)] = "syslog", [LOG_FAC(LOG_LPR)] = "lpr", [LOG_FAC(LOG_NEWS)] = "news", [LOG_FAC(LOG_UUCP)] = "uucp", [LOG_FAC(LOG_CRON)] = "cron", [LOG_FAC(LOG_AUTHPRIV)] = "authpriv", [LOG_FAC(LOG_FTP)] = "ftp", [LOG_FAC(LOG_LOCAL0)] = "local0", [LOG_FAC(LOG_LOCAL1)] = "local1", [LOG_FAC(LOG_LOCAL2)] = "local2", [LOG_FAC(LOG_LOCAL3)] = "local3", [LOG_FAC(LOG_LOCAL4)] = "local4", [LOG_FAC(LOG_LOCAL5)] = "local5", [LOG_FAC(LOG_LOCAL6)] = "local6", [LOG_FAC(LOG_LOCAL7)] = "local7", }; DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_facility_unshifted, int, LOG_FAC(~0)); bool log_facility_unshifted_is_valid(int facility) { return facility >= 0 && facility <= LOG_FAC(~0); } static const char *const log_level_table[] = { [LOG_EMERG] = "emerg", [LOG_ALERT] = "alert", [LOG_CRIT] = "crit", [LOG_ERR] = "err", [LOG_WARNING] = "warning", [LOG_NOTICE] = "notice", [LOG_INFO] = "info", [LOG_DEBUG] = "debug", }; DEFINE_STRING_TABLE_LOOKUP_WITH_FALLBACK(log_level, int, LOG_DEBUG); bool log_level_is_valid(int level) { return level >= 0 && level <= LOG_DEBUG; } /* The maximum size for a log namespace length. This is the file name size limit 255 minus the size of a * formatted machine ID minus a separator char */ #define LOG_NAMESPACE_MAX (NAME_MAX - (SD_ID128_STRING_MAX - 1) - 1) bool log_namespace_name_valid(const char *s) { /* Let's make sure the namespace fits in a filename that is prefixed with the machine ID and a dot * (so that /var/log/journal/<machine-id>.<namespace> can be created based on it). Also make sure it * is suitable as unit instance name, and does not contain fishy characters. */ if (!filename_is_valid(s)) return false; if (strlen(s) > LOG_NAMESPACE_MAX) return false; if (!unit_instance_is_valid(s)) return false; if (!string_is_safe(s)) return false; /* Let's avoid globbing for now */ if (string_is_glob(s)) return false; return true; }
3,910
28.628788
108
c
null
systemd-main/src/basic/syslog-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> int log_facility_unshifted_to_string_alloc(int i, char **s); int log_facility_unshifted_from_string(const char *s); bool log_facility_unshifted_is_valid(int faciliy); int log_level_to_string_alloc(int i, char **s); int log_level_from_string(const char *s); bool log_level_is_valid(int level); int syslog_parse_priority(const char **p, int *priority, bool with_facility); bool log_namespace_name_valid(const char *s);
505
28.764706
77
h
null
systemd-main/src/basic/time-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <inttypes.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <stdio.h> #include <time.h> typedef uint64_t usec_t; typedef uint64_t nsec_t; #define PRI_NSEC PRIu64 #define PRI_USEC PRIu64 #define NSEC_FMT "%" PRI_NSEC #define USEC_FMT "%" PRI_USEC #include "macro.h" typedef struct dual_timestamp { usec_t realtime; usec_t monotonic; } dual_timestamp; typedef struct triple_timestamp { usec_t realtime; usec_t monotonic; usec_t boottime; } triple_timestamp; typedef enum TimestampStyle { TIMESTAMP_PRETTY, TIMESTAMP_US, TIMESTAMP_UTC, TIMESTAMP_US_UTC, TIMESTAMP_UNIX, TIMESTAMP_DATE, _TIMESTAMP_STYLE_MAX, _TIMESTAMP_STYLE_INVALID = -EINVAL, } TimestampStyle; #define USEC_INFINITY ((usec_t) UINT64_MAX) #define NSEC_INFINITY ((nsec_t) UINT64_MAX) #define MSEC_PER_SEC 1000ULL #define USEC_PER_SEC ((usec_t) 1000000ULL) #define USEC_PER_MSEC ((usec_t) 1000ULL) #define NSEC_PER_SEC ((nsec_t) 1000000000ULL) #define NSEC_PER_MSEC ((nsec_t) 1000000ULL) #define NSEC_PER_USEC ((nsec_t) 1000ULL) #define USEC_PER_MINUTE ((usec_t) (60ULL*USEC_PER_SEC)) #define NSEC_PER_MINUTE ((nsec_t) (60ULL*NSEC_PER_SEC)) #define USEC_PER_HOUR ((usec_t) (60ULL*USEC_PER_MINUTE)) #define NSEC_PER_HOUR ((nsec_t) (60ULL*NSEC_PER_MINUTE)) #define USEC_PER_DAY ((usec_t) (24ULL*USEC_PER_HOUR)) #define NSEC_PER_DAY ((nsec_t) (24ULL*NSEC_PER_HOUR)) #define USEC_PER_WEEK ((usec_t) (7ULL*USEC_PER_DAY)) #define NSEC_PER_WEEK ((nsec_t) (7ULL*NSEC_PER_DAY)) #define USEC_PER_MONTH ((usec_t) (2629800ULL*USEC_PER_SEC)) #define NSEC_PER_MONTH ((nsec_t) (2629800ULL*NSEC_PER_SEC)) #define USEC_PER_YEAR ((usec_t) (31557600ULL*USEC_PER_SEC)) #define NSEC_PER_YEAR ((nsec_t) (31557600ULL*NSEC_PER_SEC)) /* We assume a maximum timezone length of 6. TZNAME_MAX is not defined on Linux, but glibc internally initializes this * to 6. Let's rely on that. */ #define FORMAT_TIMESTAMP_MAX (3U+1U+10U+1U+8U+1U+6U+1U+6U+1U) #define FORMAT_TIMESTAMP_RELATIVE_MAX 256U #define FORMAT_TIMESPAN_MAX 64U #define TIME_T_MAX (time_t)((UINTMAX_C(1) << ((sizeof(time_t) << 3) - 1)) - 1) #define DUAL_TIMESTAMP_NULL ((struct dual_timestamp) {}) #define TRIPLE_TIMESTAMP_NULL ((struct triple_timestamp) {}) usec_t now(clockid_t clock); nsec_t now_nsec(clockid_t clock); usec_t map_clock_usec(usec_t from, clockid_t from_clock, clockid_t to_clock); dual_timestamp* dual_timestamp_get(dual_timestamp *ts); dual_timestamp* dual_timestamp_from_realtime(dual_timestamp *ts, usec_t u); dual_timestamp* dual_timestamp_from_monotonic(dual_timestamp *ts, usec_t u); dual_timestamp* dual_timestamp_from_boottime(dual_timestamp *ts, usec_t u); triple_timestamp* triple_timestamp_get(triple_timestamp *ts); triple_timestamp* triple_timestamp_from_realtime(triple_timestamp *ts, usec_t u); #define DUAL_TIMESTAMP_HAS_CLOCK(clock) \ IN_SET(clock, CLOCK_REALTIME, CLOCK_REALTIME_ALARM, CLOCK_MONOTONIC) #define TRIPLE_TIMESTAMP_HAS_CLOCK(clock) \ IN_SET(clock, CLOCK_REALTIME, CLOCK_REALTIME_ALARM, CLOCK_MONOTONIC, CLOCK_BOOTTIME, CLOCK_BOOTTIME_ALARM) static inline bool timestamp_is_set(usec_t timestamp) { return timestamp > 0 && timestamp != USEC_INFINITY; } static inline bool dual_timestamp_is_set(const dual_timestamp *ts) { return timestamp_is_set(ts->realtime) || timestamp_is_set(ts->monotonic); } static inline bool triple_timestamp_is_set(const triple_timestamp *ts) { return timestamp_is_set(ts->realtime) || timestamp_is_set(ts->monotonic) || timestamp_is_set(ts->boottime); } usec_t triple_timestamp_by_clock(triple_timestamp *ts, clockid_t clock); usec_t timespec_load(const struct timespec *ts) _pure_; nsec_t timespec_load_nsec(const struct timespec *ts) _pure_; struct timespec* timespec_store(struct timespec *ts, usec_t u); struct timespec* timespec_store_nsec(struct timespec *ts, nsec_t n); #define TIMESPEC_STORE(u) timespec_store(&(struct timespec) {}, (u)) usec_t timeval_load(const struct timeval *tv) _pure_; struct timeval* timeval_store(struct timeval *tv, usec_t u); #define TIMEVAL_STORE(u) timeval_store(&(struct timeval) {}, (u)) char* format_timestamp_style(char *buf, size_t l, usec_t t, TimestampStyle style) _warn_unused_result_; char* format_timestamp_relative_full(char *buf, size_t l, usec_t t, clockid_t clock, bool implicit_left) _warn_unused_result_; char* format_timespan(char *buf, size_t l, usec_t t, usec_t accuracy) _warn_unused_result_; _warn_unused_result_ static inline char* format_timestamp_relative(char *buf, size_t l, usec_t t) { return format_timestamp_relative_full(buf, l, t, CLOCK_REALTIME, /* implicit_left = */ false); } _warn_unused_result_ static inline char* format_timestamp_relative_monotonic(char *buf, size_t l, usec_t t) { return format_timestamp_relative_full(buf, l, t, CLOCK_MONOTONIC, /* implicit_left = */ false); } _warn_unused_result_ static inline char* format_timestamp(char *buf, size_t l, usec_t t) { return format_timestamp_style(buf, l, t, TIMESTAMP_PRETTY); } /* Note: the lifetime of the compound literal is the immediately surrounding block, * see C11 §6.5.2.5, and * https://stackoverflow.com/questions/34880638/compound-literal-lifetime-and-if-blocks */ #define FORMAT_TIMESTAMP(t) format_timestamp((char[FORMAT_TIMESTAMP_MAX]){}, FORMAT_TIMESTAMP_MAX, t) #define FORMAT_TIMESTAMP_RELATIVE(t) \ format_timestamp_relative((char[FORMAT_TIMESTAMP_RELATIVE_MAX]){}, FORMAT_TIMESTAMP_RELATIVE_MAX, t) #define FORMAT_TIMESTAMP_RELATIVE_MONOTONIC(t) \ format_timestamp_relative_monotonic((char[FORMAT_TIMESTAMP_RELATIVE_MAX]){}, FORMAT_TIMESTAMP_RELATIVE_MAX, t) #define FORMAT_TIMESPAN(t, accuracy) format_timespan((char[FORMAT_TIMESPAN_MAX]){}, FORMAT_TIMESPAN_MAX, t, accuracy) #define FORMAT_TIMESTAMP_STYLE(t, style) \ format_timestamp_style((char[FORMAT_TIMESTAMP_MAX]){}, FORMAT_TIMESTAMP_MAX, t, style) int parse_timestamp(const char *t, usec_t *ret); int parse_sec(const char *t, usec_t *ret); int parse_sec_fix_0(const char *t, usec_t *ret); int parse_sec_def_infinity(const char *t, usec_t *ret); int parse_time(const char *t, usec_t *ret, usec_t default_unit); int parse_nsec(const char *t, nsec_t *ret); int get_timezones(char ***ret); int verify_timezone(const char *name, int log_level); static inline bool timezone_is_valid(const char *name, int log_level) { return verify_timezone(name, log_level) >= 0; } bool clock_supported(clockid_t clock); usec_t usec_shift_clock(usec_t, clockid_t from, clockid_t to); int get_timezone(char **ret); time_t mktime_or_timegm(struct tm *tm, bool utc); struct tm *localtime_or_gmtime_r(const time_t *t, struct tm *tm, bool utc); uint32_t usec_to_jiffies(usec_t usec); usec_t jiffies_to_usec(uint32_t jiffies); bool in_utc_timezone(void); static inline usec_t usec_add(usec_t a, usec_t b) { /* Adds two time values, and makes sure USEC_INFINITY as input results as USEC_INFINITY in output, * and doesn't overflow. */ if (a > USEC_INFINITY - b) /* overflow check */ return USEC_INFINITY; return a + b; } static inline usec_t usec_sub_unsigned(usec_t timestamp, usec_t delta) { if (timestamp == USEC_INFINITY) /* Make sure infinity doesn't degrade */ return USEC_INFINITY; if (timestamp < delta) return 0; return timestamp - delta; } static inline usec_t usec_sub_signed(usec_t timestamp, int64_t delta) { if (delta == INT64_MIN) { /* prevent overflow */ assert_cc(-(INT64_MIN + 1) == INT64_MAX); assert_cc(USEC_INFINITY > INT64_MAX); return usec_add(timestamp, (usec_t) INT64_MAX + 1); } if (delta < 0) return usec_add(timestamp, (usec_t) (-delta)); return usec_sub_unsigned(timestamp, (usec_t) delta); } static inline int usleep_safe(usec_t usec) { /* usleep() takes useconds_t that is (typically?) uint32_t. Also, usleep() may only support the * range [0, 1000000]. See usleep(3). Let's override usleep() with nanosleep(). */ // FIXME: use RET_NERRNO() macro here. Currently, this header cannot include errno-util.h. return nanosleep(TIMESPEC_STORE(usec), NULL) < 0 ? -errno : 0; } /* The last second we can format is 31. Dec 9999, 1s before midnight, because otherwise we'd enter 5 digit * year territory. However, since we want to stay away from this in all timezones we take one day off. */ #define USEC_TIMESTAMP_FORMATTABLE_MAX_64BIT ((usec_t) 253402214399000000) /* Thu 9999-12-30 23:59:59 UTC */ /* With a 32-bit time_t we can't go beyond 2038... * We parse timestamp with RFC-822/ISO 8601 (e.g. +06, or -03:00) as UTC, hence the upper bound must be off * by USEC_PER_DAY. See parse_timestamp() for more details. */ #define USEC_TIMESTAMP_FORMATTABLE_MAX_32BIT (((usec_t) INT32_MAX) * USEC_PER_SEC - USEC_PER_DAY) #if SIZEOF_TIME_T == 8 # define USEC_TIMESTAMP_FORMATTABLE_MAX USEC_TIMESTAMP_FORMATTABLE_MAX_64BIT #elif SIZEOF_TIME_T == 4 # define USEC_TIMESTAMP_FORMATTABLE_MAX USEC_TIMESTAMP_FORMATTABLE_MAX_32BIT #else # error "Yuck, time_t is neither 4 nor 8 bytes wide?" #endif int time_change_fd(void); const char* timestamp_style_to_string(TimestampStyle t) _const_; TimestampStyle timestamp_style_from_string(const char *s) _pure_;
9,672
39.136929
126
h
null
systemd-main/src/basic/tmpfile-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/mman.h> #include "alloc-util.h" #include "fd-util.h" #include "fileio.h" #include "fs-util.h" #include "hexdecoct.h" #include "macro.h" #include "memfd-util.h" #include "missing_fcntl.h" #include "missing_syscall.h" #include "path-util.h" #include "process-util.h" #include "random-util.h" #include "stat-util.h" #include "stdio-util.h" #include "string-util.h" #include "sync-util.h" #include "tmpfile-util.h" #include "umask-util.h" static int fopen_temporary_internal(int dir_fd, const char *path, FILE **ret_file) { _cleanup_fclose_ FILE *f = NULL; _cleanup_close_ int fd = -EBADF; int r; assert(dir_fd >= 0 || dir_fd == AT_FDCWD); assert(path); fd = openat(dir_fd, path, O_CLOEXEC|O_NOCTTY|O_RDWR|O_CREAT|O_EXCL, 0600); if (fd < 0) return -errno; /* This assumes that returned FILE object is short-lived and used within the same single-threaded * context and never shared externally, hence locking is not necessary. */ r = take_fdopen_unlocked(&fd, "w", &f); if (r < 0) { (void) unlinkat(dir_fd, path, 0); return r; } if (ret_file) *ret_file = TAKE_PTR(f); return 0; } int fopen_temporary_at(int dir_fd, const char *path, FILE **ret_file, char **ret_path) { _cleanup_free_ char *t = NULL; int r; assert(dir_fd >= 0 || dir_fd == AT_FDCWD); assert(path); r = tempfn_random(path, NULL, &t); if (r < 0) return r; r = fopen_temporary_internal(dir_fd, t, ret_file); if (r < 0) return r; if (ret_path) *ret_path = TAKE_PTR(t); return 0; } int fopen_temporary_child_at(int dir_fd, const char *path, FILE **ret_file, char **ret_path) { _cleanup_free_ char *t = NULL; int r; assert(dir_fd >= 0 || dir_fd == AT_FDCWD); if (!path) { r = tmp_dir(&path); if (r < 0) return r; } r = tempfn_random_child(path, NULL, &t); if (r < 0) return r; r = fopen_temporary_internal(dir_fd, t, ret_file); if (r < 0) return r; if (ret_path) *ret_path = TAKE_PTR(t); return 0; } /* This is much like mkostemp() but is subject to umask(). */ int mkostemp_safe(char *pattern) { assert(pattern); BLOCK_WITH_UMASK(0077); return RET_NERRNO(mkostemp(pattern, O_CLOEXEC)); } int fmkostemp_safe(char *pattern, const char *mode, FILE **ret_f) { _cleanup_close_ int fd = -EBADF; FILE *f; fd = mkostemp_safe(pattern); if (fd < 0) return fd; f = take_fdopen(&fd, mode); if (!f) return -errno; *ret_f = f; return 0; } static int tempfn_build(const char *p, const char *pre, const char *post, bool child, char **ret) { _cleanup_free_ char *d = NULL, *fn = NULL, *nf = NULL, *result = NULL; size_t len_pre, len_post, len_add; int r; assert(p); assert(ret); /* * Turns this: * /foo/bar/waldo * * Into this : * /foo/bar/waldo/.#<pre><post> (child == true) * /foo/bar/.#<pre>waldo<post> (child == false) */ if (pre && strchr(pre, '/')) return -EINVAL; if (post && strchr(post, '/')) return -EINVAL; len_pre = strlen_ptr(pre); len_post = strlen_ptr(post); /* NAME_MAX is counted *without* the trailing NUL byte. */ if (len_pre > NAME_MAX - STRLEN(".#") || len_post > NAME_MAX - STRLEN(".#") - len_pre) return -EINVAL; len_add = len_pre + len_post + STRLEN(".#"); if (child) { d = strdup(p); if (!d) return -ENOMEM; } else { r = path_extract_directory(p, &d); if (r < 0 && r != -EDESTADDRREQ) /* EDESTADDRREQ → No directory specified, just a filename */ return r; r = path_extract_filename(p, &fn); if (r < 0) return r; if (strlen(fn) > NAME_MAX - len_add) /* We cannot simply prepend and append strings to the filename. Let's truncate the filename. */ fn[NAME_MAX - len_add] = '\0'; } nf = strjoin(".#", strempty(pre), strempty(fn), strempty(post)); if (!nf) return -ENOMEM; if (d) { if (!path_extend(&d, nf)) return -ENOMEM; result = path_simplify(TAKE_PTR(d)); } else result = TAKE_PTR(nf); if (!path_is_valid(result)) /* New path is not valid? (Maybe because too long?) Refuse. */ return -EINVAL; *ret = TAKE_PTR(result); return 0; } int tempfn_xxxxxx(const char *p, const char *extra, char **ret) { /* * Turns this: * /foo/bar/waldo * * Into this: * /foo/bar/.#<extra>waldoXXXXXX */ return tempfn_build(p, extra, "XXXXXX", /* child = */ false, ret); } int tempfn_random(const char *p, const char *extra, char **ret) { _cleanup_free_ char *s = NULL; assert(p); assert(ret); /* * Turns this: * /foo/bar/waldo * * Into this: * /foo/bar/.#<extra>waldobaa2a261115984a9 */ if (asprintf(&s, "%016" PRIx64, random_u64()) < 0) return -ENOMEM; return tempfn_build(p, extra, s, /* child = */ false, ret); } int tempfn_random_child(const char *p, const char *extra, char **ret) { _cleanup_free_ char *s = NULL; int r; assert(ret); /* Turns this: * /foo/bar/waldo * Into this: * /foo/bar/waldo/.#<extra>3c2b6219aa75d7d0 */ if (!p) { r = tmp_dir(&p); if (r < 0) return r; } if (asprintf(&s, "%016" PRIx64, random_u64()) < 0) return -ENOMEM; return tempfn_build(p, extra, s, /* child = */ true, ret); } int open_tmpfile_unlinkable(const char *directory, int flags) { char *p; int fd, r; if (!directory) { r = tmp_dir(&directory); if (r < 0) return r; } else if (isempty(directory)) return -EINVAL; /* Returns an unlinked temporary file that cannot be linked into the file system anymore */ /* Try O_TMPFILE first, if it is supported */ fd = open(directory, flags|O_TMPFILE|O_EXCL, S_IRUSR|S_IWUSR); if (fd >= 0) return fd; /* Fall back to unguessable name + unlinking */ p = strjoina(directory, "/systemd-tmp-XXXXXX"); fd = mkostemp_safe(p); if (fd < 0) return fd; (void) unlink(p); return fd; } int open_tmpfile_linkable_at(int dir_fd, const char *target, int flags, char **ret_path) { _cleanup_free_ char *tmp = NULL; int r, fd; assert(target); assert(ret_path); /* Don't allow O_EXCL, as that has a special meaning for O_TMPFILE */ assert((flags & O_EXCL) == 0); /* Creates a temporary file, that shall be renamed to "target" later. If possible, this uses O_TMPFILE – in * which case "ret_path" will be returned as NULL. If not possible the temporary path name used is returned in * "ret_path". Use link_tmpfile() below to rename the result after writing the file in full. */ fd = open_parent_at(dir_fd, target, O_TMPFILE|flags, 0640); if (fd >= 0) { *ret_path = NULL; return fd; } log_debug_errno(fd, "Failed to use O_TMPFILE for %s: %m", target); r = tempfn_random(target, NULL, &tmp); if (r < 0) return r; fd = openat(dir_fd, tmp, O_CREAT|O_EXCL|O_NOFOLLOW|O_NOCTTY|flags, 0640); if (fd < 0) return -errno; *ret_path = TAKE_PTR(tmp); return fd; } int fopen_tmpfile_linkable(const char *target, int flags, char **ret_path, FILE **ret_file) { _cleanup_free_ char *path = NULL; _cleanup_fclose_ FILE *f = NULL; _cleanup_close_ int fd = -EBADF; assert(target); assert(ret_file); assert(ret_path); fd = open_tmpfile_linkable(target, flags, &path); if (fd < 0) return fd; f = take_fdopen(&fd, "w"); if (!f) return -ENOMEM; *ret_path = TAKE_PTR(path); *ret_file = TAKE_PTR(f); return 0; } static int link_fd(int fd, int newdirfd, const char *newpath) { int r; assert(fd >= 0); assert(newdirfd >= 0 || newdirfd == AT_FDCWD); assert(newpath); /* Try symlinking via /proc/fd/ first. */ r = RET_NERRNO(linkat(AT_FDCWD, FORMAT_PROC_FD_PATH(fd), newdirfd, newpath, AT_SYMLINK_FOLLOW)); if (r != -ENOENT) return r; /* Fall back to symlinking via AT_EMPTY_PATH as fallback (this requires CAP_DAC_READ_SEARCH and a * more recent kernel, but does not require /proc/ mounted) */ if (proc_mounted() != 0) return r; return RET_NERRNO(linkat(fd, "", newdirfd, newpath, AT_EMPTY_PATH)); } int link_tmpfile_at(int fd, int dir_fd, const char *path, const char *target, LinkTmpfileFlags flags) { _cleanup_free_ char *tmp = NULL; int r; assert(fd >= 0); assert(dir_fd >= 0 || dir_fd == AT_FDCWD); assert(target); /* Moves a temporary file created with open_tmpfile() above into its final place. If "path" is NULL * an fd created with O_TMPFILE is assumed, and linkat() is used. Otherwise it is assumed O_TMPFILE * is not supported on the directory, and renameat2() is used instead. */ if (FLAGS_SET(flags, LINK_TMPFILE_SYNC) && fsync(fd) < 0) return -errno; if (path) { if (FLAGS_SET(flags, LINK_TMPFILE_REPLACE)) r = RET_NERRNO(renameat(dir_fd, path, dir_fd, target)); else r = rename_noreplace(dir_fd, path, dir_fd, target); if (r < 0) return r; } else { r = link_fd(fd, dir_fd, target); if (r != -EEXIST || !FLAGS_SET(flags, LINK_TMPFILE_REPLACE)) return r; /* So the target already exists and we were asked to replace it. That sucks a bit, since the kernel's * linkat() logic does not allow that. We work-around this by linking the file to a random name * first, and then renaming that to the final name. This reintroduces the race O_TMPFILE kinda is * trying to fix, but at least the vulnerability window (i.e. where the file is linked into the file * system under a temporary name) is very short. */ r = tempfn_random(target, NULL, &tmp); if (r < 0) return r; if (link_fd(fd, dir_fd, tmp) < 0) return -EEXIST; /* propagate original error */ r = RET_NERRNO(renameat(dir_fd, tmp, dir_fd, target)); if (r < 0) { (void) unlinkat(dir_fd, tmp, 0); return r; } } if (FLAGS_SET(flags, LINK_TMPFILE_SYNC)) { r = fsync_full(fd); if (r < 0) return r; } return 0; } int flink_tmpfile(FILE *f, const char *path, const char *target, LinkTmpfileFlags flags) { int fd, r; assert(f); assert(target); fd = fileno(f); if (fd < 0) /* Not all FILE* objects encapsulate fds */ return -EBADF; r = fflush_and_check(f); if (r < 0) return r; return link_tmpfile(fd, path, target, flags); } int mkdtemp_malloc(const char *template, char **ret) { _cleanup_free_ char *p = NULL; int r; assert(ret); if (template) p = strdup(template); else { const char *tmp; r = tmp_dir(&tmp); if (r < 0) return r; p = path_join(tmp, "XXXXXX"); } if (!p) return -ENOMEM; if (!mkdtemp(p)) return -errno; *ret = TAKE_PTR(p); return 0; } int mkdtemp_open(const char *template, int flags, char **ret) { _cleanup_free_ char *p = NULL; int fd, r; r = mkdtemp_malloc(template, &p); if (r < 0) return r; fd = RET_NERRNO(open(p, O_DIRECTORY|O_CLOEXEC|flags)); if (fd < 0) { (void) rmdir(p); return fd; } if (ret) *ret = TAKE_PTR(p); return fd; }
13,575
27.701903
119
c
null
systemd-main/src/basic/tmpfile-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <fcntl.h> #include <stdbool.h> #include <stdio.h> int fopen_temporary_at(int dir_fd, const char *path, FILE **ret_file, char **ret_path); static inline int fopen_temporary(const char *path, FILE **ret_file, char **ret_path) { return fopen_temporary_at(AT_FDCWD, path, ret_file, ret_path); } int fopen_temporary_child_at(int dir_fd, const char *path, FILE **ret_file, char **ret_path); static inline int fopen_temporary_child(const char *path, FILE **ret_file, char **ret_path) { return fopen_temporary_child_at(AT_FDCWD, path, ret_file, ret_path); } int mkostemp_safe(char *pattern); int fmkostemp_safe(char *pattern, const char *mode, FILE**_f); int tempfn_xxxxxx(const char *p, const char *extra, char **ret); int tempfn_random(const char *p, const char *extra, char **ret); int tempfn_random_child(const char *p, const char *extra, char **ret); int open_tmpfile_unlinkable(const char *directory, int flags); int open_tmpfile_linkable_at(int dir_fd, const char *target, int flags, char **ret_path); static inline int open_tmpfile_linkable(const char *target, int flags, char **ret_path) { return open_tmpfile_linkable_at(AT_FDCWD, target, flags, ret_path); } int fopen_tmpfile_linkable(const char *target, int flags, char **ret_path, FILE **ret_file); typedef enum LinkTmpfileFlags { LINK_TMPFILE_REPLACE = 1 << 0, LINK_TMPFILE_SYNC = 1 << 1, } LinkTmpfileFlags; int link_tmpfile_at(int fd, int dir_fd, const char *path, const char *target, LinkTmpfileFlags flags); static inline int link_tmpfile(int fd, const char *path, const char *target, LinkTmpfileFlags flags) { return link_tmpfile_at(fd, AT_FDCWD, path, target, flags); } int flink_tmpfile(FILE *f, const char *path, const char *target, LinkTmpfileFlags flags); int mkdtemp_malloc(const char *template, char **ret); int mkdtemp_open(const char *template, int flags, char **ret);
1,970
42.8
102
h
null
systemd-main/src/basic/uid-alloc-range.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "chase.h" #include "fd-util.h" #include "fileio.h" #include "missing_threads.h" #include "string-util.h" #include "uid-alloc-range.h" #include "user-util.h" static const UGIDAllocationRange default_ugid_allocation_range = { .system_alloc_uid_min = SYSTEM_ALLOC_UID_MIN, .system_uid_max = SYSTEM_UID_MAX, .system_alloc_gid_min = SYSTEM_ALLOC_GID_MIN, .system_gid_max = SYSTEM_GID_MAX, }; #if ENABLE_COMPAT_MUTABLE_UID_BOUNDARIES static int parse_alloc_uid(const char *path, const char *name, const char *t, uid_t *ret_uid) { uid_t uid; int r; r = parse_uid(t, &uid); if (r < 0) return log_debug_errno(r, "%s: failed to parse %s %s, ignoring: %m", path, name, t); if (uid == 0) uid = 1; *ret_uid = uid; return 0; } #endif int read_login_defs(UGIDAllocationRange *ret_defs, const char *path, const char *root) { #if ENABLE_COMPAT_MUTABLE_UID_BOUNDARIES _cleanup_fclose_ FILE *f = NULL; UGIDAllocationRange defs; int r; if (!path) path = "/etc/login.defs"; r = chase_and_fopen_unlocked(path, root, CHASE_PREFIX_ROOT, "re", NULL, &f); if (r == -ENOENT) goto defaults; if (r < 0) return log_debug_errno(r, "Failed to open %s: %m", path); defs = default_ugid_allocation_range; for (;;) { _cleanup_free_ char *line = NULL; char *t; r = read_line(f, LINE_MAX, &line); if (r < 0) return log_debug_errno(r, "Failed to read %s: %m", path); if (r == 0) break; if ((t = first_word(line, "SYS_UID_MIN"))) (void) parse_alloc_uid(path, "SYS_UID_MIN", t, &defs.system_alloc_uid_min); else if ((t = first_word(line, "SYS_UID_MAX"))) (void) parse_alloc_uid(path, "SYS_UID_MAX", t, &defs.system_uid_max); else if ((t = first_word(line, "SYS_GID_MIN"))) (void) parse_alloc_uid(path, "SYS_GID_MIN", t, &defs.system_alloc_gid_min); else if ((t = first_word(line, "SYS_GID_MAX"))) (void) parse_alloc_uid(path, "SYS_GID_MAX", t, &defs.system_gid_max); } if (defs.system_alloc_uid_min > defs.system_uid_max) { log_debug("%s: SYS_UID_MIN > SYS_UID_MAX, resetting.", path); defs.system_alloc_uid_min = MIN(defs.system_uid_max - 1, (uid_t) SYSTEM_ALLOC_UID_MIN); /* Look at sys_uid_max to make sure sys_uid_min..sys_uid_max remains a valid range. */ } if (defs.system_alloc_gid_min > defs.system_gid_max) { log_debug("%s: SYS_GID_MIN > SYS_GID_MAX, resetting.", path); defs.system_alloc_gid_min = MIN(defs.system_gid_max - 1, (gid_t) SYSTEM_ALLOC_GID_MIN); /* Look at sys_gid_max to make sure sys_gid_min..sys_gid_max remains a valid range. */ } *ret_defs = defs; return 1; defaults: #endif *ret_defs = default_ugid_allocation_range; return 0; } const UGIDAllocationRange *acquire_ugid_allocation_range(void) { #if ENABLE_COMPAT_MUTABLE_UID_BOUNDARIES static thread_local UGIDAllocationRange defs; static thread_local int initialized = 0; /* == 0 → not initialized yet * < 0 → failure * > 0 → success */ /* This function will ignore failure to read the file, so it should only be called from places where * we don't crucially depend on the answer. In other words, it's appropriate for journald, but * probably not for sysusers. */ if (initialized == 0) initialized = read_login_defs(&defs, NULL, NULL) < 0 ? -1 : 1; if (initialized < 0) return &default_ugid_allocation_range; return &defs; #endif return &default_ugid_allocation_range; } bool uid_is_system(uid_t uid) { const UGIDAllocationRange *defs; assert_se(defs = acquire_ugid_allocation_range()); return uid <= defs->system_uid_max; } bool gid_is_system(gid_t gid) { const UGIDAllocationRange *defs; assert_se(defs = acquire_ugid_allocation_range()); return gid <= defs->system_gid_max; } bool uid_for_system_journal(uid_t uid) { /* Returns true if the specified UID shall get its data stored in the system journal. */ return uid_is_system(uid) || uid_is_dynamic(uid) || uid == UID_NOBODY || uid_is_container(uid); }
4,794
35.325758
108
c
null
systemd-main/src/basic/uid-alloc-range.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <sys/types.h> bool uid_is_system(uid_t uid); bool gid_is_system(gid_t gid); static inline bool uid_is_dynamic(uid_t uid) { return DYNAMIC_UID_MIN <= uid && uid <= DYNAMIC_UID_MAX; } static inline bool gid_is_dynamic(gid_t gid) { return uid_is_dynamic((uid_t) gid); } static inline bool uid_is_container(uid_t uid) { return CONTAINER_UID_BASE_MIN <= uid && uid <= CONTAINER_UID_BASE_MAX; } static inline bool gid_is_container(gid_t gid) { return uid_is_container((uid_t) gid); } typedef struct UGIDAllocationRange { uid_t system_alloc_uid_min; uid_t system_uid_max; gid_t system_alloc_gid_min; gid_t system_gid_max; } UGIDAllocationRange; int read_login_defs(UGIDAllocationRange *ret_defs, const char *path, const char *root); const UGIDAllocationRange *acquire_ugid_allocation_range(void); bool uid_for_system_journal(uid_t uid);
995
25.918919
87
h
null
systemd-main/src/basic/uid-range.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <stdlib.h> #include <string.h> #include "alloc-util.h" #include "errno-util.h" #include "fd-util.h" #include "format-util.h" #include "macro.h" #include "path-util.h" #include "sort-util.h" #include "stat-util.h" #include "uid-range.h" #include "user-util.h" UidRange *uid_range_free(UidRange *range) { if (!range) return NULL; free(range->entries); return mfree(range); } static bool uid_range_entry_intersect(const UidRangeEntry *a, const UidRangeEntry *b) { assert(a); assert(b); return a->start <= b->start + b->nr && a->start + a->nr >= b->start; } static int uid_range_entry_compare(const UidRangeEntry *a, const UidRangeEntry *b) { int r; assert(a); assert(b); r = CMP(a->start, b->start); if (r != 0) return r; return CMP(a->nr, b->nr); } static void uid_range_coalesce(UidRange *range) { assert(range); if (range->n_entries <= 0) return; typesafe_qsort(range->entries, range->n_entries, uid_range_entry_compare); for (size_t i = 0; i < range->n_entries; i++) { UidRangeEntry *x = range->entries + i; for (size_t j = i + 1; j < range->n_entries; j++) { UidRangeEntry *y = range->entries + j; uid_t begin, end; if (!uid_range_entry_intersect(x, y)) break; begin = MIN(x->start, y->start); end = MAX(x->start + x->nr, y->start + y->nr); x->start = begin; x->nr = end - begin; if (range->n_entries > j + 1) memmove(y, y + 1, sizeof(UidRangeEntry) * (range->n_entries - j - 1)); range->n_entries--; j--; } } } int uid_range_add_internal(UidRange **range, uid_t start, uid_t nr, bool coalesce) { _cleanup_(uid_range_freep) UidRange *range_new = NULL; UidRange *p; assert(range); if (nr <= 0) return 0; if (start > UINT32_MAX - nr) /* overflow check */ return -ERANGE; if (*range) p = *range; else { range_new = new0(UidRange, 1); if (!range_new) return -ENOMEM; p = range_new; } if (!GREEDY_REALLOC(p->entries, p->n_entries + 1)) return -ENOMEM; p->entries[p->n_entries++] = (UidRangeEntry) { .start = start, .nr = nr, }; if (coalesce) uid_range_coalesce(p); TAKE_PTR(range_new); *range = p; return 0; } int uid_range_add_str(UidRange **range, const char *s) { uid_t start, end; int r; assert(range); assert(s); r = parse_uid_range(s, &start, &end); if (r < 0) return r; return uid_range_add_internal(range, start, end - start + 1, /* coalesce = */ true); } int uid_range_next_lower(const UidRange *range, uid_t *uid) { uid_t closest = UID_INVALID, candidate; assert(range); assert(uid); if (*uid == 0) return -EBUSY; candidate = *uid - 1; for (size_t i = 0; i < range->n_entries; i++) { uid_t begin, end; begin = range->entries[i].start; end = range->entries[i].start + range->entries[i].nr - 1; if (candidate >= begin && candidate <= end) { *uid = candidate; return 1; } if (end < candidate) closest = end; } if (closest == UID_INVALID) return -EBUSY; *uid = closest; return 1; } bool uid_range_covers(const UidRange *range, uid_t start, uid_t nr) { if (nr == 0) /* empty range? always covered... */ return true; if (start > UINT32_MAX - nr) /* range overflows? definitely not covered... */ return false; if (!range) return false; for (size_t i = 0; i < range->n_entries; i++) if (start >= range->entries[i].start && start + nr <= range->entries[i].start + range->entries[i].nr) return true; return false; } int uid_range_load_userns(UidRange **ret, const char *path) { _cleanup_(uid_range_freep) UidRange *range = NULL; _cleanup_fclose_ FILE *f = NULL; int r; /* If 'path' is NULL loads the UID range of the userns namespace we run. Otherwise load the data from * the specified file (which can be either uid_map or gid_map, in case caller needs to deal with GID * maps). * * To simplify things this will modify the passed array in case of later failure. */ assert(ret); if (!path) path = "/proc/self/uid_map"; f = fopen(path, "re"); if (!f) { r = -errno; if (r == -ENOENT && path_startswith(path, "/proc/")) return proc_mounted() > 0 ? -EOPNOTSUPP : -ENOSYS; return r; } range = new0(UidRange, 1); if (!range) return -ENOMEM; for (;;) { uid_t uid_base, uid_shift, uid_range; int k; errno = 0; k = fscanf(f, UID_FMT " " UID_FMT " " UID_FMT "\n", &uid_base, &uid_shift, &uid_range); if (k == EOF) { if (ferror(f)) return errno_or_else(EIO); break; } if (k != 3) return -EBADMSG; r = uid_range_add_internal(&range, uid_base, uid_range, /* coalesce = */ false); if (r < 0) return r; } uid_range_coalesce(range); *ret = TAKE_PTR(range); return 0; }
6,371
25.773109
109
c
null
systemd-main/src/basic/uid-range.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <sys/types.h> #include "macro.h" typedef struct UidRangeEntry { uid_t start, nr; } UidRangeEntry; typedef struct UidRange { UidRangeEntry *entries; size_t n_entries; } UidRange; UidRange *uid_range_free(UidRange *range); DEFINE_TRIVIAL_CLEANUP_FUNC(UidRange*, uid_range_free); int uid_range_add_internal(UidRange **range, uid_t start, uid_t nr, bool coalesce); static inline int uid_range_add(UidRange **range, uid_t start, uid_t nr) { return uid_range_add_internal(range, start, nr, true); } int uid_range_add_str(UidRange **range, const char *s); int uid_range_next_lower(const UidRange *range, uid_t *uid); bool uid_range_covers(const UidRange *range, uid_t start, uid_t nr); static inline bool uid_range_contains(const UidRange *range, uid_t uid) { return uid_range_covers(range, uid, 1); } int uid_range_load_userns(UidRange **ret, const char *path);
997
27.514286
83
h
null
systemd-main/src/basic/umask-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <sys/stat.h> #include <sys/types.h> #include "macro.h" static inline void umaskp(mode_t *u) { umask(*u & 0777); } #define _cleanup_umask_ _cleanup_(umaskp) /* We make use of the fact here that the umask() concept is using only the lower 9 bits of mode_t, although * mode_t has space for the file type in the bits further up. We simply OR in the file type mask S_IFMT to * distinguish the first and the second iteration of the WITH_UMASK() loop, so that we can run the first one, * and exit on the second. */ assert_cc((S_IFMT & 0777) == 0); #define WITH_UMASK(mask) \ for (_cleanup_umask_ mode_t _saved_umask_ = umask(mask) | S_IFMT; \ FLAGS_SET(_saved_umask_, S_IFMT); \ _saved_umask_ &= 0777) #define BLOCK_WITH_UMASK(mask) \ _unused_ _cleanup_umask_ mode_t _saved_umask_ = umask(mask);
1,010
32.7
109
h
null
systemd-main/src/basic/unaligned.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <endian.h> #include <stdint.h> #include "unaligned-fundamental.h" /* BE */ static inline uint16_t unaligned_read_be16(const void *_u) { const struct __attribute__((__packed__, __may_alias__)) { uint16_t x; } *u = _u; return be16toh(u->x); } static inline uint32_t unaligned_read_be32(const void *_u) { const struct __attribute__((__packed__, __may_alias__)) { uint32_t x; } *u = _u; return be32toh(u->x); } static inline uint64_t unaligned_read_be64(const void *_u) { const struct __attribute__((__packed__, __may_alias__)) { uint64_t x; } *u = _u; return be64toh(u->x); } static inline void unaligned_write_be16(void *_u, uint16_t a) { struct __attribute__((__packed__, __may_alias__)) { uint16_t x; } *u = _u; u->x = be16toh(a); } static inline void unaligned_write_be32(void *_u, uint32_t a) { struct __attribute__((__packed__, __may_alias__)) { uint32_t x; } *u = _u; u->x = be32toh(a); } static inline void unaligned_write_be64(void *_u, uint64_t a) { struct __attribute__((__packed__, __may_alias__)) { uint64_t x; } *u = _u; u->x = be64toh(a); } /* LE */ static inline uint16_t unaligned_read_le16(const void *_u) { const struct __attribute__((__packed__, __may_alias__)) { uint16_t x; } *u = _u; return le16toh(u->x); } static inline uint32_t unaligned_read_le32(const void *_u) { const struct __attribute__((__packed__, __may_alias__)) { uint32_t x; } *u = _u; return le32toh(u->x); } static inline uint64_t unaligned_read_le64(const void *_u) { const struct __attribute__((__packed__, __may_alias__)) { uint64_t x; } *u = _u; return le64toh(u->x); } static inline void unaligned_write_le16(void *_u, uint16_t a) { struct __attribute__((__packed__, __may_alias__)) { uint16_t x; } *u = _u; u->x = le16toh(a); } static inline void unaligned_write_le32(void *_u, uint32_t a) { struct __attribute__((__packed__, __may_alias__)) { uint32_t x; } *u = _u; u->x = le32toh(a); } static inline void unaligned_write_le64(void *_u, uint64_t a) { struct __attribute__((__packed__, __may_alias__)) { uint64_t x; } *u = _u; u->x = le64toh(a); }
2,331
26.761905
88
h
null
systemd-main/src/basic/unit-def.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "bus-label.h" #include "string-table.h" #include "unit-def.h" #include "unit-name.h" char *unit_dbus_path_from_name(const char *name) { _cleanup_free_ char *e = NULL; assert(name); e = bus_label_escape(name); if (!e) return NULL; return strjoin("/org/freedesktop/systemd1/unit/", e); } int unit_name_from_dbus_path(const char *path, char **name) { const char *e; char *n; e = startswith(path, "/org/freedesktop/systemd1/unit/"); if (!e) return -EINVAL; n = bus_label_unescape(e); if (!n) return -ENOMEM; *name = n; return 0; } const char* unit_dbus_interface_from_type(UnitType t) { static const char *const table[_UNIT_TYPE_MAX] = { [UNIT_SERVICE] = "org.freedesktop.systemd1.Service", [UNIT_SOCKET] = "org.freedesktop.systemd1.Socket", [UNIT_TARGET] = "org.freedesktop.systemd1.Target", [UNIT_DEVICE] = "org.freedesktop.systemd1.Device", [UNIT_MOUNT] = "org.freedesktop.systemd1.Mount", [UNIT_AUTOMOUNT] = "org.freedesktop.systemd1.Automount", [UNIT_SWAP] = "org.freedesktop.systemd1.Swap", [UNIT_TIMER] = "org.freedesktop.systemd1.Timer", [UNIT_PATH] = "org.freedesktop.systemd1.Path", [UNIT_SLICE] = "org.freedesktop.systemd1.Slice", [UNIT_SCOPE] = "org.freedesktop.systemd1.Scope", }; if (t < 0) return NULL; if (t >= _UNIT_TYPE_MAX) return NULL; return table[t]; } const char *unit_dbus_interface_from_name(const char *name) { UnitType t; t = unit_name_to_type(name); if (t < 0) return NULL; return unit_dbus_interface_from_type(t); } static const char* const unit_type_table[_UNIT_TYPE_MAX] = { [UNIT_SERVICE] = "service", [UNIT_SOCKET] = "socket", [UNIT_TARGET] = "target", [UNIT_DEVICE] = "device", [UNIT_MOUNT] = "mount", [UNIT_AUTOMOUNT] = "automount", [UNIT_SWAP] = "swap", [UNIT_TIMER] = "timer", [UNIT_PATH] = "path", [UNIT_SLICE] = "slice", [UNIT_SCOPE] = "scope", }; DEFINE_STRING_TABLE_LOOKUP(unit_type, UnitType); static const char* const unit_load_state_table[_UNIT_LOAD_STATE_MAX] = { [UNIT_STUB] = "stub", [UNIT_LOADED] = "loaded", [UNIT_NOT_FOUND] = "not-found", [UNIT_BAD_SETTING] = "bad-setting", [UNIT_ERROR] = "error", [UNIT_MERGED] = "merged", [UNIT_MASKED] = "masked" }; DEFINE_STRING_TABLE_LOOKUP(unit_load_state, UnitLoadState); static const char* const unit_active_state_table[_UNIT_ACTIVE_STATE_MAX] = { [UNIT_ACTIVE] = "active", [UNIT_RELOADING] = "reloading", [UNIT_INACTIVE] = "inactive", [UNIT_FAILED] = "failed", [UNIT_ACTIVATING] = "activating", [UNIT_DEACTIVATING] = "deactivating", [UNIT_MAINTENANCE] = "maintenance", }; DEFINE_STRING_TABLE_LOOKUP(unit_active_state, UnitActiveState); static const char* const freezer_state_table[_FREEZER_STATE_MAX] = { [FREEZER_RUNNING] = "running", [FREEZER_FREEZING] = "freezing", [FREEZER_FROZEN] = "frozen", [FREEZER_THAWING] = "thawing", }; DEFINE_STRING_TABLE_LOOKUP(freezer_state, FreezerState); static const char* const unit_marker_table[_UNIT_MARKER_MAX] = { [UNIT_MARKER_NEEDS_RELOAD] = "needs-reload", [UNIT_MARKER_NEEDS_RESTART] = "needs-restart", }; DEFINE_STRING_TABLE_LOOKUP(unit_marker, UnitMarker); static const char* const automount_state_table[_AUTOMOUNT_STATE_MAX] = { [AUTOMOUNT_DEAD] = "dead", [AUTOMOUNT_WAITING] = "waiting", [AUTOMOUNT_RUNNING] = "running", [AUTOMOUNT_FAILED] = "failed" }; DEFINE_STRING_TABLE_LOOKUP(automount_state, AutomountState); static const char* const device_state_table[_DEVICE_STATE_MAX] = { [DEVICE_DEAD] = "dead", [DEVICE_TENTATIVE] = "tentative", [DEVICE_PLUGGED] = "plugged", }; DEFINE_STRING_TABLE_LOOKUP(device_state, DeviceState); static const char* const mount_state_table[_MOUNT_STATE_MAX] = { [MOUNT_DEAD] = "dead", [MOUNT_MOUNTING] = "mounting", [MOUNT_MOUNTING_DONE] = "mounting-done", [MOUNT_MOUNTED] = "mounted", [MOUNT_REMOUNTING] = "remounting", [MOUNT_UNMOUNTING] = "unmounting", [MOUNT_REMOUNTING_SIGTERM] = "remounting-sigterm", [MOUNT_REMOUNTING_SIGKILL] = "remounting-sigkill", [MOUNT_UNMOUNTING_SIGTERM] = "unmounting-sigterm", [MOUNT_UNMOUNTING_SIGKILL] = "unmounting-sigkill", [MOUNT_UNMOUNTING_CATCHUP] = "unmounting-catchup", [MOUNT_FAILED] = "failed", [MOUNT_CLEANING] = "cleaning", }; DEFINE_STRING_TABLE_LOOKUP(mount_state, MountState); static const char* const path_state_table[_PATH_STATE_MAX] = { [PATH_DEAD] = "dead", [PATH_WAITING] = "waiting", [PATH_RUNNING] = "running", [PATH_FAILED] = "failed" }; DEFINE_STRING_TABLE_LOOKUP(path_state, PathState); static const char* const scope_state_table[_SCOPE_STATE_MAX] = { [SCOPE_DEAD] = "dead", [SCOPE_START_CHOWN] = "start-chown", [SCOPE_RUNNING] = "running", [SCOPE_ABANDONED] = "abandoned", [SCOPE_STOP_SIGTERM] = "stop-sigterm", [SCOPE_STOP_SIGKILL] = "stop-sigkill", [SCOPE_FAILED] = "failed", }; DEFINE_STRING_TABLE_LOOKUP(scope_state, ScopeState); static const char* const service_state_table[_SERVICE_STATE_MAX] = { [SERVICE_DEAD] = "dead", [SERVICE_CONDITION] = "condition", [SERVICE_START_PRE] = "start-pre", [SERVICE_START] = "start", [SERVICE_START_POST] = "start-post", [SERVICE_RUNNING] = "running", [SERVICE_EXITED] = "exited", [SERVICE_RELOAD] = "reload", [SERVICE_RELOAD_SIGNAL] = "reload-signal", [SERVICE_RELOAD_NOTIFY] = "reload-notify", [SERVICE_STOP] = "stop", [SERVICE_STOP_WATCHDOG] = "stop-watchdog", [SERVICE_STOP_SIGTERM] = "stop-sigterm", [SERVICE_STOP_SIGKILL] = "stop-sigkill", [SERVICE_STOP_POST] = "stop-post", [SERVICE_FINAL_WATCHDOG] = "final-watchdog", [SERVICE_FINAL_SIGTERM] = "final-sigterm", [SERVICE_FINAL_SIGKILL] = "final-sigkill", [SERVICE_FAILED] = "failed", [SERVICE_DEAD_BEFORE_AUTO_RESTART] = "dead-before-auto-restart", [SERVICE_FAILED_BEFORE_AUTO_RESTART] = "failed-before-auto-restart", [SERVICE_DEAD_RESOURCES_PINNED] = "dead-resources-pinned", [SERVICE_AUTO_RESTART] = "auto-restart", [SERVICE_AUTO_RESTART_QUEUED] = "auto-restart-queued", [SERVICE_CLEANING] = "cleaning", }; DEFINE_STRING_TABLE_LOOKUP(service_state, ServiceState); static const char* const slice_state_table[_SLICE_STATE_MAX] = { [SLICE_DEAD] = "dead", [SLICE_ACTIVE] = "active" }; DEFINE_STRING_TABLE_LOOKUP(slice_state, SliceState); static const char* const socket_state_table[_SOCKET_STATE_MAX] = { [SOCKET_DEAD] = "dead", [SOCKET_START_PRE] = "start-pre", [SOCKET_START_CHOWN] = "start-chown", [SOCKET_START_POST] = "start-post", [SOCKET_LISTENING] = "listening", [SOCKET_RUNNING] = "running", [SOCKET_STOP_PRE] = "stop-pre", [SOCKET_STOP_PRE_SIGTERM] = "stop-pre-sigterm", [SOCKET_STOP_PRE_SIGKILL] = "stop-pre-sigkill", [SOCKET_STOP_POST] = "stop-post", [SOCKET_FINAL_SIGTERM] = "final-sigterm", [SOCKET_FINAL_SIGKILL] = "final-sigkill", [SOCKET_FAILED] = "failed", [SOCKET_CLEANING] = "cleaning", }; DEFINE_STRING_TABLE_LOOKUP(socket_state, SocketState); static const char* const swap_state_table[_SWAP_STATE_MAX] = { [SWAP_DEAD] = "dead", [SWAP_ACTIVATING] = "activating", [SWAP_ACTIVATING_DONE] = "activating-done", [SWAP_ACTIVE] = "active", [SWAP_DEACTIVATING] = "deactivating", [SWAP_DEACTIVATING_SIGTERM] = "deactivating-sigterm", [SWAP_DEACTIVATING_SIGKILL] = "deactivating-sigkill", [SWAP_FAILED] = "failed", [SWAP_CLEANING] = "cleaning", }; DEFINE_STRING_TABLE_LOOKUP(swap_state, SwapState); static const char* const target_state_table[_TARGET_STATE_MAX] = { [TARGET_DEAD] = "dead", [TARGET_ACTIVE] = "active" }; DEFINE_STRING_TABLE_LOOKUP(target_state, TargetState); static const char* const timer_state_table[_TIMER_STATE_MAX] = { [TIMER_DEAD] = "dead", [TIMER_WAITING] = "waiting", [TIMER_RUNNING] = "running", [TIMER_ELAPSED] = "elapsed", [TIMER_FAILED] = "failed" }; DEFINE_STRING_TABLE_LOOKUP(timer_state, TimerState); static const char* const unit_dependency_table[_UNIT_DEPENDENCY_MAX] = { [UNIT_REQUIRES] = "Requires", [UNIT_REQUISITE] = "Requisite", [UNIT_WANTS] = "Wants", [UNIT_BINDS_TO] = "BindsTo", [UNIT_PART_OF] = "PartOf", [UNIT_UPHOLDS] = "Upholds", [UNIT_REQUIRED_BY] = "RequiredBy", [UNIT_REQUISITE_OF] = "RequisiteOf", [UNIT_WANTED_BY] = "WantedBy", [UNIT_BOUND_BY] = "BoundBy", [UNIT_UPHELD_BY] = "UpheldBy", [UNIT_CONSISTS_OF] = "ConsistsOf", [UNIT_CONFLICTS] = "Conflicts", [UNIT_CONFLICTED_BY] = "ConflictedBy", [UNIT_BEFORE] = "Before", [UNIT_AFTER] = "After", [UNIT_ON_SUCCESS] = "OnSuccess", [UNIT_ON_SUCCESS_OF] = "OnSuccessOf", [UNIT_ON_FAILURE] = "OnFailure", [UNIT_ON_FAILURE_OF] = "OnFailureOf", [UNIT_TRIGGERS] = "Triggers", [UNIT_TRIGGERED_BY] = "TriggeredBy", [UNIT_PROPAGATES_RELOAD_TO] = "PropagatesReloadTo", [UNIT_RELOAD_PROPAGATED_FROM] = "ReloadPropagatedFrom", [UNIT_PROPAGATES_STOP_TO] = "PropagatesStopTo", [UNIT_STOP_PROPAGATED_FROM] = "StopPropagatedFrom", [UNIT_JOINS_NAMESPACE_OF] = "JoinsNamespaceOf", [UNIT_REFERENCES] = "References", [UNIT_REFERENCED_BY] = "ReferencedBy", [UNIT_IN_SLICE] = "InSlice", [UNIT_SLICE_OF] = "SliceOf", }; DEFINE_STRING_TABLE_LOOKUP(unit_dependency, UnitDependency); static const char* const notify_access_table[_NOTIFY_ACCESS_MAX] = { [NOTIFY_NONE] = "none", [NOTIFY_MAIN] = "main", [NOTIFY_EXEC] = "exec", [NOTIFY_ALL] = "all" }; DEFINE_STRING_TABLE_LOOKUP(notify_access, NotifyAccess); SpecialGlyph unit_active_state_to_glyph(UnitActiveState state) { static const SpecialGlyph map[_UNIT_ACTIVE_STATE_MAX] = { [UNIT_ACTIVE] = SPECIAL_GLYPH_BLACK_CIRCLE, [UNIT_RELOADING] = SPECIAL_GLYPH_CIRCLE_ARROW, [UNIT_INACTIVE] = SPECIAL_GLYPH_WHITE_CIRCLE, [UNIT_FAILED] = SPECIAL_GLYPH_MULTIPLICATION_SIGN, [UNIT_ACTIVATING] = SPECIAL_GLYPH_BLACK_CIRCLE, [UNIT_DEACTIVATING] = SPECIAL_GLYPH_BLACK_CIRCLE, [UNIT_MAINTENANCE] = SPECIAL_GLYPH_WHITE_CIRCLE, }; if (state < 0) return _SPECIAL_GLYPH_INVALID; assert(state < _UNIT_ACTIVE_STATE_MAX); return map[state]; }
12,608
36.978916
76
c
null
systemd-main/src/basic/unit-def.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "errno-list.h" #include "glyph-util.h" #include "macro.h" /* The enum order is used to order unit jobs in the job queue * when other criteria (cpu weight, nice level) are identical. * In this case service units have the highest priority. */ typedef enum UnitType { UNIT_SERVICE, UNIT_MOUNT, UNIT_SWAP, UNIT_SOCKET, UNIT_TARGET, UNIT_DEVICE, UNIT_AUTOMOUNT, UNIT_TIMER, UNIT_PATH, UNIT_SLICE, UNIT_SCOPE, _UNIT_TYPE_MAX, _UNIT_TYPE_INVALID = -EINVAL, _UNIT_TYPE_ERRNO_MAX = -ERRNO_MAX, /* Ensure the whole errno range fits into this enum */ } UnitType; typedef enum UnitLoadState { UNIT_STUB, UNIT_LOADED, UNIT_NOT_FOUND, /* error condition #1: unit file not found */ UNIT_BAD_SETTING, /* error condition #2: we couldn't parse some essential unit file setting */ UNIT_ERROR, /* error condition #3: other "system" error, catchall for the rest */ UNIT_MERGED, UNIT_MASKED, _UNIT_LOAD_STATE_MAX, _UNIT_LOAD_STATE_INVALID = -EINVAL, } UnitLoadState; typedef enum UnitActiveState { UNIT_ACTIVE, UNIT_RELOADING, UNIT_INACTIVE, UNIT_FAILED, UNIT_ACTIVATING, UNIT_DEACTIVATING, UNIT_MAINTENANCE, _UNIT_ACTIVE_STATE_MAX, _UNIT_ACTIVE_STATE_INVALID = -EINVAL, } UnitActiveState; typedef enum FreezerState { FREEZER_RUNNING, FREEZER_FREEZING, FREEZER_FROZEN, FREEZER_THAWING, _FREEZER_STATE_MAX, _FREEZER_STATE_INVALID = -EINVAL, } FreezerState; typedef enum UnitMarker { UNIT_MARKER_NEEDS_RELOAD, UNIT_MARKER_NEEDS_RESTART, _UNIT_MARKER_MAX, _UNIT_MARKER_INVALID = -EINVAL, } UnitMarker; typedef enum AutomountState { AUTOMOUNT_DEAD, AUTOMOUNT_WAITING, AUTOMOUNT_RUNNING, AUTOMOUNT_FAILED, _AUTOMOUNT_STATE_MAX, _AUTOMOUNT_STATE_INVALID = -EINVAL, } AutomountState; /* We simply watch devices, we cannot plug/unplug them. That * simplifies the state engine greatly */ typedef enum DeviceState { DEVICE_DEAD, DEVICE_TENTATIVE, /* mounted or swapped, but not (yet) announced by udev */ DEVICE_PLUGGED, /* announced by udev */ _DEVICE_STATE_MAX, _DEVICE_STATE_INVALID = -EINVAL, } DeviceState; typedef enum MountState { MOUNT_DEAD, MOUNT_MOUNTING, /* /usr/bin/mount is running, but the mount is not done yet. */ MOUNT_MOUNTING_DONE, /* /usr/bin/mount is running, and the mount is done. */ MOUNT_MOUNTED, MOUNT_REMOUNTING, MOUNT_UNMOUNTING, MOUNT_REMOUNTING_SIGTERM, MOUNT_REMOUNTING_SIGKILL, MOUNT_UNMOUNTING_SIGTERM, MOUNT_UNMOUNTING_SIGKILL, MOUNT_UNMOUNTING_CATCHUP, MOUNT_FAILED, MOUNT_CLEANING, _MOUNT_STATE_MAX, _MOUNT_STATE_INVALID = -EINVAL, } MountState; typedef enum PathState { PATH_DEAD, PATH_WAITING, PATH_RUNNING, PATH_FAILED, _PATH_STATE_MAX, _PATH_STATE_INVALID = -EINVAL, } PathState; typedef enum ScopeState { SCOPE_DEAD, SCOPE_START_CHOWN, SCOPE_RUNNING, SCOPE_ABANDONED, SCOPE_STOP_SIGTERM, SCOPE_STOP_SIGKILL, SCOPE_FAILED, _SCOPE_STATE_MAX, _SCOPE_STATE_INVALID = -EINVAL, } ScopeState; typedef enum ServiceState { SERVICE_DEAD, SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST, SERVICE_RUNNING, SERVICE_EXITED, /* Nothing is running anymore, but RemainAfterExit is true hence this is OK */ SERVICE_RELOAD, /* Reloading via ExecReload= */ SERVICE_RELOAD_SIGNAL, /* Reloading via SIGHUP requested */ SERVICE_RELOAD_NOTIFY, /* Waiting for READY=1 after RELOADING=1 notify */ SERVICE_STOP, /* No STOP_PRE state, instead just register multiple STOP executables */ SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST, SERVICE_FINAL_WATCHDOG, /* In case the STOP_POST executable needs to be aborted. */ SERVICE_FINAL_SIGTERM, /* In case the STOP_POST executable hangs, we shoot that down, too */ SERVICE_FINAL_SIGKILL, SERVICE_FAILED, SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_DEAD_RESOURCES_PINNED, /* Like SERVICE_DEAD, but with pinned resources */ SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED, SERVICE_CLEANING, _SERVICE_STATE_MAX, _SERVICE_STATE_INVALID = -EINVAL, } ServiceState; typedef enum SliceState { SLICE_DEAD, SLICE_ACTIVE, _SLICE_STATE_MAX, _SLICE_STATE_INVALID = -EINVAL, } SliceState; typedef enum SocketState { SOCKET_DEAD, SOCKET_START_PRE, SOCKET_START_CHOWN, SOCKET_START_POST, SOCKET_LISTENING, SOCKET_RUNNING, SOCKET_STOP_PRE, SOCKET_STOP_PRE_SIGTERM, SOCKET_STOP_PRE_SIGKILL, SOCKET_STOP_POST, SOCKET_FINAL_SIGTERM, SOCKET_FINAL_SIGKILL, SOCKET_FAILED, SOCKET_CLEANING, _SOCKET_STATE_MAX, _SOCKET_STATE_INVALID = -EINVAL, } SocketState; typedef enum SwapState { SWAP_DEAD, SWAP_ACTIVATING, /* /sbin/swapon is running, but the swap not yet enabled. */ SWAP_ACTIVATING_DONE, /* /sbin/swapon is running, and the swap is done. */ SWAP_ACTIVE, SWAP_DEACTIVATING, SWAP_DEACTIVATING_SIGTERM, SWAP_DEACTIVATING_SIGKILL, SWAP_FAILED, SWAP_CLEANING, _SWAP_STATE_MAX, _SWAP_STATE_INVALID = -EINVAL, } SwapState; typedef enum TargetState { TARGET_DEAD, TARGET_ACTIVE, _TARGET_STATE_MAX, _TARGET_STATE_INVALID = -EINVAL, } TargetState; typedef enum TimerState { TIMER_DEAD, TIMER_WAITING, TIMER_RUNNING, TIMER_ELAPSED, TIMER_FAILED, _TIMER_STATE_MAX, _TIMER_STATE_INVALID = -EINVAL, } TimerState; typedef enum UnitDependency { /* Positive dependencies */ UNIT_REQUIRES, UNIT_REQUISITE, UNIT_WANTS, UNIT_BINDS_TO, UNIT_PART_OF, UNIT_UPHOLDS, /* Inverse of the above */ UNIT_REQUIRED_BY, /* inverse of 'requires' is 'required_by' */ UNIT_REQUISITE_OF, /* inverse of 'requisite' is 'requisite_of' */ UNIT_WANTED_BY, /* inverse of 'wants' */ UNIT_BOUND_BY, /* inverse of 'binds_to' */ UNIT_CONSISTS_OF, /* inverse of 'part_of' */ UNIT_UPHELD_BY, /* inverse of 'uphold' */ /* Negative dependencies */ UNIT_CONFLICTS, /* inverse of 'conflicts' is 'conflicted_by' */ UNIT_CONFLICTED_BY, /* Order */ UNIT_BEFORE, /* inverse of 'before' is 'after' and vice versa */ UNIT_AFTER, /* OnSuccess= + OnFailure= */ UNIT_ON_SUCCESS, UNIT_ON_SUCCESS_OF, UNIT_ON_FAILURE, UNIT_ON_FAILURE_OF, /* Triggers (i.e. a socket triggers a service) */ UNIT_TRIGGERS, UNIT_TRIGGERED_BY, /* Propagate reloads */ UNIT_PROPAGATES_RELOAD_TO, UNIT_RELOAD_PROPAGATED_FROM, /* Propagate stops */ UNIT_PROPAGATES_STOP_TO, UNIT_STOP_PROPAGATED_FROM, /* Joins namespace of */ UNIT_JOINS_NAMESPACE_OF, /* Reference information for GC logic */ UNIT_REFERENCES, /* Inverse of 'references' is 'referenced_by' */ UNIT_REFERENCED_BY, /* Slice= */ UNIT_IN_SLICE, UNIT_SLICE_OF, _UNIT_DEPENDENCY_MAX, _UNIT_DEPENDENCY_INVALID = -EINVAL, } UnitDependency; typedef enum NotifyAccess { NOTIFY_NONE, NOTIFY_ALL, NOTIFY_MAIN, NOTIFY_EXEC, _NOTIFY_ACCESS_MAX, _NOTIFY_ACCESS_INVALID = -EINVAL, } NotifyAccess; char *unit_dbus_path_from_name(const char *name); int unit_name_from_dbus_path(const char *path, char **name); const char* unit_dbus_interface_from_type(UnitType t); const char *unit_dbus_interface_from_name(const char *name); const char *unit_type_to_string(UnitType i) _const_; UnitType unit_type_from_string(const char *s) _pure_; const char *unit_load_state_to_string(UnitLoadState i) _const_; UnitLoadState unit_load_state_from_string(const char *s) _pure_; const char *unit_active_state_to_string(UnitActiveState i) _const_; UnitActiveState unit_active_state_from_string(const char *s) _pure_; const char *freezer_state_to_string(FreezerState i) _const_; FreezerState freezer_state_from_string(const char *s) _pure_; const char *unit_marker_to_string(UnitMarker m) _const_; UnitMarker unit_marker_from_string(const char *s) _pure_; const char* automount_state_to_string(AutomountState i) _const_; AutomountState automount_state_from_string(const char *s) _pure_; const char* device_state_to_string(DeviceState i) _const_; DeviceState device_state_from_string(const char *s) _pure_; const char* mount_state_to_string(MountState i) _const_; MountState mount_state_from_string(const char *s) _pure_; const char* path_state_to_string(PathState i) _const_; PathState path_state_from_string(const char *s) _pure_; const char* scope_state_to_string(ScopeState i) _const_; ScopeState scope_state_from_string(const char *s) _pure_; const char* service_state_to_string(ServiceState i) _const_; ServiceState service_state_from_string(const char *s) _pure_; const char* slice_state_to_string(SliceState i) _const_; SliceState slice_state_from_string(const char *s) _pure_; const char* socket_state_to_string(SocketState i) _const_; SocketState socket_state_from_string(const char *s) _pure_; const char* swap_state_to_string(SwapState i) _const_; SwapState swap_state_from_string(const char *s) _pure_; const char* target_state_to_string(TargetState i) _const_; TargetState target_state_from_string(const char *s) _pure_; const char *timer_state_to_string(TimerState i) _const_; TimerState timer_state_from_string(const char *s) _pure_; const char *unit_dependency_to_string(UnitDependency i) _const_; UnitDependency unit_dependency_from_string(const char *s) _pure_; const char* notify_access_to_string(NotifyAccess i) _const_; NotifyAccess notify_access_from_string(const char *s) _pure_; SpecialGlyph unit_active_state_to_glyph(UnitActiveState state);
10,909
30.80758
113
h
null
systemd-main/src/basic/unit-file.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "hashmap.h" #include "path-lookup.h" #include "time-util.h" #include "unit-name.h" typedef enum UnitFileState UnitFileState; enum UnitFileState { UNIT_FILE_ENABLED, UNIT_FILE_ENABLED_RUNTIME, UNIT_FILE_LINKED, UNIT_FILE_LINKED_RUNTIME, UNIT_FILE_ALIAS, UNIT_FILE_MASKED, UNIT_FILE_MASKED_RUNTIME, UNIT_FILE_STATIC, UNIT_FILE_DISABLED, UNIT_FILE_INDIRECT, UNIT_FILE_GENERATED, UNIT_FILE_TRANSIENT, UNIT_FILE_BAD, _UNIT_FILE_STATE_MAX, _UNIT_FILE_STATE_INVALID = -EINVAL, }; bool unit_type_may_alias(UnitType type) _const_; bool unit_type_may_template(UnitType type) _const_; int unit_symlink_name_compatible(const char *symlink, const char *target, bool instance_propagation); int unit_validate_alias_symlink_or_warn(int log_level, const char *filename, const char *target); bool lookup_paths_timestamp_hash_same(const LookupPaths *lp, uint64_t timestamp_hash, uint64_t *ret_new); int unit_file_resolve_symlink( const char *root_dir, char **search_path, const char *dir, int dirfd, const char *filename, bool resolve_destination_target, char **ret_destination); int unit_file_build_name_map( const LookupPaths *lp, uint64_t *cache_timestamp_hash, Hashmap **unit_ids_map, Hashmap **unit_names_map, Set **path_cache); int unit_file_find_fragment( Hashmap *unit_ids_map, Hashmap *unit_name_map, const char *unit_name, const char **ret_fragment_path, Set **ret_names); const char* runlevel_to_target(const char *rl);
1,907
29.285714
105
h
null
systemd-main/src/basic/unit-name.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <stddef.h> #include <stdint.h> #include <stdlib.h> #include "sd-id128.h" #include "alloc-util.h" #include "glob-util.h" #include "hexdecoct.h" #include "memory-util.h" #include "path-util.h" #include "random-util.h" #include "sparse-endian.h" #include "special.h" #include "stdio-util.h" #include "string-util.h" #include "strv.h" #include "unit-name.h" /* Characters valid in a unit name. */ #define VALID_CHARS \ DIGITS \ LETTERS \ ":-_.\\" /* The same, but also permits the single @ character that may appear */ #define VALID_CHARS_WITH_AT \ "@" \ VALID_CHARS /* All chars valid in a unit name glob */ #define VALID_CHARS_GLOB \ VALID_CHARS_WITH_AT \ "[]!-*?" #define LONG_UNIT_NAME_HASH_KEY SD_ID128_MAKE(ec,f2,37,fb,58,32,4a,32,84,9f,06,9b,0d,21,eb,9a) #define UNIT_NAME_HASH_LENGTH_CHARS 16 bool unit_name_is_valid(const char *n, UnitNameFlags flags) { const char *e, *i, *at; assert((flags & ~(UNIT_NAME_PLAIN|UNIT_NAME_INSTANCE|UNIT_NAME_TEMPLATE)) == 0); if (_unlikely_(flags == 0)) return false; if (isempty(n)) return false; if (strlen(n) >= UNIT_NAME_MAX) return false; e = strrchr(n, '.'); if (!e || e == n) return false; if (unit_type_from_string(e + 1) < 0) return false; for (i = n, at = NULL; i < e; i++) { if (*i == '@' && !at) at = i; if (!strchr(VALID_CHARS_WITH_AT, *i)) return false; } if (at == n) return false; if (flags & UNIT_NAME_PLAIN) if (!at) return true; if (flags & UNIT_NAME_INSTANCE) if (at && e > at + 1) return true; if (flags & UNIT_NAME_TEMPLATE) if (at && e == at + 1) return true; return false; } bool unit_prefix_is_valid(const char *p) { /* We don't allow additional @ in the prefix string */ if (isempty(p)) return false; return in_charset(p, VALID_CHARS); } bool unit_instance_is_valid(const char *i) { /* The max length depends on the length of the string, so we * don't really check this here. */ if (isempty(i)) return false; /* We allow additional @ in the instance string, we do not * allow them in the prefix! */ return in_charset(i, "@" VALID_CHARS); } bool unit_suffix_is_valid(const char *s) { if (isempty(s)) return false; if (s[0] != '.') return false; if (unit_type_from_string(s + 1) < 0) return false; return true; } int unit_name_to_prefix(const char *n, char **ret) { const char *p; char *s; assert(n); assert(ret); if (!unit_name_is_valid(n, UNIT_NAME_ANY)) return -EINVAL; p = strchr(n, '@'); if (!p) p = strrchr(n, '.'); assert_se(p); s = strndup(n, p - n); if (!s) return -ENOMEM; *ret = s; return 0; } UnitNameFlags unit_name_to_instance(const char *n, char **ret) { const char *p, *d; assert(n); if (!unit_name_is_valid(n, UNIT_NAME_ANY)) return -EINVAL; /* Everything past the first @ and before the last . is the instance */ p = strchr(n, '@'); if (!p) { if (ret) *ret = NULL; return UNIT_NAME_PLAIN; } p++; d = strrchr(p, '.'); if (!d) return -EINVAL; if (ret) { char *i = strndup(p, d-p); if (!i) return -ENOMEM; *ret = i; } return d > p ? UNIT_NAME_INSTANCE : UNIT_NAME_TEMPLATE; } int unit_name_to_prefix_and_instance(const char *n, char **ret) { const char *d; char *s; assert(n); assert(ret); if (!unit_name_is_valid(n, UNIT_NAME_ANY)) return -EINVAL; d = strrchr(n, '.'); if (!d) return -EINVAL; s = strndup(n, d - n); if (!s) return -ENOMEM; *ret = s; return 0; } UnitType unit_name_to_type(const char *n) { const char *e; assert(n); if (!unit_name_is_valid(n, UNIT_NAME_ANY)) return _UNIT_TYPE_INVALID; assert_se(e = strrchr(n, '.')); return unit_type_from_string(e + 1); } int unit_name_change_suffix(const char *n, const char *suffix, char **ret) { _cleanup_free_ char *s = NULL; size_t a, b; char *e; assert(n); assert(suffix); assert(ret); if (!unit_name_is_valid(n, UNIT_NAME_ANY)) return -EINVAL; if (!unit_suffix_is_valid(suffix)) return -EINVAL; assert_se(e = strrchr(n, '.')); a = e - n; b = strlen(suffix); s = new(char, a + b + 1); if (!s) return -ENOMEM; strcpy(mempcpy(s, n, a), suffix); /* Make sure the name is still valid (i.e. didn't grow too large due to longer suffix) */ if (!unit_name_is_valid(s, UNIT_NAME_ANY)) return -EINVAL; *ret = TAKE_PTR(s); return 0; } int unit_name_build(const char *prefix, const char *instance, const char *suffix, char **ret) { UnitType type; assert(prefix); assert(suffix); assert(ret); if (suffix[0] != '.') return -EINVAL; type = unit_type_from_string(suffix + 1); if (type < 0) return type; return unit_name_build_from_type(prefix, instance, type, ret); } int unit_name_build_from_type(const char *prefix, const char *instance, UnitType type, char **ret) { _cleanup_free_ char *s = NULL; const char *ut; assert(prefix); assert(type >= 0); assert(type < _UNIT_TYPE_MAX); assert(ret); if (!unit_prefix_is_valid(prefix)) return -EINVAL; ut = unit_type_to_string(type); if (instance) { if (!unit_instance_is_valid(instance)) return -EINVAL; s = strjoin(prefix, "@", instance, ".", ut); } else s = strjoin(prefix, ".", ut); if (!s) return -ENOMEM; /* Verify that this didn't grow too large (or otherwise is invalid) */ if (!unit_name_is_valid(s, instance ? UNIT_NAME_INSTANCE : UNIT_NAME_PLAIN)) return -EINVAL; *ret = TAKE_PTR(s); return 0; } static char *do_escape_char(char c, char *t) { assert(t); *(t++) = '\\'; *(t++) = 'x'; *(t++) = hexchar(c >> 4); *(t++) = hexchar(c); return t; } static char *do_escape(const char *f, char *t) { assert(f); assert(t); /* do not create units with a leading '.', like for "/.dotdir" mount points */ if (*f == '.') { t = do_escape_char(*f, t); f++; } for (; *f; f++) { if (*f == '/') *(t++) = '-'; else if (IN_SET(*f, '-', '\\') || !strchr(VALID_CHARS, *f)) t = do_escape_char(*f, t); else *(t++) = *f; } return t; } char *unit_name_escape(const char *f) { char *r, *t; assert(f); r = new(char, strlen(f)*4+1); if (!r) return NULL; t = do_escape(f, r); *t = 0; return r; } int unit_name_unescape(const char *f, char **ret) { _cleanup_free_ char *r = NULL; char *t; assert(f); r = strdup(f); if (!r) return -ENOMEM; for (t = r; *f; f++) { if (*f == '-') *(t++) = '/'; else if (*f == '\\') { int a, b; if (f[1] != 'x') return -EINVAL; a = unhexchar(f[2]); if (a < 0) return -EINVAL; b = unhexchar(f[3]); if (b < 0) return -EINVAL; *(t++) = (char) (((uint8_t) a << 4U) | (uint8_t) b); f += 3; } else *(t++) = *f; } *t = 0; *ret = TAKE_PTR(r); return 0; } int unit_name_path_escape(const char *f, char **ret) { _cleanup_free_ char *p = NULL; char *s; assert(f); assert(ret); p = strdup(f); if (!p) return -ENOMEM; path_simplify(p); if (empty_or_root(p)) s = strdup("-"); else { if (!path_is_normalized(p)) return -EINVAL; /* Truncate trailing slashes and skip leading slashes */ delete_trailing_chars(p, "/"); s = unit_name_escape(skip_leading_chars(p, "/")); } if (!s) return -ENOMEM; *ret = s; return 0; } int unit_name_path_unescape(const char *f, char **ret) { _cleanup_free_ char *s = NULL; int r; assert(f); if (isempty(f)) return -EINVAL; if (streq(f, "-")) { s = strdup("/"); if (!s) return -ENOMEM; } else { _cleanup_free_ char *w = NULL; r = unit_name_unescape(f, &w); if (r < 0) return r; /* Don't accept trailing or leading slashes */ if (startswith(w, "/") || endswith(w, "/")) return -EINVAL; /* Prefix a slash again */ s = strjoin("/", w); if (!s) return -ENOMEM; if (!path_is_normalized(s)) return -EINVAL; } if (ret) *ret = TAKE_PTR(s); return 0; } int unit_name_replace_instance(const char *f, const char *i, char **ret) { _cleanup_free_ char *s = NULL; const char *p, *e; size_t a, b; assert(f); assert(i); assert(ret); if (!unit_name_is_valid(f, UNIT_NAME_INSTANCE|UNIT_NAME_TEMPLATE)) return -EINVAL; if (!unit_instance_is_valid(i)) return -EINVAL; assert_se(p = strchr(f, '@')); assert_se(e = strrchr(f, '.')); a = p - f; b = strlen(i); s = new(char, a + 1 + b + strlen(e) + 1); if (!s) return -ENOMEM; strcpy(mempcpy(mempcpy(s, f, a + 1), i, b), e); /* Make sure the resulting name still is valid, i.e. didn't grow too large */ if (!unit_name_is_valid(s, UNIT_NAME_INSTANCE)) return -EINVAL; *ret = TAKE_PTR(s); return 0; } int unit_name_template(const char *f, char **ret) { const char *p, *e; char *s; size_t a; assert(f); assert(ret); if (!unit_name_is_valid(f, UNIT_NAME_INSTANCE|UNIT_NAME_TEMPLATE)) return -EINVAL; assert_se(p = strchr(f, '@')); assert_se(e = strrchr(f, '.')); a = p - f; s = new(char, a + 1 + strlen(e) + 1); if (!s) return -ENOMEM; strcpy(mempcpy(s, f, a + 1), e); *ret = s; return 0; } bool unit_name_is_hashed(const char *name) { char *s; if (!unit_name_is_valid(name, UNIT_NAME_PLAIN)) return false; assert_se(s = strrchr(name, '.')); if (s - name < UNIT_NAME_HASH_LENGTH_CHARS + 1) return false; s -= UNIT_NAME_HASH_LENGTH_CHARS; if (s[-1] != '_') return false; for (size_t i = 0; i < UNIT_NAME_HASH_LENGTH_CHARS; i++) if (!strchr(LOWERCASE_HEXDIGITS, s[i])) return false; return true; } int unit_name_hash_long(const char *name, char **ret) { _cleanup_free_ char *n = NULL, *hash = NULL; char *suffix; le64_t h; size_t len; if (strlen(name) < UNIT_NAME_MAX) return -EMSGSIZE; suffix = strrchr(name, '.'); if (!suffix) return -EINVAL; if (unit_type_from_string(suffix+1) < 0) return -EINVAL; h = htole64(siphash24_string(name, LONG_UNIT_NAME_HASH_KEY.bytes)); hash = hexmem(&h, sizeof(h)); if (!hash) return -ENOMEM; assert_se(strlen(hash) == UNIT_NAME_HASH_LENGTH_CHARS); len = UNIT_NAME_MAX - 1 - strlen(suffix+1) - UNIT_NAME_HASH_LENGTH_CHARS - 2; assert(len > 0 && len < UNIT_NAME_MAX); n = strndup(name, len); if (!n) return -ENOMEM; if (!strextend(&n, "_", hash, suffix)) return -ENOMEM; assert_se(unit_name_is_valid(n, UNIT_NAME_PLAIN)); *ret = TAKE_PTR(n); return 0; } int unit_name_from_path(const char *path, const char *suffix, char **ret) { _cleanup_free_ char *p = NULL, *s = NULL; int r; assert(path); assert(suffix); assert(ret); if (!unit_suffix_is_valid(suffix)) return -EINVAL; r = unit_name_path_escape(path, &p); if (r < 0) return r; s = strjoin(p, suffix); if (!s) return -ENOMEM; if (strlen(s) >= UNIT_NAME_MAX) { _cleanup_free_ char *n = NULL; log_debug("Unit name \"%s\" too long, falling back to hashed unit name.", s); r = unit_name_hash_long(s, &n); if (r < 0) return r; free_and_replace(s, n); } /* Refuse if this for some other reason didn't result in a valid name */ if (!unit_name_is_valid(s, UNIT_NAME_PLAIN)) return -EINVAL; *ret = TAKE_PTR(s); return 0; } int unit_name_from_path_instance(const char *prefix, const char *path, const char *suffix, char **ret) { _cleanup_free_ char *p = NULL, *s = NULL; int r; assert(prefix); assert(path); assert(suffix); assert(ret); if (!unit_prefix_is_valid(prefix)) return -EINVAL; if (!unit_suffix_is_valid(suffix)) return -EINVAL; r = unit_name_path_escape(path, &p); if (r < 0) return r; s = strjoin(prefix, "@", p, suffix); if (!s) return -ENOMEM; if (strlen(s) >= UNIT_NAME_MAX) /* Return a slightly more descriptive error for this specific condition */ return -ENAMETOOLONG; /* Refuse if this for some other reason didn't result in a valid name */ if (!unit_name_is_valid(s, UNIT_NAME_INSTANCE)) return -EINVAL; *ret = TAKE_PTR(s); return 0; } int unit_name_to_path(const char *name, char **ret) { _cleanup_free_ char *prefix = NULL; int r; assert(name); r = unit_name_to_prefix(name, &prefix); if (r < 0) return r; if (unit_name_is_hashed(name)) return -ENAMETOOLONG; return unit_name_path_unescape(prefix, ret); } static bool do_escape_mangle(const char *f, bool allow_globs, char *t) { const char *valid_chars; bool mangled = false; assert(f); assert(t); /* We'll only escape the obvious characters here, to play safe. * * Returns true if any characters were mangled, false otherwise. */ valid_chars = allow_globs ? VALID_CHARS_GLOB : VALID_CHARS_WITH_AT; for (; *f; f++) if (*f == '/') { *(t++) = '-'; mangled = true; } else if (!strchr(valid_chars, *f)) { t = do_escape_char(*f, t); mangled = true; } else *(t++) = *f; *t = 0; return mangled; } /** * Convert a string to a unit name. /dev/blah is converted to dev-blah.device, * /blah/blah is converted to blah-blah.mount, anything else is left alone, * except that @suffix is appended if a valid unit suffix is not present. * * If @allow_globs, globs characters are preserved. Otherwise, they are escaped. */ int unit_name_mangle_with_suffix(const char *name, const char *operation, UnitNameMangle flags, const char *suffix, char **ret) { _cleanup_free_ char *s = NULL; bool mangled, suggest_escape = true; int r; assert(name); assert(suffix); assert(ret); if (isempty(name)) /* We cannot mangle empty unit names to become valid, sorry. */ return -EINVAL; if (!unit_suffix_is_valid(suffix)) return -EINVAL; /* Already a fully valid unit name? If so, no mangling is necessary... */ if (unit_name_is_valid(name, UNIT_NAME_ANY)) goto good; /* Already a fully valid globbing expression? If so, no mangling is necessary either... */ if (string_is_glob(name) && in_charset(name, VALID_CHARS_GLOB)) { if (flags & UNIT_NAME_MANGLE_GLOB) goto good; log_full(flags & UNIT_NAME_MANGLE_WARN ? LOG_NOTICE : LOG_DEBUG, "Glob pattern passed%s%s, but globs are not supported for this.", operation ? " " : "", strempty(operation)); suggest_escape = false; } if (is_device_path(name)) { r = unit_name_from_path(name, ".device", ret); if (r >= 0) return 1; if (r != -EINVAL) return r; } if (path_is_absolute(name)) { r = unit_name_from_path(name, ".mount", ret); if (r >= 0) return 1; if (r != -EINVAL) return r; } s = new(char, strlen(name) * 4 + strlen(suffix) + 1); if (!s) return -ENOMEM; mangled = do_escape_mangle(name, flags & UNIT_NAME_MANGLE_GLOB, s); if (mangled) log_full(flags & UNIT_NAME_MANGLE_WARN ? LOG_NOTICE : LOG_DEBUG, "Invalid unit name \"%s\" escaped as \"%s\"%s.", name, s, suggest_escape ? " (maybe you should use systemd-escape?)" : ""); /* Append a suffix if it doesn't have any, but only if this is not a glob, so that we can allow * "foo.*" as a valid glob. */ if ((!(flags & UNIT_NAME_MANGLE_GLOB) || !string_is_glob(s)) && unit_name_to_type(s) < 0) strcat(s, suffix); /* Make sure mangling didn't grow this too large (but don't do this check if globbing is allowed, * since globs generally do not qualify as valid unit names) */ if (!FLAGS_SET(flags, UNIT_NAME_MANGLE_GLOB) && !unit_name_is_valid(s, UNIT_NAME_ANY)) return -EINVAL; *ret = TAKE_PTR(s); return 1; good: s = strdup(name); if (!s) return -ENOMEM; *ret = TAKE_PTR(s); return 0; } int slice_build_parent_slice(const char *slice, char **ret) { _cleanup_free_ char *s = NULL; char *dash; int r; assert(slice); assert(ret); if (!slice_name_is_valid(slice)) return -EINVAL; if (streq(slice, SPECIAL_ROOT_SLICE)) { *ret = NULL; return 0; } s = strdup(slice); if (!s) return -ENOMEM; dash = strrchr(s, '-'); if (dash) strcpy(dash, ".slice"); else { r = free_and_strdup(&s, SPECIAL_ROOT_SLICE); if (r < 0) return r; } *ret = TAKE_PTR(s); return 1; } int slice_build_subslice(const char *slice, const char *name, char **ret) { char *subslice; assert(slice); assert(name); assert(ret); if (!slice_name_is_valid(slice)) return -EINVAL; if (!unit_prefix_is_valid(name)) return -EINVAL; if (streq(slice, SPECIAL_ROOT_SLICE)) subslice = strjoin(name, ".slice"); else { char *e; assert_se(e = endswith(slice, ".slice")); subslice = new(char, (e - slice) + 1 + strlen(name) + 6 + 1); if (!subslice) return -ENOMEM; stpcpy(stpcpy(stpcpy(mempcpy(subslice, slice, e - slice), "-"), name), ".slice"); } *ret = subslice; return 0; } bool slice_name_is_valid(const char *name) { const char *p, *e; bool dash = false; if (!unit_name_is_valid(name, UNIT_NAME_PLAIN)) return false; if (streq(name, SPECIAL_ROOT_SLICE)) return true; e = endswith(name, ".slice"); if (!e) return false; for (p = name; p < e; p++) { if (*p == '-') { /* Don't allow initial dash */ if (p == name) return false; /* Don't allow multiple dashes */ if (dash) return false; dash = true; } else dash = false; } /* Don't allow trailing hash */ if (dash) return false; return true; } bool unit_name_prefix_equal(const char *a, const char *b) { const char *p, *q; assert(a); assert(b); if (!unit_name_is_valid(a, UNIT_NAME_ANY) || !unit_name_is_valid(b, UNIT_NAME_ANY)) return false; p = strchr(a, '@'); if (!p) p = strrchr(a, '.'); q = strchr(b, '@'); if (!q) q = strrchr(b, '.'); assert(p); assert(q); return memcmp_nn(a, p - a, b, q - b) == 0; }
23,358
24.782561
129
c
null
systemd-main/src/basic/unit-name.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "macro.h" #include "unit-def.h" #define UNIT_NAME_MAX 256 typedef enum UnitNameFlags { UNIT_NAME_PLAIN = 1 << 0, /* Allow foo.service */ UNIT_NAME_TEMPLATE = 1 << 1, /* Allow [email protected] */ UNIT_NAME_INSTANCE = 1 << 2, /* Allow [email protected] */ UNIT_NAME_ANY = UNIT_NAME_PLAIN|UNIT_NAME_TEMPLATE|UNIT_NAME_INSTANCE, _UNIT_NAME_INVALID = -EINVAL, } UnitNameFlags; bool unit_name_is_valid(const char *n, UnitNameFlags flags) _pure_; bool unit_prefix_is_valid(const char *p) _pure_; bool unit_instance_is_valid(const char *i) _pure_; bool unit_suffix_is_valid(const char *s) _pure_; int unit_name_to_prefix(const char *n, char **ret); UnitNameFlags unit_name_to_instance(const char *n, char **ret); static inline UnitNameFlags unit_name_classify(const char *n) { return unit_name_to_instance(n, NULL); } int unit_name_to_prefix_and_instance(const char *n, char **ret); UnitType unit_name_to_type(const char *n) _pure_; int unit_name_change_suffix(const char *n, const char *suffix, char **ret); int unit_name_build(const char *prefix, const char *instance, const char *suffix, char **ret); int unit_name_build_from_type(const char *prefix, const char *instance, UnitType, char **ret); char *unit_name_escape(const char *f); int unit_name_unescape(const char *f, char **ret); int unit_name_path_escape(const char *f, char **ret); int unit_name_path_unescape(const char *f, char **ret); int unit_name_replace_instance(const char *f, const char *i, char **ret); int unit_name_template(const char *f, char **ret); int unit_name_hash_long(const char *name, char **ret); bool unit_name_is_hashed(const char *name); int unit_name_from_path(const char *path, const char *suffix, char **ret); int unit_name_from_path_instance(const char *prefix, const char *path, const char *suffix, char **ret); int unit_name_to_path(const char *name, char **ret); typedef enum UnitNameMangle { UNIT_NAME_MANGLE_GLOB = 1 << 0, UNIT_NAME_MANGLE_WARN = 1 << 1, } UnitNameMangle; int unit_name_mangle_with_suffix(const char *name, const char *operation, UnitNameMangle flags, const char *suffix, char **ret); static inline int unit_name_mangle(const char *name, UnitNameMangle flags, char **ret) { return unit_name_mangle_with_suffix(name, NULL, flags, ".service", ret); } int slice_build_parent_slice(const char *slice, char **ret); int slice_build_subslice(const char *slice, const char *name, char **subslice); bool slice_name_is_valid(const char *name); bool unit_name_prefix_equal(const char *a, const char *b);
2,676
37.242857
128
h
null
systemd-main/src/basic/utf8.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* Parts of this file are based on the GLIB utf8 validation functions. The * original license text follows. */ /* gutf8.c - Operations on UTF-8 strings. * * Copyright (C) 1999 Tom Tromey * Copyright (C) 2000 Red Hat, Inc. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ #include <errno.h> #include <stdbool.h> #include <stdlib.h> #include "alloc-util.h" #include "gunicode.h" #include "hexdecoct.h" #include "macro.h" #include "string-util.h" #include "utf8.h" bool unichar_is_valid(char32_t ch) { if (ch >= 0x110000) /* End of unicode space */ return false; if ((ch & 0xFFFFF800) == 0xD800) /* Reserved area for UTF-16 */ return false; if ((ch >= 0xFDD0) && (ch <= 0xFDEF)) /* Reserved */ return false; if ((ch & 0xFFFE) == 0xFFFE) /* BOM (Byte Order Mark) */ return false; return true; } static bool unichar_is_control(char32_t ch) { /* 0 to ' '-1 is the C0 range. DEL=0x7F, and DEL+1 to 0x9F is C1 range. '\t' is in C0 range, but more or less harmless and commonly used. */ return (ch < ' ' && !IN_SET(ch, '\t', '\n')) || (0x7F <= ch && ch <= 0x9F); } /* count of characters used to encode one unicode char */ static size_t utf8_encoded_expected_len(uint8_t c) { if (c < 0x80) return 1; if ((c & 0xe0) == 0xc0) return 2; if ((c & 0xf0) == 0xe0) return 3; if ((c & 0xf8) == 0xf0) return 4; if ((c & 0xfc) == 0xf8) return 5; if ((c & 0xfe) == 0xfc) return 6; return 0; } /* decode one unicode char */ int utf8_encoded_to_unichar(const char *str, char32_t *ret_unichar) { char32_t unichar; size_t len; assert(str); len = utf8_encoded_expected_len(str[0]); switch (len) { case 1: *ret_unichar = (char32_t)str[0]; return 1; case 2: unichar = str[0] & 0x1f; break; case 3: unichar = (char32_t)str[0] & 0x0f; break; case 4: unichar = (char32_t)str[0] & 0x07; break; case 5: unichar = (char32_t)str[0] & 0x03; break; case 6: unichar = (char32_t)str[0] & 0x01; break; default: return -EINVAL; } for (size_t i = 1; i < len; i++) { if (((char32_t)str[i] & 0xc0) != 0x80) return -EINVAL; unichar <<= 6; unichar |= (char32_t)str[i] & 0x3f; } *ret_unichar = unichar; return len; } bool utf8_is_printable_newline(const char* str, size_t length, bool allow_newline) { assert(str); for (const char *p = str; length > 0;) { int encoded_len; char32_t val; encoded_len = utf8_encoded_valid_unichar(p, length); if (encoded_len < 0) return false; assert(encoded_len > 0 && (size_t) encoded_len <= length); if (utf8_encoded_to_unichar(p, &val) < 0 || unichar_is_control(val) || (!allow_newline && val == '\n')) return false; length -= encoded_len; p += encoded_len; } return true; } char *utf8_is_valid_n(const char *str, size_t len_bytes) { /* Check if the string is composed of valid utf8 characters. If length len_bytes is given, stop after * len_bytes. Otherwise, stop at NUL. */ assert(str); for (const char *p = str; len_bytes != SIZE_MAX ? (size_t) (p - str) < len_bytes : *p != '\0'; ) { int len; if (_unlikely_(*p == '\0') && len_bytes != SIZE_MAX) return NULL; /* embedded NUL */ len = utf8_encoded_valid_unichar(p, len_bytes != SIZE_MAX ? len_bytes - (p - str) : SIZE_MAX); if (_unlikely_(len < 0)) return NULL; /* invalid character */ p += len; } return (char*) str; } char *utf8_escape_invalid(const char *str) { char *p, *s; assert(str); p = s = malloc(strlen(str) * 4 + 1); if (!p) return NULL; while (*str) { int len; len = utf8_encoded_valid_unichar(str, SIZE_MAX); if (len > 0) { s = mempcpy(s, str, len); str += len; } else { s = stpcpy(s, UTF8_REPLACEMENT_CHARACTER); str += 1; } } *s = '\0'; return str_realloc(p); } static int utf8_char_console_width(const char *str) { char32_t c; int r; r = utf8_encoded_to_unichar(str, &c); if (r < 0) return r; /* TODO: we should detect combining characters */ return unichar_iswide(c) ? 2 : 1; } char *utf8_escape_non_printable_full(const char *str, size_t console_width, bool force_ellipsis) { char *p, *s, *prev_s; size_t n = 0; /* estimated print width */ assert(str); if (console_width == 0) return strdup(""); p = s = prev_s = malloc(strlen(str) * 4 + 1); if (!p) return NULL; for (;;) { int len; char *saved_s = s; if (!*str) { /* done! */ if (force_ellipsis) goto truncation; else goto finish; } len = utf8_encoded_valid_unichar(str, SIZE_MAX); if (len > 0) { if (utf8_is_printable(str, len)) { int w; w = utf8_char_console_width(str); assert(w >= 0); if (n + w > console_width) goto truncation; s = mempcpy(s, str, len); str += len; n += w; } else { for (; len > 0; len--) { if (n + 4 > console_width) goto truncation; *(s++) = '\\'; *(s++) = 'x'; *(s++) = hexchar((int) *str >> 4); *(s++) = hexchar((int) *str); str += 1; n += 4; } } } else { if (n + 1 > console_width) goto truncation; s = mempcpy(s, UTF8_REPLACEMENT_CHARACTER, strlen(UTF8_REPLACEMENT_CHARACTER)); str += 1; n += 1; } prev_s = saved_s; } truncation: /* Try to go back one if we don't have enough space for the ellipsis */ if (n + 1 > console_width) s = prev_s; s = mempcpy(s, "…", strlen("…")); finish: *s = '\0'; return str_realloc(p); } char *ascii_is_valid(const char *str) { /* Check whether the string consists of valid ASCII bytes, * i.e values between 0 and 127, inclusive. */ assert(str); for (const char *p = str; *p; p++) if ((unsigned char) *p >= 128) return NULL; return (char*) str; } char *ascii_is_valid_n(const char *str, size_t len) { /* Very similar to ascii_is_valid(), but checks exactly len * bytes and rejects any NULs in that range. */ assert(str); for (size_t i = 0; i < len; i++) if ((unsigned char) str[i] >= 128 || str[i] == 0) return NULL; return (char*) str; } int utf8_to_ascii(const char *str, char replacement_char, char **ret) { /* Convert to a string that has only ASCII chars, replacing anything that is not ASCII * by replacement_char. */ _cleanup_free_ char *ans = new(char, strlen(str) + 1); if (!ans) return -ENOMEM; char *q = ans; for (const char *p = str; *p; q++) { int l; l = utf8_encoded_valid_unichar(p, SIZE_MAX); if (l < 0) /* Non-UTF-8, let's not even try to propagate the garbage */ return l; if (l == 1) *q = *p; else /* non-ASCII, we need to replace it */ *q = replacement_char; p += l; } *q = '\0'; *ret = TAKE_PTR(ans); return 0; } /** * utf8_encode_unichar() - Encode single UCS-4 character as UTF-8 * @out_utf8: output buffer of at least 4 bytes or NULL * @g: UCS-4 character to encode * * This encodes a single UCS-4 character as UTF-8 and writes it into @out_utf8. * The length of the character is returned. It is not zero-terminated! If the * output buffer is NULL, only the length is returned. * * Returns: The length in bytes that the UTF-8 representation does or would * occupy. */ size_t utf8_encode_unichar(char *out_utf8, char32_t g) { if (g < (1 << 7)) { if (out_utf8) out_utf8[0] = g & 0x7f; return 1; } else if (g < (1 << 11)) { if (out_utf8) { out_utf8[0] = 0xc0 | ((g >> 6) & 0x1f); out_utf8[1] = 0x80 | (g & 0x3f); } return 2; } else if (g < (1 << 16)) { if (out_utf8) { out_utf8[0] = 0xe0 | ((g >> 12) & 0x0f); out_utf8[1] = 0x80 | ((g >> 6) & 0x3f); out_utf8[2] = 0x80 | (g & 0x3f); } return 3; } else if (g < (1 << 21)) { if (out_utf8) { out_utf8[0] = 0xf0 | ((g >> 18) & 0x07); out_utf8[1] = 0x80 | ((g >> 12) & 0x3f); out_utf8[2] = 0x80 | ((g >> 6) & 0x3f); out_utf8[3] = 0x80 | (g & 0x3f); } return 4; } return 0; } char *utf16_to_utf8(const char16_t *s, size_t length /* bytes! */) { const uint8_t *f; char *r, *t; assert(s); /* Input length is in bytes, i.e. the shortest possible character takes 2 bytes. Each unicode character may * take up to 4 bytes in UTF-8. Let's also account for a trailing NUL byte. */ if (length * 2 < length) return NULL; /* overflow */ r = new(char, length * 2 + 1); if (!r) return NULL; f = (const uint8_t*) s; t = r; while (f + 1 < (const uint8_t*) s + length) { char16_t w1, w2; /* see RFC 2781 section 2.2 */ w1 = f[1] << 8 | f[0]; f += 2; if (!utf16_is_surrogate(w1)) { t += utf8_encode_unichar(t, w1); continue; } if (utf16_is_trailing_surrogate(w1)) continue; /* spurious trailing surrogate, ignore */ if (f + 1 >= (const uint8_t*) s + length) break; w2 = f[1] << 8 | f[0]; f += 2; if (!utf16_is_trailing_surrogate(w2)) { f -= 2; continue; /* surrogate missing its trailing surrogate, ignore */ } t += utf8_encode_unichar(t, utf16_surrogate_pair_to_unichar(w1, w2)); } *t = 0; return r; } size_t utf16_encode_unichar(char16_t *out, char32_t c) { /* Note that this encodes as little-endian. */ switch (c) { case 0 ... 0xd7ffU: case 0xe000U ... 0xffffU: out[0] = htole16(c); return 1; case 0x10000U ... 0x10ffffU: c -= 0x10000U; out[0] = htole16((c >> 10) + 0xd800U); out[1] = htole16((c & 0x3ffU) + 0xdc00U); return 2; default: /* A surrogate (invalid) */ return 0; } } char16_t *utf8_to_utf16(const char *s, size_t length) { char16_t *n, *p; int r; assert(s); n = new(char16_t, length + 1); if (!n) return NULL; p = n; for (size_t i = 0; i < length;) { char32_t unichar; size_t e; e = utf8_encoded_expected_len(s[i]); if (e <= 1) /* Invalid and single byte characters are copied as they are */ goto copy; if (i + e > length) /* sequence longer than input buffer, then copy as-is */ goto copy; r = utf8_encoded_to_unichar(s + i, &unichar); if (r < 0) /* sequence invalid, then copy as-is */ goto copy; p += utf16_encode_unichar(p, unichar); i += e; continue; copy: *(p++) = htole16(s[i++]); } *p = 0; return n; } size_t char16_strlen(const char16_t *s) { size_t n = 0; assert(s); while (*s != 0) n++, s++; return n; } /* expected size used to encode one unicode char */ static int utf8_unichar_to_encoded_len(char32_t unichar) { if (unichar < 0x80) return 1; if (unichar < 0x800) return 2; if (unichar < 0x10000) return 3; if (unichar < 0x200000) return 4; if (unichar < 0x4000000) return 5; return 6; } /* validate one encoded unicode char and return its length */ int utf8_encoded_valid_unichar(const char *str, size_t length /* bytes */) { char32_t unichar; size_t len; int r; assert(str); assert(length > 0); /* We read until NUL, at most length bytes. SIZE_MAX may be used to disable the length check. */ len = utf8_encoded_expected_len(str[0]); if (len == 0) return -EINVAL; /* Do we have a truncated multi-byte character? */ if (len > length) return -EINVAL; /* ascii is valid */ if (len == 1) return 1; /* check if expected encoded chars are available */ for (size_t i = 0; i < len; i++) if ((str[i] & 0x80) != 0x80) return -EINVAL; r = utf8_encoded_to_unichar(str, &unichar); if (r < 0) return r; /* check if encoded length matches encoded value */ if (utf8_unichar_to_encoded_len(unichar) != (int) len) return -EINVAL; /* check if value has valid range */ if (!unichar_is_valid(unichar)) return -EINVAL; return (int) len; } size_t utf8_n_codepoints(const char *str) { size_t n = 0; /* Returns the number of UTF-8 codepoints in this string, or SIZE_MAX if the string is not valid UTF-8. */ while (*str != 0) { int k; k = utf8_encoded_valid_unichar(str, SIZE_MAX); if (k < 0) return SIZE_MAX; str += k; n++; } return n; } size_t utf8_console_width(const char *str) { size_t n = 0; /* Returns the approximate width a string will take on screen when printed on a character cell * terminal/console. */ while (*str) { int w; w = utf8_char_console_width(str); if (w < 0) return SIZE_MAX; n += w; str = utf8_next_char(str); } return n; }
17,596
27.847541
115
c
null
systemd-main/src/basic/utf8.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include <uchar.h> #include "macro.h" #include "missing_type.h" #define UTF8_REPLACEMENT_CHARACTER "\xef\xbf\xbd" #define UTF8_BYTE_ORDER_MARK "\xef\xbb\xbf" bool unichar_is_valid(char32_t c); char *utf8_is_valid_n(const char *str, size_t len_bytes) _pure_; static inline char *utf8_is_valid(const char *s) { return utf8_is_valid_n(s, SIZE_MAX); } char *ascii_is_valid(const char *s) _pure_; char *ascii_is_valid_n(const char *str, size_t len); int utf8_to_ascii(const char *str, char replacement_char, char **ret); bool utf8_is_printable_newline(const char* str, size_t length, bool allow_newline) _pure_; #define utf8_is_printable(str, length) utf8_is_printable_newline(str, length, true) char *utf8_escape_invalid(const char *s); char *utf8_escape_non_printable_full(const char *str, size_t console_width, bool force_ellipsis); static inline char *utf8_escape_non_printable(const char *str) { return utf8_escape_non_printable_full(str, SIZE_MAX, false); } size_t utf8_encode_unichar(char *out_utf8, char32_t g); size_t utf16_encode_unichar(char16_t *out, char32_t c); char *utf16_to_utf8(const char16_t *s, size_t length /* bytes! */); char16_t *utf8_to_utf16(const char *s, size_t length); size_t char16_strlen(const char16_t *s); /* returns the number of 16-bit words in the string (not bytes!) */ int utf8_encoded_valid_unichar(const char *str, size_t length); int utf8_encoded_to_unichar(const char *str, char32_t *ret_unichar); static inline bool utf16_is_surrogate(char16_t c) { return c >= 0xd800U && c <= 0xdfffU; } static inline bool utf16_is_trailing_surrogate(char16_t c) { return c >= 0xdc00U && c <= 0xdfffU; } static inline char32_t utf16_surrogate_pair_to_unichar(char16_t lead, char16_t trail) { return ((((char32_t) lead - 0xd800U) << 10) + ((char32_t) trail - 0xdc00U) + 0x10000U); } size_t utf8_n_codepoints(const char *str); size_t utf8_console_width(const char *str);
2,071
33.533333
108
h
null
systemd-main/src/basic/virt.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include "errno-list.h" #include "macro.h" typedef enum Virtualization { VIRTUALIZATION_NONE = 0, VIRTUALIZATION_VM_FIRST, VIRTUALIZATION_KVM = VIRTUALIZATION_VM_FIRST, VIRTUALIZATION_AMAZON, VIRTUALIZATION_QEMU, VIRTUALIZATION_BOCHS, VIRTUALIZATION_XEN, VIRTUALIZATION_UML, VIRTUALIZATION_VMWARE, VIRTUALIZATION_ORACLE, VIRTUALIZATION_MICROSOFT, VIRTUALIZATION_ZVM, VIRTUALIZATION_PARALLELS, VIRTUALIZATION_BHYVE, VIRTUALIZATION_QNX, VIRTUALIZATION_ACRN, VIRTUALIZATION_POWERVM, VIRTUALIZATION_APPLE, VIRTUALIZATION_SRE, VIRTUALIZATION_VM_OTHER, VIRTUALIZATION_VM_LAST = VIRTUALIZATION_VM_OTHER, VIRTUALIZATION_CONTAINER_FIRST, VIRTUALIZATION_SYSTEMD_NSPAWN = VIRTUALIZATION_CONTAINER_FIRST, VIRTUALIZATION_LXC_LIBVIRT, VIRTUALIZATION_LXC, VIRTUALIZATION_OPENVZ, VIRTUALIZATION_DOCKER, VIRTUALIZATION_PODMAN, VIRTUALIZATION_RKT, VIRTUALIZATION_WSL, VIRTUALIZATION_PROOT, VIRTUALIZATION_POUCH, VIRTUALIZATION_CONTAINER_OTHER, VIRTUALIZATION_CONTAINER_LAST = VIRTUALIZATION_CONTAINER_OTHER, _VIRTUALIZATION_MAX, _VIRTUALIZATION_INVALID = -EINVAL, _VIRTUALIZATION_ERRNO_MAX = -ERRNO_MAX, /* ensure full range of errno fits into this enum */ } Virtualization; static inline bool VIRTUALIZATION_IS_VM(Virtualization x) { return x >= VIRTUALIZATION_VM_FIRST && x <= VIRTUALIZATION_VM_LAST; } static inline bool VIRTUALIZATION_IS_CONTAINER(Virtualization x) { return x >= VIRTUALIZATION_CONTAINER_FIRST && x <= VIRTUALIZATION_CONTAINER_LAST; } Virtualization detect_vm(void); Virtualization detect_container(void); Virtualization detect_virtualization(void); int running_in_userns(void); int running_in_chroot(void); const char *virtualization_to_string(Virtualization v) _const_; Virtualization virtualization_from_string(const char *s) _pure_; bool has_cpu_with_flag(const char *flag);
2,188
30.271429
100
h
null
systemd-main/src/basic/xattr-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <stdint.h> #include <stdlib.h> #include <sys/time.h> #include <sys/xattr.h> #include "alloc-util.h" #include "errno-util.h" #include "fd-util.h" #include "macro.h" #include "missing_syscall.h" #include "sparse-endian.h" #include "stat-util.h" #include "stdio-util.h" #include "string-util.h" #include "time-util.h" #include "xattr-util.h" int getxattr_at_malloc( int fd, const char *path, const char *name, int flags, char **ret) { _cleanup_close_ int opened_fd = -EBADF; unsigned n_attempts = 7; bool by_procfs = false; size_t l = 100; assert(fd >= 0 || fd == AT_FDCWD); assert(name); assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH)) == 0); assert(ret); /* So, this is single function that does what getxattr()/lgetxattr()/fgetxattr() does, but in one go, * and with additional bells and whistles. Specifically: * * 1. This works on O_PATH fds (which fgetxattr() does not) * 2. Provides full openat()-style semantics, i.e. by-fd, by-path and combination thereof * 3. As extension to openat()-style semantics implies AT_EMPTY_PATH if path is NULL. * 4. Does a malloc() loop, automatically sizing the allocation * 5. NUL-terminates the returned buffer (for safety) */ if (!path) /* If path is NULL, imply AT_EMPTY_PATH. – But if it's "", don't — for safety reasons. */ flags |= AT_EMPTY_PATH; if (isempty(path)) { if (!FLAGS_SET(flags, AT_EMPTY_PATH)) return -EINVAL; if (fd == AT_FDCWD) /* Both unspecified? Then operate on current working directory */ path = "."; else path = NULL; } else if (fd != AT_FDCWD) { /* If both have been specified, then we go via O_PATH */ opened_fd = openat(fd, path, O_PATH|O_CLOEXEC|(FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? 0 : O_NOFOLLOW)); if (opened_fd < 0) return -errno; fd = opened_fd; path = NULL; by_procfs = true; /* fgetxattr() is not going to work, go via /proc/ link right-away */ } for (;;) { _cleanup_free_ char *v = NULL; ssize_t n; if (n_attempts == 0) /* If someone is racing against us, give up eventually */ return -EBUSY; n_attempts--; v = new0(char, l+1); if (!v) return -ENOMEM; l = MALLOC_ELEMENTSOF(v) - 1; if (path) n = FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? getxattr(path, name, v, l) : lgetxattr(path, name, v, l); else n = by_procfs ? getxattr(FORMAT_PROC_FD_PATH(fd), name, v, l) : fgetxattr(fd, name, v, l); if (n < 0) { if (errno == EBADF) { if (by_procfs || path) return -EBADF; by_procfs = true; /* Might be an O_PATH fd, try again via /proc/ link */ continue; } if (errno != ERANGE) return -errno; } else { v[n] = 0; /* NUL terminate */ *ret = TAKE_PTR(v); return (int) n; } if (path) n = FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? getxattr(path, name, NULL, 0) : lgetxattr(path, name, NULL, 0); else n = by_procfs ? getxattr(FORMAT_PROC_FD_PATH(fd), name, NULL, 0) : fgetxattr(fd, name, NULL, 0); if (n < 0) return -errno; if (n > INT_MAX) /* We couldn't return this as 'int' anymore */ return -E2BIG; l = (size_t) n; } } static int parse_crtime(le64_t le, usec_t *usec) { uint64_t u; assert(usec); u = le64toh(le); if (IN_SET(u, 0, UINT64_MAX)) return -EIO; *usec = (usec_t) u; return 0; } int fd_getcrtime_at( int fd, const char *path, int flags, usec_t *ret) { _cleanup_free_ le64_t *le = NULL; STRUCT_STATX_DEFINE(sx); usec_t a, b; int r; assert(fd >= 0 || fd == AT_FDCWD); assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH)) == 0); assert(ret); if (!path) flags |= AT_EMPTY_PATH; /* So here's the deal: the creation/birth time (crtime/btime) of a file is a relatively newly supported concept * on Linux (or more strictly speaking: a concept that only recently got supported in the API, it was * implemented on various file systems on the lower level since a while, but never was accessible). However, we * needed a concept like that for vacuuming algorithms and such, hence we emulated it via a user xattr for a * long time. Starting with Linux 4.11 there's statx() which exposes the timestamp to userspace for the first * time, where it is available. This function will read it, but it tries to keep some compatibility with older * systems: we try to read both the crtime/btime and the xattr, and then use whatever is older. After all the * concept is useful for determining how "old" a file really is, and hence using the older of the two makes * most sense. */ if (statx(fd, strempty(path), (flags & ~AT_SYMLINK_FOLLOW)|(FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? 0 : AT_SYMLINK_NOFOLLOW)|AT_STATX_DONT_SYNC, STATX_BTIME, &sx) >= 0 && (sx.stx_mask & STATX_BTIME) && sx.stx_btime.tv_sec != 0) a = (usec_t) sx.stx_btime.tv_sec * USEC_PER_SEC + (usec_t) sx.stx_btime.tv_nsec / NSEC_PER_USEC; else a = USEC_INFINITY; r = getxattr_at_malloc(fd, path, "user.crtime_usec", flags, (char**) &le); if (r >= 0) { if (r != sizeof(*le)) r = -EIO; else r = parse_crtime(*le, &b); } if (r < 0) { if (a != USEC_INFINITY) { *ret = a; return 0; } return r; } if (a != USEC_INFINITY) *ret = MIN(a, b); else *ret = b; return 0; } int fd_setcrtime(int fd, usec_t usec) { le64_t le; assert(fd >= 0); if (!timestamp_is_set(usec)) usec = now(CLOCK_REALTIME); le = htole64((uint64_t) usec); return RET_NERRNO(fsetxattr(fd, "user.crtime_usec", &le, sizeof(le), 0)); } int listxattr_at_malloc( int fd, const char *path, int flags, char **ret) { _cleanup_close_ int opened_fd = -EBADF; bool by_procfs = false; unsigned n_attempts = 7; size_t l = 100; assert(fd >= 0 || fd == AT_FDCWD); assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH)) == 0); assert(ret); /* This is to listxattr()/llistattr()/flistattr() what getxattr_at_malloc() is to getxattr()/… */ if (!path) /* If path is NULL, imply AT_EMPTY_PATH. – But if it's "", don't. */ flags |= AT_EMPTY_PATH; if (isempty(path)) { if (!FLAGS_SET(flags, AT_EMPTY_PATH)) return -EINVAL; if (fd == AT_FDCWD) /* Both unspecified? Then operate on current working directory */ path = "."; else path = NULL; } else if (fd != AT_FDCWD) { /* If both have been specified, then we go via O_PATH */ opened_fd = openat(fd, path, O_PATH|O_CLOEXEC|(FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? 0 : O_NOFOLLOW)); if (opened_fd < 0) return -errno; fd = opened_fd; path = NULL; by_procfs = true; } for (;;) { _cleanup_free_ char *v = NULL; ssize_t n; if (n_attempts == 0) /* If someone is racing against us, give up eventually */ return -EBUSY; n_attempts--; v = new(char, l+1); if (!v) return -ENOMEM; l = MALLOC_ELEMENTSOF(v) - 1; if (path) n = FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? listxattr(path, v, l) : llistxattr(path, v, l); else n = by_procfs ? listxattr(FORMAT_PROC_FD_PATH(fd), v, l) : flistxattr(fd, v, l); if (n < 0) { if (errno == EBADF) { if (by_procfs || path) return -EBADF; by_procfs = true; /* Might be an O_PATH fd, try again via /proc/ link */ continue; } if (errno != ERANGE) return -errno; } else { v[n] = 0; /* NUL terminate */ *ret = TAKE_PTR(v); return (int) n; } if (path) n = FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? listxattr(path, NULL, 0) : llistxattr(path, NULL, 0); else n = by_procfs ? listxattr(FORMAT_PROC_FD_PATH(fd), NULL, 0) : flistxattr(fd, NULL, 0); if (n < 0) return -errno; if (n > INT_MAX) /* We couldn't return this as 'int' anymore */ return -E2BIG; l = (size_t) n; } } int xsetxattr(int fd, const char *path, const char *name, const char *value, size_t size, int flags) { _cleanup_close_ int opened_fd = -EBADF; bool by_procfs = false; int r; assert(fd >= 0 || fd == AT_FDCWD); assert(name); assert(value); assert((flags & ~(AT_SYMLINK_FOLLOW|AT_EMPTY_PATH)) == 0); /* So, this is a single function that does what setxattr()/lsetxattr()/fsetxattr() do, but in one go, * and with additional bells and whistles. Specifically: * * 1. This works on O_PATH fds (which fsetxattr() does not) * 2. Provides full openat()-style semantics, i.e. by-fd, by-path and combination thereof * 3. As extension to openat()-style semantics implies AT_EMPTY_PATH if path is NULL. */ if (!path) /* If path is NULL, imply AT_EMPTY_PATH. – But if it's "", don't — for safety reasons. */ flags |= AT_EMPTY_PATH; if (size == SIZE_MAX) size = strlen(value); if (isempty(path)) { if (!FLAGS_SET(flags, AT_EMPTY_PATH)) return -EINVAL; if (fd == AT_FDCWD) /* Both unspecified? Then operate on current working directory */ path = "."; else { r = fd_is_opath(fd); if (r < 0) return r; by_procfs = r; path = NULL; } } else if (fd != AT_FDCWD) { /* If both have been specified, then we go via O_PATH */ opened_fd = openat(fd, path, O_PATH|O_CLOEXEC|(FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? 0 : O_NOFOLLOW)); if (opened_fd < 0) return -errno; fd = opened_fd; path = NULL; by_procfs = true; /* fsetxattr() is not going to work, go via /proc/ link right-away */ } if (path) r = FLAGS_SET(flags, AT_SYMLINK_FOLLOW) ? setxattr(path, name, value, size, 0) : lsetxattr(path, name, value, size, 0); else r = by_procfs ? setxattr(FORMAT_PROC_FD_PATH(fd), name, value, size, 0) : fsetxattr(fd, name, value, size, 0); if (r < 0) return -errno; return 0; }
13,046
34.745205
130
c
null
systemd-main/src/basic/xattr-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> #include <stddef.h> #include <sys/types.h> #include "time-util.h" int getxattr_at_malloc(int fd, const char *path, const char *name, int flags, char **ret); static inline int getxattr_malloc(const char *path, const char *name, char **ret) { return getxattr_at_malloc(AT_FDCWD, path, name, AT_SYMLINK_FOLLOW, ret); } static inline int lgetxattr_malloc(const char *path, const char *name, char **ret) { return getxattr_at_malloc(AT_FDCWD, path, name, 0, ret); } static inline int fgetxattr_malloc(int fd, const char *name, char **ret) { return getxattr_at_malloc(fd, NULL, name, AT_EMPTY_PATH, ret); } int fd_setcrtime(int fd, usec_t usec); int fd_getcrtime_at(int fd, const char *name, int flags, usec_t *ret); static inline int fd_getcrtime(int fd, usec_t *ret) { return fd_getcrtime_at(fd, NULL, 0, ret); } int listxattr_at_malloc(int fd, const char *path, int flags, char **ret); static inline int listxattr_malloc(const char *path, char **ret) { return listxattr_at_malloc(AT_FDCWD, path, AT_SYMLINK_FOLLOW, ret); } static inline int llistxattr_malloc(const char *path, char **ret) { return listxattr_at_malloc(AT_FDCWD, path, 0, ret); } static inline int flistxattr_malloc(int fd, char **ret) { return listxattr_at_malloc(fd, NULL, AT_EMPTY_PATH, ret); } int xsetxattr(int fd, const char *path, const char *name, const char *value, size_t size, int flags);
1,508
35.804878
101
h
null
systemd-main/src/basic/linux/batman_adv.h
/* SPDX-License-Identifier: MIT */ /* Copyright (C) B.A.T.M.A.N. contributors: * * Matthias Schiffer */ #ifndef _UAPI_LINUX_BATMAN_ADV_H_ #define _UAPI_LINUX_BATMAN_ADV_H_ #define BATADV_NL_NAME "batadv" #define BATADV_NL_MCAST_GROUP_CONFIG "config" #define BATADV_NL_MCAST_GROUP_TPMETER "tpmeter" /** * enum batadv_tt_client_flags - TT client specific flags * * Bits from 0 to 7 are called _remote flags_ because they are sent on the wire. * Bits from 8 to 15 are called _local flags_ because they are used for local * computations only. * * Bits from 4 to 7 - a subset of remote flags - are ensured to be in sync with * the other nodes in the network. To achieve this goal these flags are included * in the TT CRC computation. */ enum batadv_tt_client_flags { /** * @BATADV_TT_CLIENT_DEL: the client has to be deleted from the table */ BATADV_TT_CLIENT_DEL = (1 << 0), /** * @BATADV_TT_CLIENT_ROAM: the client roamed to/from another node and * the new update telling its new real location has not been * received/sent yet */ BATADV_TT_CLIENT_ROAM = (1 << 1), /** * @BATADV_TT_CLIENT_WIFI: this client is connected through a wifi * interface. This information is used by the "AP Isolation" feature */ BATADV_TT_CLIENT_WIFI = (1 << 4), /** * @BATADV_TT_CLIENT_ISOLA: this client is considered "isolated". This * information is used by the Extended Isolation feature */ BATADV_TT_CLIENT_ISOLA = (1 << 5), /** * @BATADV_TT_CLIENT_NOPURGE: this client should never be removed from * the table */ BATADV_TT_CLIENT_NOPURGE = (1 << 8), /** * @BATADV_TT_CLIENT_NEW: this client has been added to the local table * but has not been announced yet */ BATADV_TT_CLIENT_NEW = (1 << 9), /** * @BATADV_TT_CLIENT_PENDING: this client is marked for removal but it * is kept in the table for one more originator interval for consistency * purposes */ BATADV_TT_CLIENT_PENDING = (1 << 10), /** * @BATADV_TT_CLIENT_TEMP: this global client has been detected to be * part of the network but no node has already announced it */ BATADV_TT_CLIENT_TEMP = (1 << 11), }; /** * enum batadv_mcast_flags_priv - Private, own multicast flags * * These are internal, multicast related flags. Currently they describe certain * multicast related attributes of the segment this originator bridges into the * mesh. * * Those attributes are used to determine the public multicast flags this * originator is going to announce via TT. * * For netlink, if BATADV_MCAST_FLAGS_BRIDGED is unset then all querier * related flags are undefined. */ enum batadv_mcast_flags_priv { /** * @BATADV_MCAST_FLAGS_BRIDGED: There is a bridge on top of the mesh * interface. */ BATADV_MCAST_FLAGS_BRIDGED = (1 << 0), /** * @BATADV_MCAST_FLAGS_QUERIER_IPV4_EXISTS: Whether an IGMP querier * exists in the mesh */ BATADV_MCAST_FLAGS_QUERIER_IPV4_EXISTS = (1 << 1), /** * @BATADV_MCAST_FLAGS_QUERIER_IPV6_EXISTS: Whether an MLD querier * exists in the mesh */ BATADV_MCAST_FLAGS_QUERIER_IPV6_EXISTS = (1 << 2), /** * @BATADV_MCAST_FLAGS_QUERIER_IPV4_SHADOWING: If an IGMP querier * exists, whether it is potentially shadowing multicast listeners * (i.e. querier is behind our own bridge segment) */ BATADV_MCAST_FLAGS_QUERIER_IPV4_SHADOWING = (1 << 3), /** * @BATADV_MCAST_FLAGS_QUERIER_IPV6_SHADOWING: If an MLD querier * exists, whether it is potentially shadowing multicast listeners * (i.e. querier is behind our own bridge segment) */ BATADV_MCAST_FLAGS_QUERIER_IPV6_SHADOWING = (1 << 4), }; /** * enum batadv_gw_modes - gateway mode of node */ enum batadv_gw_modes { /** @BATADV_GW_MODE_OFF: gw mode disabled */ BATADV_GW_MODE_OFF, /** @BATADV_GW_MODE_CLIENT: send DHCP requests to gw servers */ BATADV_GW_MODE_CLIENT, /** @BATADV_GW_MODE_SERVER: announce itself as gateway server */ BATADV_GW_MODE_SERVER, }; /** * enum batadv_nl_attrs - batman-adv netlink attributes */ enum batadv_nl_attrs { /** * @BATADV_ATTR_UNSPEC: unspecified attribute to catch errors */ BATADV_ATTR_UNSPEC, /** * @BATADV_ATTR_VERSION: batman-adv version string */ BATADV_ATTR_VERSION, /** * @BATADV_ATTR_ALGO_NAME: name of routing algorithm */ BATADV_ATTR_ALGO_NAME, /** * @BATADV_ATTR_MESH_IFINDEX: index of the batman-adv interface */ BATADV_ATTR_MESH_IFINDEX, /** * @BATADV_ATTR_MESH_IFNAME: name of the batman-adv interface */ BATADV_ATTR_MESH_IFNAME, /** * @BATADV_ATTR_MESH_ADDRESS: mac address of the batman-adv interface */ BATADV_ATTR_MESH_ADDRESS, /** * @BATADV_ATTR_HARD_IFINDEX: index of the non-batman-adv interface */ BATADV_ATTR_HARD_IFINDEX, /** * @BATADV_ATTR_HARD_IFNAME: name of the non-batman-adv interface */ BATADV_ATTR_HARD_IFNAME, /** * @BATADV_ATTR_HARD_ADDRESS: mac address of the non-batman-adv * interface */ BATADV_ATTR_HARD_ADDRESS, /** * @BATADV_ATTR_ORIG_ADDRESS: originator mac address */ BATADV_ATTR_ORIG_ADDRESS, /** * @BATADV_ATTR_TPMETER_RESULT: result of run (see * batadv_tp_meter_status) */ BATADV_ATTR_TPMETER_RESULT, /** * @BATADV_ATTR_TPMETER_TEST_TIME: time (msec) the run took */ BATADV_ATTR_TPMETER_TEST_TIME, /** * @BATADV_ATTR_TPMETER_BYTES: amount of acked bytes during run */ BATADV_ATTR_TPMETER_BYTES, /** * @BATADV_ATTR_TPMETER_COOKIE: session cookie to match tp_meter session */ BATADV_ATTR_TPMETER_COOKIE, /** * @BATADV_ATTR_PAD: attribute used for padding for 64-bit alignment */ BATADV_ATTR_PAD, /** * @BATADV_ATTR_ACTIVE: Flag indicating if the hard interface is active */ BATADV_ATTR_ACTIVE, /** * @BATADV_ATTR_TT_ADDRESS: Client MAC address */ BATADV_ATTR_TT_ADDRESS, /** * @BATADV_ATTR_TT_TTVN: Translation table version */ BATADV_ATTR_TT_TTVN, /** * @BATADV_ATTR_TT_LAST_TTVN: Previous translation table version */ BATADV_ATTR_TT_LAST_TTVN, /** * @BATADV_ATTR_TT_CRC32: CRC32 over translation table */ BATADV_ATTR_TT_CRC32, /** * @BATADV_ATTR_TT_VID: VLAN ID */ BATADV_ATTR_TT_VID, /** * @BATADV_ATTR_TT_FLAGS: Translation table client flags */ BATADV_ATTR_TT_FLAGS, /** * @BATADV_ATTR_FLAG_BEST: Flags indicating entry is the best */ BATADV_ATTR_FLAG_BEST, /** * @BATADV_ATTR_LAST_SEEN_MSECS: Time in milliseconds since last seen */ BATADV_ATTR_LAST_SEEN_MSECS, /** * @BATADV_ATTR_NEIGH_ADDRESS: Neighbour MAC address */ BATADV_ATTR_NEIGH_ADDRESS, /** * @BATADV_ATTR_TQ: TQ to neighbour */ BATADV_ATTR_TQ, /** * @BATADV_ATTR_THROUGHPUT: Estimated throughput to Neighbour */ BATADV_ATTR_THROUGHPUT, /** * @BATADV_ATTR_BANDWIDTH_UP: Reported uplink bandwidth */ BATADV_ATTR_BANDWIDTH_UP, /** * @BATADV_ATTR_BANDWIDTH_DOWN: Reported downlink bandwidth */ BATADV_ATTR_BANDWIDTH_DOWN, /** * @BATADV_ATTR_ROUTER: Gateway router MAC address */ BATADV_ATTR_ROUTER, /** * @BATADV_ATTR_BLA_OWN: Flag indicating own originator */ BATADV_ATTR_BLA_OWN, /** * @BATADV_ATTR_BLA_ADDRESS: Bridge loop avoidance claim MAC address */ BATADV_ATTR_BLA_ADDRESS, /** * @BATADV_ATTR_BLA_VID: BLA VLAN ID */ BATADV_ATTR_BLA_VID, /** * @BATADV_ATTR_BLA_BACKBONE: BLA gateway originator MAC address */ BATADV_ATTR_BLA_BACKBONE, /** * @BATADV_ATTR_BLA_CRC: BLA CRC */ BATADV_ATTR_BLA_CRC, /** * @BATADV_ATTR_DAT_CACHE_IP4ADDRESS: Client IPv4 address */ BATADV_ATTR_DAT_CACHE_IP4ADDRESS, /** * @BATADV_ATTR_DAT_CACHE_HWADDRESS: Client MAC address */ BATADV_ATTR_DAT_CACHE_HWADDRESS, /** * @BATADV_ATTR_DAT_CACHE_VID: VLAN ID */ BATADV_ATTR_DAT_CACHE_VID, /** * @BATADV_ATTR_MCAST_FLAGS: Per originator multicast flags */ BATADV_ATTR_MCAST_FLAGS, /** * @BATADV_ATTR_MCAST_FLAGS_PRIV: Private, own multicast flags */ BATADV_ATTR_MCAST_FLAGS_PRIV, /** * @BATADV_ATTR_VLANID: VLAN id on top of soft interface */ BATADV_ATTR_VLANID, /** * @BATADV_ATTR_AGGREGATED_OGMS_ENABLED: whether the batman protocol * messages of the mesh interface shall be aggregated or not. */ BATADV_ATTR_AGGREGATED_OGMS_ENABLED, /** * @BATADV_ATTR_AP_ISOLATION_ENABLED: whether the data traffic going * from a wireless client to another wireless client will be silently * dropped. */ BATADV_ATTR_AP_ISOLATION_ENABLED, /** * @BATADV_ATTR_ISOLATION_MARK: the isolation mark which is used to * classify clients as "isolated" by the Extended Isolation feature. */ BATADV_ATTR_ISOLATION_MARK, /** * @BATADV_ATTR_ISOLATION_MASK: the isolation (bit)mask which is used to * classify clients as "isolated" by the Extended Isolation feature. */ BATADV_ATTR_ISOLATION_MASK, /** * @BATADV_ATTR_BONDING_ENABLED: whether the data traffic going through * the mesh will be sent using multiple interfaces at the same time. */ BATADV_ATTR_BONDING_ENABLED, /** * @BATADV_ATTR_BRIDGE_LOOP_AVOIDANCE_ENABLED: whether the bridge loop * avoidance feature is enabled. This feature detects and avoids loops * between the mesh and devices bridged with the soft interface */ BATADV_ATTR_BRIDGE_LOOP_AVOIDANCE_ENABLED, /** * @BATADV_ATTR_DISTRIBUTED_ARP_TABLE_ENABLED: whether the distributed * arp table feature is enabled. This feature uses a distributed hash * table to answer ARP requests without flooding the request through * the whole mesh. */ BATADV_ATTR_DISTRIBUTED_ARP_TABLE_ENABLED, /** * @BATADV_ATTR_FRAGMENTATION_ENABLED: whether the data traffic going * through the mesh will be fragmented or silently discarded if the * packet size exceeds the outgoing interface MTU. */ BATADV_ATTR_FRAGMENTATION_ENABLED, /** * @BATADV_ATTR_GW_BANDWIDTH_DOWN: defines the download bandwidth which * is propagated by this node if %BATADV_ATTR_GW_BANDWIDTH_MODE was set * to 'server'. */ BATADV_ATTR_GW_BANDWIDTH_DOWN, /** * @BATADV_ATTR_GW_BANDWIDTH_UP: defines the upload bandwidth which * is propagated by this node if %BATADV_ATTR_GW_BANDWIDTH_MODE was set * to 'server'. */ BATADV_ATTR_GW_BANDWIDTH_UP, /** * @BATADV_ATTR_GW_MODE: defines the state of the gateway features. * Possible values are specified in enum batadv_gw_modes */ BATADV_ATTR_GW_MODE, /** * @BATADV_ATTR_GW_SEL_CLASS: defines the selection criteria this node * will use to choose a gateway if gw_mode was set to 'client'. */ BATADV_ATTR_GW_SEL_CLASS, /** * @BATADV_ATTR_HOP_PENALTY: defines the penalty which will be applied * to an originator message's tq-field on every hop and/or per * hard interface */ BATADV_ATTR_HOP_PENALTY, /** * @BATADV_ATTR_LOG_LEVEL: bitmask with to define which debug messages * should be send to the debug log/trace ring buffer */ BATADV_ATTR_LOG_LEVEL, /** * @BATADV_ATTR_MULTICAST_FORCEFLOOD_ENABLED: whether multicast * optimizations should be replaced by simple broadcast-like flooding * of multicast packets. If set to non-zero then all nodes in the mesh * are going to use classic flooding for any multicast packet with no * optimizations. */ BATADV_ATTR_MULTICAST_FORCEFLOOD_ENABLED, /** * @BATADV_ATTR_NETWORK_CODING_ENABLED: whether Network Coding (using * some magic to send fewer wifi packets but still the same content) is * enabled or not. */ BATADV_ATTR_NETWORK_CODING_ENABLED, /** * @BATADV_ATTR_ORIG_INTERVAL: defines the interval in milliseconds in * which batman sends its protocol messages. */ BATADV_ATTR_ORIG_INTERVAL, /** * @BATADV_ATTR_ELP_INTERVAL: defines the interval in milliseconds in * which batman emits probing packets for neighbor sensing (ELP). */ BATADV_ATTR_ELP_INTERVAL, /** * @BATADV_ATTR_THROUGHPUT_OVERRIDE: defines the throughput value to be * used by B.A.T.M.A.N. V when estimating the link throughput using * this interface. If the value is set to 0 then batman-adv will try to * estimate the throughput by itself. */ BATADV_ATTR_THROUGHPUT_OVERRIDE, /** * @BATADV_ATTR_MULTICAST_FANOUT: defines the maximum number of packet * copies that may be generated for a multicast-to-unicast conversion. * Once this limit is exceeded distribution will fall back to broadcast. */ BATADV_ATTR_MULTICAST_FANOUT, /* add attributes above here, update the policy in netlink.c */ /** * @__BATADV_ATTR_AFTER_LAST: internal use */ __BATADV_ATTR_AFTER_LAST, /** * @NUM_BATADV_ATTR: total number of batadv_nl_attrs available */ NUM_BATADV_ATTR = __BATADV_ATTR_AFTER_LAST, /** * @BATADV_ATTR_MAX: highest attribute number currently defined */ BATADV_ATTR_MAX = __BATADV_ATTR_AFTER_LAST - 1 }; /** * enum batadv_nl_commands - supported batman-adv netlink commands */ enum batadv_nl_commands { /** * @BATADV_CMD_UNSPEC: unspecified command to catch errors */ BATADV_CMD_UNSPEC, /** * @BATADV_CMD_GET_MESH: Get attributes from softif/mesh */ BATADV_CMD_GET_MESH, /** * @BATADV_CMD_GET_MESH_INFO: Alias for @BATADV_CMD_GET_MESH */ BATADV_CMD_GET_MESH_INFO = BATADV_CMD_GET_MESH, /** * @BATADV_CMD_TP_METER: Start a tp meter session */ BATADV_CMD_TP_METER, /** * @BATADV_CMD_TP_METER_CANCEL: Cancel a tp meter session */ BATADV_CMD_TP_METER_CANCEL, /** * @BATADV_CMD_GET_ROUTING_ALGOS: Query the list of routing algorithms. */ BATADV_CMD_GET_ROUTING_ALGOS, /** * @BATADV_CMD_GET_HARDIF: Get attributes from a hardif of the * current softif */ BATADV_CMD_GET_HARDIF, /** * @BATADV_CMD_GET_HARDIFS: Alias for @BATADV_CMD_GET_HARDIF */ BATADV_CMD_GET_HARDIFS = BATADV_CMD_GET_HARDIF, /** * @BATADV_CMD_GET_TRANSTABLE_LOCAL: Query list of local translations */ BATADV_CMD_GET_TRANSTABLE_LOCAL, /** * @BATADV_CMD_GET_TRANSTABLE_GLOBAL: Query list of global translations */ BATADV_CMD_GET_TRANSTABLE_GLOBAL, /** * @BATADV_CMD_GET_ORIGINATORS: Query list of originators */ BATADV_CMD_GET_ORIGINATORS, /** * @BATADV_CMD_GET_NEIGHBORS: Query list of neighbours */ BATADV_CMD_GET_NEIGHBORS, /** * @BATADV_CMD_GET_GATEWAYS: Query list of gateways */ BATADV_CMD_GET_GATEWAYS, /** * @BATADV_CMD_GET_BLA_CLAIM: Query list of bridge loop avoidance claims */ BATADV_CMD_GET_BLA_CLAIM, /** * @BATADV_CMD_GET_BLA_BACKBONE: Query list of bridge loop avoidance * backbones */ BATADV_CMD_GET_BLA_BACKBONE, /** * @BATADV_CMD_GET_DAT_CACHE: Query list of DAT cache entries */ BATADV_CMD_GET_DAT_CACHE, /** * @BATADV_CMD_GET_MCAST_FLAGS: Query list of multicast flags */ BATADV_CMD_GET_MCAST_FLAGS, /** * @BATADV_CMD_SET_MESH: Set attributes for softif/mesh */ BATADV_CMD_SET_MESH, /** * @BATADV_CMD_SET_HARDIF: Set attributes for hardif of the * current softif */ BATADV_CMD_SET_HARDIF, /** * @BATADV_CMD_GET_VLAN: Get attributes from a VLAN of the * current softif */ BATADV_CMD_GET_VLAN, /** * @BATADV_CMD_SET_VLAN: Set attributes for VLAN of the * current softif */ BATADV_CMD_SET_VLAN, /* add new commands above here */ /** * @__BATADV_CMD_AFTER_LAST: internal use */ __BATADV_CMD_AFTER_LAST, /** * @BATADV_CMD_MAX: highest used command number */ BATADV_CMD_MAX = __BATADV_CMD_AFTER_LAST - 1 }; /** * enum batadv_tp_meter_reason - reason of a tp meter test run stop */ enum batadv_tp_meter_reason { /** * @BATADV_TP_REASON_COMPLETE: sender finished tp run */ BATADV_TP_REASON_COMPLETE = 3, /** * @BATADV_TP_REASON_CANCEL: sender was stopped during run */ BATADV_TP_REASON_CANCEL = 4, /* error status >= 128 */ /** * @BATADV_TP_REASON_DST_UNREACHABLE: receiver could not be reached or * didn't answer */ BATADV_TP_REASON_DST_UNREACHABLE = 128, /** * @BATADV_TP_REASON_RESEND_LIMIT: (unused) sender retry reached limit */ BATADV_TP_REASON_RESEND_LIMIT = 129, /** * @BATADV_TP_REASON_ALREADY_ONGOING: test to or from the same node * already ongoing */ BATADV_TP_REASON_ALREADY_ONGOING = 130, /** * @BATADV_TP_REASON_MEMORY_ERROR: test was stopped due to low memory */ BATADV_TP_REASON_MEMORY_ERROR = 131, /** * @BATADV_TP_REASON_CANT_SEND: failed to send via outgoing interface */ BATADV_TP_REASON_CANT_SEND = 132, /** * @BATADV_TP_REASON_TOO_MANY: too many ongoing sessions */ BATADV_TP_REASON_TOO_MANY = 133, }; /** * enum batadv_ifla_attrs - batman-adv ifla nested attributes */ enum batadv_ifla_attrs { /** * @IFLA_BATADV_UNSPEC: unspecified attribute which is not parsed by * rtnetlink */ IFLA_BATADV_UNSPEC, /** * @IFLA_BATADV_ALGO_NAME: routing algorithm (name) which should be * used by the newly registered batadv net_device. */ IFLA_BATADV_ALGO_NAME, /* add attributes above here, update the policy in soft-interface.c */ /** * @__IFLA_BATADV_MAX: internal use */ __IFLA_BATADV_MAX, }; #define IFLA_BATADV_MAX (__IFLA_BATADV_MAX - 1) #endif /* _UAPI_LINUX_BATMAN_ADV_H_ */
16,902
22.975887
80
h
null
systemd-main/src/basic/linux/cfm_bridge.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ #ifndef _UAPI_LINUX_CFM_BRIDGE_H_ #define _UAPI_LINUX_CFM_BRIDGE_H_ #include <linux/types.h> #include <linux/if_ether.h> #define ETHER_HEADER_LENGTH (6+6+4+2) #define CFM_MAID_LENGTH 48 #define CFM_CCM_PDU_LENGTH 75 #define CFM_PORT_STATUS_TLV_LENGTH 4 #define CFM_IF_STATUS_TLV_LENGTH 4 #define CFM_IF_STATUS_TLV_TYPE 4 #define CFM_PORT_STATUS_TLV_TYPE 2 #define CFM_ENDE_TLV_TYPE 0 #define CFM_CCM_MAX_FRAME_LENGTH (ETHER_HEADER_LENGTH+\ CFM_CCM_PDU_LENGTH+\ CFM_PORT_STATUS_TLV_LENGTH+\ CFM_IF_STATUS_TLV_LENGTH) #define CFM_FRAME_PRIO 7 #define CFM_CCM_TLV_OFFSET 70 #define CFM_CCM_PDU_MAID_OFFSET 10 #define CFM_CCM_PDU_MEPID_OFFSET 8 #define CFM_CCM_PDU_SEQNR_OFFSET 4 #define CFM_CCM_PDU_TLV_OFFSET 74 #define CFM_CCM_ITU_RESERVED_SIZE 16 struct br_cfm_common_hdr { __u8 mdlevel_version; __u8 opcode; __u8 flags; __u8 tlv_offset; }; enum br_cfm_opcodes { BR_CFM_OPCODE_CCM = 0x1, }; /* MEP domain */ enum br_cfm_domain { BR_CFM_PORT, BR_CFM_VLAN, }; /* MEP direction */ enum br_cfm_mep_direction { BR_CFM_MEP_DIRECTION_DOWN, BR_CFM_MEP_DIRECTION_UP, }; /* CCM interval supported. */ enum br_cfm_ccm_interval { BR_CFM_CCM_INTERVAL_NONE, BR_CFM_CCM_INTERVAL_3_3_MS, BR_CFM_CCM_INTERVAL_10_MS, BR_CFM_CCM_INTERVAL_100_MS, BR_CFM_CCM_INTERVAL_1_SEC, BR_CFM_CCM_INTERVAL_10_SEC, BR_CFM_CCM_INTERVAL_1_MIN, BR_CFM_CCM_INTERVAL_10_MIN, }; #endif
1,466
21.569231
63
h
null
systemd-main/src/basic/linux/fib_rules.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_FIB_RULES_H #define __LINUX_FIB_RULES_H #include <linux/types.h> #include <linux/rtnetlink.h> /* rule is permanent, and cannot be deleted */ #define FIB_RULE_PERMANENT 0x00000001 #define FIB_RULE_INVERT 0x00000002 #define FIB_RULE_UNRESOLVED 0x00000004 #define FIB_RULE_IIF_DETACHED 0x00000008 #define FIB_RULE_DEV_DETACHED FIB_RULE_IIF_DETACHED #define FIB_RULE_OIF_DETACHED 0x00000010 /* try to find source address in routing lookups */ #define FIB_RULE_FIND_SADDR 0x00010000 struct fib_rule_hdr { __u8 family; __u8 dst_len; __u8 src_len; __u8 tos; __u8 table; __u8 res1; /* reserved */ __u8 res2; /* reserved */ __u8 action; __u32 flags; }; struct fib_rule_uid_range { __u32 start; __u32 end; }; struct fib_rule_port_range { __u16 start; __u16 end; }; enum { FRA_UNSPEC, FRA_DST, /* destination address */ FRA_SRC, /* source address */ FRA_IIFNAME, /* interface name */ #define FRA_IFNAME FRA_IIFNAME FRA_GOTO, /* target to jump to (FR_ACT_GOTO) */ FRA_UNUSED2, FRA_PRIORITY, /* priority/preference */ FRA_UNUSED3, FRA_UNUSED4, FRA_UNUSED5, FRA_FWMARK, /* mark */ FRA_FLOW, /* flow/class id */ FRA_TUN_ID, FRA_SUPPRESS_IFGROUP, FRA_SUPPRESS_PREFIXLEN, FRA_TABLE, /* Extended table id */ FRA_FWMASK, /* mask for netfilter mark */ FRA_OIFNAME, FRA_PAD, FRA_L3MDEV, /* iif or oif is l3mdev goto its table */ FRA_UID_RANGE, /* UID range */ FRA_PROTOCOL, /* Originator of the rule */ FRA_IP_PROTO, /* ip proto */ FRA_SPORT_RANGE, /* sport */ FRA_DPORT_RANGE, /* dport */ __FRA_MAX }; #define FRA_MAX (__FRA_MAX - 1) enum { FR_ACT_UNSPEC, FR_ACT_TO_TBL, /* Pass to fixed table */ FR_ACT_GOTO, /* Jump to another rule */ FR_ACT_NOP, /* No operation */ FR_ACT_RES3, FR_ACT_RES4, FR_ACT_BLACKHOLE, /* Drop without notification */ FR_ACT_UNREACHABLE, /* Drop with ENETUNREACH */ FR_ACT_PROHIBIT, /* Drop with EACCES */ __FR_ACT_MAX, }; #define FR_ACT_MAX (__FR_ACT_MAX - 1) #endif
2,036
21.384615
62
h
null
systemd-main/src/basic/linux/genetlink.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _UAPI__LINUX_GENERIC_NETLINK_H #define _UAPI__LINUX_GENERIC_NETLINK_H #include <linux/types.h> #include <linux/netlink.h> #define GENL_NAMSIZ 16 /* length of family name */ #define GENL_MIN_ID NLMSG_MIN_TYPE #define GENL_MAX_ID 1023 struct genlmsghdr { __u8 cmd; __u8 version; __u16 reserved; }; #define GENL_HDRLEN NLMSG_ALIGN(sizeof(struct genlmsghdr)) #define GENL_ADMIN_PERM 0x01 #define GENL_CMD_CAP_DO 0x02 #define GENL_CMD_CAP_DUMP 0x04 #define GENL_CMD_CAP_HASPOL 0x08 #define GENL_UNS_ADMIN_PERM 0x10 /* * List of reserved static generic netlink identifiers: */ #define GENL_ID_CTRL NLMSG_MIN_TYPE #define GENL_ID_VFS_DQUOT (NLMSG_MIN_TYPE + 1) #define GENL_ID_PMCRAID (NLMSG_MIN_TYPE + 2) /* must be last reserved + 1 */ #define GENL_START_ALLOC (NLMSG_MIN_TYPE + 3) /************************************************************************** * Controller **************************************************************************/ enum { CTRL_CMD_UNSPEC, CTRL_CMD_NEWFAMILY, CTRL_CMD_DELFAMILY, CTRL_CMD_GETFAMILY, CTRL_CMD_NEWOPS, CTRL_CMD_DELOPS, CTRL_CMD_GETOPS, CTRL_CMD_NEWMCAST_GRP, CTRL_CMD_DELMCAST_GRP, CTRL_CMD_GETMCAST_GRP, /* unused */ CTRL_CMD_GETPOLICY, __CTRL_CMD_MAX, }; #define CTRL_CMD_MAX (__CTRL_CMD_MAX - 1) enum { CTRL_ATTR_UNSPEC, CTRL_ATTR_FAMILY_ID, CTRL_ATTR_FAMILY_NAME, CTRL_ATTR_VERSION, CTRL_ATTR_HDRSIZE, CTRL_ATTR_MAXATTR, CTRL_ATTR_OPS, CTRL_ATTR_MCAST_GROUPS, CTRL_ATTR_POLICY, CTRL_ATTR_OP_POLICY, CTRL_ATTR_OP, __CTRL_ATTR_MAX, }; #define CTRL_ATTR_MAX (__CTRL_ATTR_MAX - 1) enum { CTRL_ATTR_OP_UNSPEC, CTRL_ATTR_OP_ID, CTRL_ATTR_OP_FLAGS, __CTRL_ATTR_OP_MAX, }; #define CTRL_ATTR_OP_MAX (__CTRL_ATTR_OP_MAX - 1) enum { CTRL_ATTR_MCAST_GRP_UNSPEC, CTRL_ATTR_MCAST_GRP_NAME, CTRL_ATTR_MCAST_GRP_ID, __CTRL_ATTR_MCAST_GRP_MAX, }; #define CTRL_ATTR_MCAST_GRP_MAX (__CTRL_ATTR_MCAST_GRP_MAX - 1) enum { CTRL_ATTR_POLICY_UNSPEC, CTRL_ATTR_POLICY_DO, CTRL_ATTR_POLICY_DUMP, __CTRL_ATTR_POLICY_DUMP_MAX, CTRL_ATTR_POLICY_DUMP_MAX = __CTRL_ATTR_POLICY_DUMP_MAX - 1 }; #define CTRL_ATTR_POLICY_MAX (__CTRL_ATTR_POLICY_DUMP_MAX - 1) #endif /* _UAPI__LINUX_GENERIC_NETLINK_H */
2,253
20.673077
76
h
null
systemd-main/src/basic/linux/if.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the INET interface module. * * Version: @(#)if.h 1.0.2 04/18/93 * * Authors: Original taken from Berkeley UNIX 4.3, (c) UCB 1982-1988 * Ross Biro * Fred N. van Kempen, <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _LINUX_IF_H #define _LINUX_IF_H #include <linux/libc-compat.h> /* for compatibility with glibc */ #include <linux/types.h> /* for "__kernel_caddr_t" et al */ #include <linux/socket.h> /* for "struct sockaddr" et al */ #ifndef __KERNEL__ #include <sys/socket.h> /* for struct sockaddr. */ #endif #if __UAPI_DEF_IF_IFNAMSIZ #define IFNAMSIZ 16 #endif /* __UAPI_DEF_IF_IFNAMSIZ */ #define IFALIASZ 256 #define ALTIFNAMSIZ 128 #include <linux/hdlc/ioctl.h> /* For glibc compatibility. An empty enum does not compile. */ #if __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO != 0 || \ __UAPI_DEF_IF_NET_DEVICE_FLAGS != 0 /** * enum net_device_flags - &struct net_device flags * * These are the &struct net_device flags, they can be set by drivers, the * kernel and some can be triggered by userspace. Userspace can query and * set these flags using userspace utilities but there is also a sysfs * entry available for all dev flags which can be queried and set. These flags * are shared for all types of net_devices. The sysfs entries are available * via /sys/class/net/<dev>/flags. Flags which can be toggled through sysfs * are annotated below, note that only a few flags can be toggled and some * other flags are always preserved from the original net_device flags * even if you try to set them via sysfs. Flags which are always preserved * are kept under the flag grouping @IFF_VOLATILE. Flags which are volatile * are annotated below as such. * * You should have a pretty good reason to be extending these flags. * * @IFF_UP: interface is up. Can be toggled through sysfs. * @IFF_BROADCAST: broadcast address valid. Volatile. * @IFF_DEBUG: turn on debugging. Can be toggled through sysfs. * @IFF_LOOPBACK: is a loopback net. Volatile. * @IFF_POINTOPOINT: interface is has p-p link. Volatile. * @IFF_NOTRAILERS: avoid use of trailers. Can be toggled through sysfs. * Volatile. * @IFF_RUNNING: interface RFC2863 OPER_UP. Volatile. * @IFF_NOARP: no ARP protocol. Can be toggled through sysfs. Volatile. * @IFF_PROMISC: receive all packets. Can be toggled through sysfs. * @IFF_ALLMULTI: receive all multicast packets. Can be toggled through * sysfs. * @IFF_MASTER: master of a load balancer. Volatile. * @IFF_SLAVE: slave of a load balancer. Volatile. * @IFF_MULTICAST: Supports multicast. Can be toggled through sysfs. * @IFF_PORTSEL: can set media type. Can be toggled through sysfs. * @IFF_AUTOMEDIA: auto media select active. Can be toggled through sysfs. * @IFF_DYNAMIC: dialup device with changing addresses. Can be toggled * through sysfs. * @IFF_LOWER_UP: driver signals L1 up. Volatile. * @IFF_DORMANT: driver signals dormant. Volatile. * @IFF_ECHO: echo sent packets. Volatile. */ enum net_device_flags { /* for compatibility with glibc net/if.h */ #if __UAPI_DEF_IF_NET_DEVICE_FLAGS IFF_UP = 1<<0, /* sysfs */ IFF_BROADCAST = 1<<1, /* volatile */ IFF_DEBUG = 1<<2, /* sysfs */ IFF_LOOPBACK = 1<<3, /* volatile */ IFF_POINTOPOINT = 1<<4, /* volatile */ IFF_NOTRAILERS = 1<<5, /* sysfs */ IFF_RUNNING = 1<<6, /* volatile */ IFF_NOARP = 1<<7, /* sysfs */ IFF_PROMISC = 1<<8, /* sysfs */ IFF_ALLMULTI = 1<<9, /* sysfs */ IFF_MASTER = 1<<10, /* volatile */ IFF_SLAVE = 1<<11, /* volatile */ IFF_MULTICAST = 1<<12, /* sysfs */ IFF_PORTSEL = 1<<13, /* sysfs */ IFF_AUTOMEDIA = 1<<14, /* sysfs */ IFF_DYNAMIC = 1<<15, /* sysfs */ #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS */ #if __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO IFF_LOWER_UP = 1<<16, /* volatile */ IFF_DORMANT = 1<<17, /* volatile */ IFF_ECHO = 1<<18, /* volatile */ #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO */ }; #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO != 0 || __UAPI_DEF_IF_NET_DEVICE_FLAGS != 0 */ /* for compatibility with glibc net/if.h */ #if __UAPI_DEF_IF_NET_DEVICE_FLAGS #define IFF_UP IFF_UP #define IFF_BROADCAST IFF_BROADCAST #define IFF_DEBUG IFF_DEBUG #define IFF_LOOPBACK IFF_LOOPBACK #define IFF_POINTOPOINT IFF_POINTOPOINT #define IFF_NOTRAILERS IFF_NOTRAILERS #define IFF_RUNNING IFF_RUNNING #define IFF_NOARP IFF_NOARP #define IFF_PROMISC IFF_PROMISC #define IFF_ALLMULTI IFF_ALLMULTI #define IFF_MASTER IFF_MASTER #define IFF_SLAVE IFF_SLAVE #define IFF_MULTICAST IFF_MULTICAST #define IFF_PORTSEL IFF_PORTSEL #define IFF_AUTOMEDIA IFF_AUTOMEDIA #define IFF_DYNAMIC IFF_DYNAMIC #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS */ #if __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO #define IFF_LOWER_UP IFF_LOWER_UP #define IFF_DORMANT IFF_DORMANT #define IFF_ECHO IFF_ECHO #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO */ #define IFF_VOLATILE (IFF_LOOPBACK|IFF_POINTOPOINT|IFF_BROADCAST|IFF_ECHO|\ IFF_MASTER|IFF_SLAVE|IFF_RUNNING|IFF_LOWER_UP|IFF_DORMANT) #define IF_GET_IFACE 0x0001 /* for querying only */ #define IF_GET_PROTO 0x0002 /* For definitions see hdlc.h */ #define IF_IFACE_V35 0x1000 /* V.35 serial interface */ #define IF_IFACE_V24 0x1001 /* V.24 serial interface */ #define IF_IFACE_X21 0x1002 /* X.21 serial interface */ #define IF_IFACE_T1 0x1003 /* T1 telco serial interface */ #define IF_IFACE_E1 0x1004 /* E1 telco serial interface */ #define IF_IFACE_SYNC_SERIAL 0x1005 /* can't be set by software */ #define IF_IFACE_X21D 0x1006 /* X.21 Dual Clocking (FarSite) */ /* For definitions see hdlc.h */ #define IF_PROTO_HDLC 0x2000 /* raw HDLC protocol */ #define IF_PROTO_PPP 0x2001 /* PPP protocol */ #define IF_PROTO_CISCO 0x2002 /* Cisco HDLC protocol */ #define IF_PROTO_FR 0x2003 /* Frame Relay protocol */ #define IF_PROTO_FR_ADD_PVC 0x2004 /* Create FR PVC */ #define IF_PROTO_FR_DEL_PVC 0x2005 /* Delete FR PVC */ #define IF_PROTO_X25 0x2006 /* X.25 */ #define IF_PROTO_HDLC_ETH 0x2007 /* raw HDLC, Ethernet emulation */ #define IF_PROTO_FR_ADD_ETH_PVC 0x2008 /* Create FR Ethernet-bridged PVC */ #define IF_PROTO_FR_DEL_ETH_PVC 0x2009 /* Delete FR Ethernet-bridged PVC */ #define IF_PROTO_FR_PVC 0x200A /* for reading PVC status */ #define IF_PROTO_FR_ETH_PVC 0x200B #define IF_PROTO_RAW 0x200C /* RAW Socket */ /* RFC 2863 operational status */ enum { IF_OPER_UNKNOWN, IF_OPER_NOTPRESENT, IF_OPER_DOWN, IF_OPER_LOWERLAYERDOWN, IF_OPER_TESTING, IF_OPER_DORMANT, IF_OPER_UP, }; /* link modes */ enum { IF_LINK_MODE_DEFAULT, IF_LINK_MODE_DORMANT, /* limit upward transition to dormant */ IF_LINK_MODE_TESTING, /* limit upward transition to testing */ }; /* * Device mapping structure. I'd just gone off and designed a * beautiful scheme using only loadable modules with arguments * for driver options and along come the PCMCIA people 8) * * Ah well. The get() side of this is good for WDSETUP, and it'll * be handy for debugging things. The set side is fine for now and * being very small might be worth keeping for clean configuration. */ /* for compatibility with glibc net/if.h */ #if __UAPI_DEF_IF_IFMAP struct ifmap { unsigned long mem_start; unsigned long mem_end; unsigned short base_addr; unsigned char irq; unsigned char dma; unsigned char port; /* 3 bytes spare */ }; #endif /* __UAPI_DEF_IF_IFMAP */ struct if_settings { unsigned int type; /* Type of physical device or protocol */ unsigned int size; /* Size of the data allocated by the caller */ union { /* {atm/eth/dsl}_settings anyone ? */ raw_hdlc_proto *raw_hdlc; cisco_proto *cisco; fr_proto *fr; fr_proto_pvc *fr_pvc; fr_proto_pvc_info *fr_pvc_info; x25_hdlc_proto *x25; /* interface settings */ sync_serial_settings *sync; te1_settings *te1; } ifs_ifsu; }; /* * Interface request structure used for socket * ioctl's. All interface ioctl's must have parameter * definitions which begin with ifr_name. The * remainder may be interface specific. */ /* for compatibility with glibc net/if.h */ #if __UAPI_DEF_IF_IFREQ struct ifreq { #define IFHWADDRLEN 6 union { char ifrn_name[IFNAMSIZ]; /* if name, e.g. "en0" */ } ifr_ifrn; union { struct sockaddr ifru_addr; struct sockaddr ifru_dstaddr; struct sockaddr ifru_broadaddr; struct sockaddr ifru_netmask; struct sockaddr ifru_hwaddr; short ifru_flags; int ifru_ivalue; int ifru_mtu; struct ifmap ifru_map; char ifru_slave[IFNAMSIZ]; /* Just fits the size */ char ifru_newname[IFNAMSIZ]; void * ifru_data; struct if_settings ifru_settings; } ifr_ifru; }; #endif /* __UAPI_DEF_IF_IFREQ */ #define ifr_name ifr_ifrn.ifrn_name /* interface name */ #define ifr_hwaddr ifr_ifru.ifru_hwaddr /* MAC address */ #define ifr_addr ifr_ifru.ifru_addr /* address */ #define ifr_dstaddr ifr_ifru.ifru_dstaddr /* other end of p-p lnk */ #define ifr_broadaddr ifr_ifru.ifru_broadaddr /* broadcast address */ #define ifr_netmask ifr_ifru.ifru_netmask /* interface net mask */ #define ifr_flags ifr_ifru.ifru_flags /* flags */ #define ifr_metric ifr_ifru.ifru_ivalue /* metric */ #define ifr_mtu ifr_ifru.ifru_mtu /* mtu */ #define ifr_map ifr_ifru.ifru_map /* device map */ #define ifr_slave ifr_ifru.ifru_slave /* slave device */ #define ifr_data ifr_ifru.ifru_data /* for use by interface */ #define ifr_ifindex ifr_ifru.ifru_ivalue /* interface index */ #define ifr_bandwidth ifr_ifru.ifru_ivalue /* link bandwidth */ #define ifr_qlen ifr_ifru.ifru_ivalue /* Queue length */ #define ifr_newname ifr_ifru.ifru_newname /* New name */ #define ifr_settings ifr_ifru.ifru_settings /* Device/proto settings*/ /* * Structure used in SIOCGIFCONF request. * Used to retrieve interface configuration * for machine (useful for programs which * must know all networks accessible). */ /* for compatibility with glibc net/if.h */ #if __UAPI_DEF_IF_IFCONF struct ifconf { int ifc_len; /* size of buffer */ union { char *ifcu_buf; struct ifreq *ifcu_req; } ifc_ifcu; }; #endif /* __UAPI_DEF_IF_IFCONF */ #define ifc_buf ifc_ifcu.ifcu_buf /* buffer address */ #define ifc_req ifc_ifcu.ifcu_req /* array of structures */ #endif /* _LINUX_IF_H */
10,874
35.493289
109
h
null
systemd-main/src/basic/linux/if_addr.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __LINUX_IF_ADDR_H #define __LINUX_IF_ADDR_H #include <linux/types.h> #include <linux/netlink.h> struct ifaddrmsg { __u8 ifa_family; __u8 ifa_prefixlen; /* The prefix length */ __u8 ifa_flags; /* Flags */ __u8 ifa_scope; /* Address scope */ __u32 ifa_index; /* Link index */ }; /* * Important comment: * IFA_ADDRESS is prefix address, rather than local interface address. * It makes no difference for normally configured broadcast interfaces, * but for point-to-point IFA_ADDRESS is DESTINATION address, * local address is supplied in IFA_LOCAL attribute. * * IFA_FLAGS is a u32 attribute that extends the u8 field ifa_flags. * If present, the value from struct ifaddrmsg will be ignored. */ enum { IFA_UNSPEC, IFA_ADDRESS, IFA_LOCAL, IFA_LABEL, IFA_BROADCAST, IFA_ANYCAST, IFA_CACHEINFO, IFA_MULTICAST, IFA_FLAGS, IFA_RT_PRIORITY, /* u32, priority/metric for prefix route */ IFA_TARGET_NETNSID, IFA_PROTO, /* u8, address protocol */ __IFA_MAX, }; #define IFA_MAX (__IFA_MAX - 1) /* ifa_flags */ #define IFA_F_SECONDARY 0x01 #define IFA_F_TEMPORARY IFA_F_SECONDARY #define IFA_F_NODAD 0x02 #define IFA_F_OPTIMISTIC 0x04 #define IFA_F_DADFAILED 0x08 #define IFA_F_HOMEADDRESS 0x10 #define IFA_F_DEPRECATED 0x20 #define IFA_F_TENTATIVE 0x40 #define IFA_F_PERMANENT 0x80 #define IFA_F_MANAGETEMPADDR 0x100 #define IFA_F_NOPREFIXROUTE 0x200 #define IFA_F_MCAUTOJOIN 0x400 #define IFA_F_STABLE_PRIVACY 0x800 struct ifa_cacheinfo { __u32 ifa_prefered; __u32 ifa_valid; __u32 cstamp; /* created timestamp, hundredths of seconds */ __u32 tstamp; /* updated timestamp, hundredths of seconds */ }; /* backwards compatibility for userspace */ #ifndef __KERNEL__ #define IFA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct ifaddrmsg)))) #define IFA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct ifaddrmsg)) #endif /* ifa_proto */ #define IFAPROT_UNSPEC 0 #define IFAPROT_KERNEL_LO 1 /* loopback */ #define IFAPROT_KERNEL_RA 2 /* set by kernel from router announcement */ #define IFAPROT_KERNEL_LL 3 /* link-local set by kernel */ #endif
2,169
26.125
92
h
null
systemd-main/src/basic/linux/if_bonding.h
/* SPDX-License-Identifier: GPL-1.0+ WITH Linux-syscall-note */ /* * Bond several ethernet interfaces into a Cisco, running 'Etherchannel'. * * * Portions are (c) Copyright 1995 Simon "Guru Aleph-Null" Janes * NCM: Network and Communications Management, Inc. * * BUT, I'm the one who modified it for ethernet, so: * (c) Copyright 1999, Thomas Davis, [email protected] * * This software may be used and distributed according to the terms * of the GNU Public License, incorporated herein by reference. * * 2003/03/18 - Amir Noam <amir.noam at intel dot com> * - Added support for getting slave's speed and duplex via ethtool. * Needed for 802.3ad and other future modes. * * 2003/03/18 - Tsippy Mendelson <tsippy.mendelson at intel dot com> and * Shmulik Hen <shmulik.hen at intel dot com> * - Enable support of modes that need to use the unique mac address of * each slave. * * 2003/03/18 - Tsippy Mendelson <tsippy.mendelson at intel dot com> and * Amir Noam <amir.noam at intel dot com> * - Moved driver's private data types to bonding.h * * 2003/03/18 - Amir Noam <amir.noam at intel dot com>, * Tsippy Mendelson <tsippy.mendelson at intel dot com> and * Shmulik Hen <shmulik.hen at intel dot com> * - Added support for IEEE 802.3ad Dynamic link aggregation mode. * * 2003/05/01 - Amir Noam <amir.noam at intel dot com> * - Added ABI version control to restore compatibility between * new/old ifenslave and new/old bonding. * * 2003/12/01 - Shmulik Hen <shmulik.hen at intel dot com> * - Code cleanup and style changes * * 2005/05/05 - Jason Gabler <jygabler at lbl dot gov> * - added definitions for various XOR hashing policies */ #ifndef _LINUX_IF_BONDING_H #define _LINUX_IF_BONDING_H #include <linux/if.h> #include <linux/types.h> #include <linux/if_ether.h> /* userland - kernel ABI version (2003/05/08) */ #define BOND_ABI_VERSION 2 /* * We can remove these ioctl definitions in 2.5. People should use the * SIOC*** versions of them instead */ #define BOND_ENSLAVE_OLD (SIOCDEVPRIVATE) #define BOND_RELEASE_OLD (SIOCDEVPRIVATE + 1) #define BOND_SETHWADDR_OLD (SIOCDEVPRIVATE + 2) #define BOND_SLAVE_INFO_QUERY_OLD (SIOCDEVPRIVATE + 11) #define BOND_INFO_QUERY_OLD (SIOCDEVPRIVATE + 12) #define BOND_CHANGE_ACTIVE_OLD (SIOCDEVPRIVATE + 13) #define BOND_CHECK_MII_STATUS (SIOCGMIIPHY) #define BOND_MODE_ROUNDROBIN 0 #define BOND_MODE_ACTIVEBACKUP 1 #define BOND_MODE_XOR 2 #define BOND_MODE_BROADCAST 3 #define BOND_MODE_8023AD 4 #define BOND_MODE_TLB 5 #define BOND_MODE_ALB 6 /* TLB + RLB (receive load balancing) */ /* each slave's link has 4 states */ #define BOND_LINK_UP 0 /* link is up and running */ #define BOND_LINK_FAIL 1 /* link has just gone down */ #define BOND_LINK_DOWN 2 /* link has been down for too long time */ #define BOND_LINK_BACK 3 /* link is going back */ /* each slave has several states */ #define BOND_STATE_ACTIVE 0 /* link is active */ #define BOND_STATE_BACKUP 1 /* link is backup */ #define BOND_DEFAULT_MAX_BONDS 1 /* Default maximum number of devices to support */ #define BOND_DEFAULT_TX_QUEUES 16 /* Default number of tx queues per device */ #define BOND_DEFAULT_RESEND_IGMP 1 /* Default number of IGMP membership reports */ /* hashing types */ #define BOND_XMIT_POLICY_LAYER2 0 /* layer 2 (MAC only), default */ #define BOND_XMIT_POLICY_LAYER34 1 /* layer 3+4 (IP ^ (TCP || UDP)) */ #define BOND_XMIT_POLICY_LAYER23 2 /* layer 2+3 (IP ^ MAC) */ #define BOND_XMIT_POLICY_ENCAP23 3 /* encapsulated layer 2+3 */ #define BOND_XMIT_POLICY_ENCAP34 4 /* encapsulated layer 3+4 */ #define BOND_XMIT_POLICY_VLAN_SRCMAC 5 /* vlan + source MAC */ /* 802.3ad port state definitions (43.4.2.2 in the 802.3ad standard) */ #define LACP_STATE_LACP_ACTIVITY 0x1 #define LACP_STATE_LACP_TIMEOUT 0x2 #define LACP_STATE_AGGREGATION 0x4 #define LACP_STATE_SYNCHRONIZATION 0x8 #define LACP_STATE_COLLECTING 0x10 #define LACP_STATE_DISTRIBUTING 0x20 #define LACP_STATE_DEFAULTED 0x40 #define LACP_STATE_EXPIRED 0x80 typedef struct ifbond { __s32 bond_mode; __s32 num_slaves; __s32 miimon; } ifbond; typedef struct ifslave { __s32 slave_id; /* Used as an IN param to the BOND_SLAVE_INFO_QUERY ioctl */ char slave_name[IFNAMSIZ]; __s8 link; __s8 state; __u32 link_failure_count; } ifslave; struct ad_info { __u16 aggregator_id; __u16 ports; __u16 actor_key; __u16 partner_key; __u8 partner_system[ETH_ALEN]; }; /* Embedded inside LINK_XSTATS_TYPE_BOND */ enum { BOND_XSTATS_UNSPEC, BOND_XSTATS_3AD, __BOND_XSTATS_MAX }; #define BOND_XSTATS_MAX (__BOND_XSTATS_MAX - 1) /* Embedded inside BOND_XSTATS_3AD */ enum { BOND_3AD_STAT_LACPDU_RX, BOND_3AD_STAT_LACPDU_TX, BOND_3AD_STAT_LACPDU_UNKNOWN_RX, BOND_3AD_STAT_LACPDU_ILLEGAL_RX, BOND_3AD_STAT_MARKER_RX, BOND_3AD_STAT_MARKER_TX, BOND_3AD_STAT_MARKER_RESP_RX, BOND_3AD_STAT_MARKER_RESP_TX, BOND_3AD_STAT_MARKER_UNKNOWN_RX, BOND_3AD_STAT_PAD, __BOND_3AD_STAT_MAX }; #define BOND_3AD_STAT_MAX (__BOND_3AD_STAT_MAX - 1) #endif /* _LINUX_IF_BONDING_H */
5,145
31.987179
86
h
null
systemd-main/src/basic/linux/if_bridge.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Linux ethernet bridge * * Authors: * Lennert Buytenhek <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _UAPI_LINUX_IF_BRIDGE_H #define _UAPI_LINUX_IF_BRIDGE_H #include <linux/types.h> #include <linux/if_ether.h> #include <linux/in6.h> #define SYSFS_BRIDGE_ATTR "bridge" #define SYSFS_BRIDGE_FDB "brforward" #define SYSFS_BRIDGE_PORT_SUBDIR "brif" #define SYSFS_BRIDGE_PORT_ATTR "brport" #define SYSFS_BRIDGE_PORT_LINK "bridge" #define BRCTL_VERSION 1 #define BRCTL_GET_VERSION 0 #define BRCTL_GET_BRIDGES 1 #define BRCTL_ADD_BRIDGE 2 #define BRCTL_DEL_BRIDGE 3 #define BRCTL_ADD_IF 4 #define BRCTL_DEL_IF 5 #define BRCTL_GET_BRIDGE_INFO 6 #define BRCTL_GET_PORT_LIST 7 #define BRCTL_SET_BRIDGE_FORWARD_DELAY 8 #define BRCTL_SET_BRIDGE_HELLO_TIME 9 #define BRCTL_SET_BRIDGE_MAX_AGE 10 #define BRCTL_SET_AGEING_TIME 11 #define BRCTL_SET_GC_INTERVAL 12 #define BRCTL_GET_PORT_INFO 13 #define BRCTL_SET_BRIDGE_STP_STATE 14 #define BRCTL_SET_BRIDGE_PRIORITY 15 #define BRCTL_SET_PORT_PRIORITY 16 #define BRCTL_SET_PATH_COST 17 #define BRCTL_GET_FDB_ENTRIES 18 #define BR_STATE_DISABLED 0 #define BR_STATE_LISTENING 1 #define BR_STATE_LEARNING 2 #define BR_STATE_FORWARDING 3 #define BR_STATE_BLOCKING 4 struct __bridge_info { __u64 designated_root; __u64 bridge_id; __u32 root_path_cost; __u32 max_age; __u32 hello_time; __u32 forward_delay; __u32 bridge_max_age; __u32 bridge_hello_time; __u32 bridge_forward_delay; __u8 topology_change; __u8 topology_change_detected; __u8 root_port; __u8 stp_enabled; __u32 ageing_time; __u32 gc_interval; __u32 hello_timer_value; __u32 tcn_timer_value; __u32 topology_change_timer_value; __u32 gc_timer_value; }; struct __port_info { __u64 designated_root; __u64 designated_bridge; __u16 port_id; __u16 designated_port; __u32 path_cost; __u32 designated_cost; __u8 state; __u8 top_change_ack; __u8 config_pending; __u8 unused0; __u32 message_age_timer_value; __u32 forward_delay_timer_value; __u32 hold_timer_value; }; struct __fdb_entry { __u8 mac_addr[ETH_ALEN]; __u8 port_no; __u8 is_local; __u32 ageing_timer_value; __u8 port_hi; __u8 pad0; __u16 unused; }; /* Bridge Flags */ #define BRIDGE_FLAGS_MASTER 1 /* Bridge command to/from master */ #define BRIDGE_FLAGS_SELF 2 /* Bridge command to/from lowerdev */ #define BRIDGE_MODE_VEB 0 /* Default loopback mode */ #define BRIDGE_MODE_VEPA 1 /* 802.1Qbg defined VEPA mode */ #define BRIDGE_MODE_UNDEF 0xFFFF /* mode undefined */ /* Bridge management nested attributes * [IFLA_AF_SPEC] = { * [IFLA_BRIDGE_FLAGS] * [IFLA_BRIDGE_MODE] * [IFLA_BRIDGE_VLAN_INFO] * } */ enum { IFLA_BRIDGE_FLAGS, IFLA_BRIDGE_MODE, IFLA_BRIDGE_VLAN_INFO, IFLA_BRIDGE_VLAN_TUNNEL_INFO, IFLA_BRIDGE_MRP, IFLA_BRIDGE_CFM, IFLA_BRIDGE_MST, __IFLA_BRIDGE_MAX, }; #define IFLA_BRIDGE_MAX (__IFLA_BRIDGE_MAX - 1) #define BRIDGE_VLAN_INFO_MASTER (1<<0) /* Operate on Bridge device as well */ #define BRIDGE_VLAN_INFO_PVID (1<<1) /* VLAN is PVID, ingress untagged */ #define BRIDGE_VLAN_INFO_UNTAGGED (1<<2) /* VLAN egresses untagged */ #define BRIDGE_VLAN_INFO_RANGE_BEGIN (1<<3) /* VLAN is start of vlan range */ #define BRIDGE_VLAN_INFO_RANGE_END (1<<4) /* VLAN is end of vlan range */ #define BRIDGE_VLAN_INFO_BRENTRY (1<<5) /* Global bridge VLAN entry */ #define BRIDGE_VLAN_INFO_ONLY_OPTS (1<<6) /* Skip create/delete/flags */ struct bridge_vlan_info { __u16 flags; __u16 vid; }; enum { IFLA_BRIDGE_VLAN_TUNNEL_UNSPEC, IFLA_BRIDGE_VLAN_TUNNEL_ID, IFLA_BRIDGE_VLAN_TUNNEL_VID, IFLA_BRIDGE_VLAN_TUNNEL_FLAGS, __IFLA_BRIDGE_VLAN_TUNNEL_MAX, }; #define IFLA_BRIDGE_VLAN_TUNNEL_MAX (__IFLA_BRIDGE_VLAN_TUNNEL_MAX - 1) struct bridge_vlan_xstats { __u64 rx_bytes; __u64 rx_packets; __u64 tx_bytes; __u64 tx_packets; __u16 vid; __u16 flags; __u32 pad2; }; enum { IFLA_BRIDGE_MRP_UNSPEC, IFLA_BRIDGE_MRP_INSTANCE, IFLA_BRIDGE_MRP_PORT_STATE, IFLA_BRIDGE_MRP_PORT_ROLE, IFLA_BRIDGE_MRP_RING_STATE, IFLA_BRIDGE_MRP_RING_ROLE, IFLA_BRIDGE_MRP_START_TEST, IFLA_BRIDGE_MRP_INFO, IFLA_BRIDGE_MRP_IN_ROLE, IFLA_BRIDGE_MRP_IN_STATE, IFLA_BRIDGE_MRP_START_IN_TEST, __IFLA_BRIDGE_MRP_MAX, }; #define IFLA_BRIDGE_MRP_MAX (__IFLA_BRIDGE_MRP_MAX - 1) enum { IFLA_BRIDGE_MRP_INSTANCE_UNSPEC, IFLA_BRIDGE_MRP_INSTANCE_RING_ID, IFLA_BRIDGE_MRP_INSTANCE_P_IFINDEX, IFLA_BRIDGE_MRP_INSTANCE_S_IFINDEX, IFLA_BRIDGE_MRP_INSTANCE_PRIO, __IFLA_BRIDGE_MRP_INSTANCE_MAX, }; #define IFLA_BRIDGE_MRP_INSTANCE_MAX (__IFLA_BRIDGE_MRP_INSTANCE_MAX - 1) enum { IFLA_BRIDGE_MRP_PORT_STATE_UNSPEC, IFLA_BRIDGE_MRP_PORT_STATE_STATE, __IFLA_BRIDGE_MRP_PORT_STATE_MAX, }; #define IFLA_BRIDGE_MRP_PORT_STATE_MAX (__IFLA_BRIDGE_MRP_PORT_STATE_MAX - 1) enum { IFLA_BRIDGE_MRP_PORT_ROLE_UNSPEC, IFLA_BRIDGE_MRP_PORT_ROLE_ROLE, __IFLA_BRIDGE_MRP_PORT_ROLE_MAX, }; #define IFLA_BRIDGE_MRP_PORT_ROLE_MAX (__IFLA_BRIDGE_MRP_PORT_ROLE_MAX - 1) enum { IFLA_BRIDGE_MRP_RING_STATE_UNSPEC, IFLA_BRIDGE_MRP_RING_STATE_RING_ID, IFLA_BRIDGE_MRP_RING_STATE_STATE, __IFLA_BRIDGE_MRP_RING_STATE_MAX, }; #define IFLA_BRIDGE_MRP_RING_STATE_MAX (__IFLA_BRIDGE_MRP_RING_STATE_MAX - 1) enum { IFLA_BRIDGE_MRP_RING_ROLE_UNSPEC, IFLA_BRIDGE_MRP_RING_ROLE_RING_ID, IFLA_BRIDGE_MRP_RING_ROLE_ROLE, __IFLA_BRIDGE_MRP_RING_ROLE_MAX, }; #define IFLA_BRIDGE_MRP_RING_ROLE_MAX (__IFLA_BRIDGE_MRP_RING_ROLE_MAX - 1) enum { IFLA_BRIDGE_MRP_START_TEST_UNSPEC, IFLA_BRIDGE_MRP_START_TEST_RING_ID, IFLA_BRIDGE_MRP_START_TEST_INTERVAL, IFLA_BRIDGE_MRP_START_TEST_MAX_MISS, IFLA_BRIDGE_MRP_START_TEST_PERIOD, IFLA_BRIDGE_MRP_START_TEST_MONITOR, __IFLA_BRIDGE_MRP_START_TEST_MAX, }; #define IFLA_BRIDGE_MRP_START_TEST_MAX (__IFLA_BRIDGE_MRP_START_TEST_MAX - 1) enum { IFLA_BRIDGE_MRP_INFO_UNSPEC, IFLA_BRIDGE_MRP_INFO_RING_ID, IFLA_BRIDGE_MRP_INFO_P_IFINDEX, IFLA_BRIDGE_MRP_INFO_S_IFINDEX, IFLA_BRIDGE_MRP_INFO_PRIO, IFLA_BRIDGE_MRP_INFO_RING_STATE, IFLA_BRIDGE_MRP_INFO_RING_ROLE, IFLA_BRIDGE_MRP_INFO_TEST_INTERVAL, IFLA_BRIDGE_MRP_INFO_TEST_MAX_MISS, IFLA_BRIDGE_MRP_INFO_TEST_MONITOR, IFLA_BRIDGE_MRP_INFO_I_IFINDEX, IFLA_BRIDGE_MRP_INFO_IN_STATE, IFLA_BRIDGE_MRP_INFO_IN_ROLE, IFLA_BRIDGE_MRP_INFO_IN_TEST_INTERVAL, IFLA_BRIDGE_MRP_INFO_IN_TEST_MAX_MISS, __IFLA_BRIDGE_MRP_INFO_MAX, }; #define IFLA_BRIDGE_MRP_INFO_MAX (__IFLA_BRIDGE_MRP_INFO_MAX - 1) enum { IFLA_BRIDGE_MRP_IN_STATE_UNSPEC, IFLA_BRIDGE_MRP_IN_STATE_IN_ID, IFLA_BRIDGE_MRP_IN_STATE_STATE, __IFLA_BRIDGE_MRP_IN_STATE_MAX, }; #define IFLA_BRIDGE_MRP_IN_STATE_MAX (__IFLA_BRIDGE_MRP_IN_STATE_MAX - 1) enum { IFLA_BRIDGE_MRP_IN_ROLE_UNSPEC, IFLA_BRIDGE_MRP_IN_ROLE_RING_ID, IFLA_BRIDGE_MRP_IN_ROLE_IN_ID, IFLA_BRIDGE_MRP_IN_ROLE_ROLE, IFLA_BRIDGE_MRP_IN_ROLE_I_IFINDEX, __IFLA_BRIDGE_MRP_IN_ROLE_MAX, }; #define IFLA_BRIDGE_MRP_IN_ROLE_MAX (__IFLA_BRIDGE_MRP_IN_ROLE_MAX - 1) enum { IFLA_BRIDGE_MRP_START_IN_TEST_UNSPEC, IFLA_BRIDGE_MRP_START_IN_TEST_IN_ID, IFLA_BRIDGE_MRP_START_IN_TEST_INTERVAL, IFLA_BRIDGE_MRP_START_IN_TEST_MAX_MISS, IFLA_BRIDGE_MRP_START_IN_TEST_PERIOD, __IFLA_BRIDGE_MRP_START_IN_TEST_MAX, }; #define IFLA_BRIDGE_MRP_START_IN_TEST_MAX (__IFLA_BRIDGE_MRP_START_IN_TEST_MAX - 1) struct br_mrp_instance { __u32 ring_id; __u32 p_ifindex; __u32 s_ifindex; __u16 prio; }; struct br_mrp_ring_state { __u32 ring_id; __u32 ring_state; }; struct br_mrp_ring_role { __u32 ring_id; __u32 ring_role; }; struct br_mrp_start_test { __u32 ring_id; __u32 interval; __u32 max_miss; __u32 period; __u32 monitor; }; struct br_mrp_in_state { __u32 in_state; __u16 in_id; }; struct br_mrp_in_role { __u32 ring_id; __u32 in_role; __u32 i_ifindex; __u16 in_id; }; struct br_mrp_start_in_test { __u32 interval; __u32 max_miss; __u32 period; __u16 in_id; }; enum { IFLA_BRIDGE_CFM_UNSPEC, IFLA_BRIDGE_CFM_MEP_CREATE, IFLA_BRIDGE_CFM_MEP_DELETE, IFLA_BRIDGE_CFM_MEP_CONFIG, IFLA_BRIDGE_CFM_CC_CONFIG, IFLA_BRIDGE_CFM_CC_PEER_MEP_ADD, IFLA_BRIDGE_CFM_CC_PEER_MEP_REMOVE, IFLA_BRIDGE_CFM_CC_RDI, IFLA_BRIDGE_CFM_CC_CCM_TX, IFLA_BRIDGE_CFM_MEP_CREATE_INFO, IFLA_BRIDGE_CFM_MEP_CONFIG_INFO, IFLA_BRIDGE_CFM_CC_CONFIG_INFO, IFLA_BRIDGE_CFM_CC_RDI_INFO, IFLA_BRIDGE_CFM_CC_CCM_TX_INFO, IFLA_BRIDGE_CFM_CC_PEER_MEP_INFO, IFLA_BRIDGE_CFM_MEP_STATUS_INFO, IFLA_BRIDGE_CFM_CC_PEER_STATUS_INFO, __IFLA_BRIDGE_CFM_MAX, }; #define IFLA_BRIDGE_CFM_MAX (__IFLA_BRIDGE_CFM_MAX - 1) enum { IFLA_BRIDGE_CFM_MEP_CREATE_UNSPEC, IFLA_BRIDGE_CFM_MEP_CREATE_INSTANCE, IFLA_BRIDGE_CFM_MEP_CREATE_DOMAIN, IFLA_BRIDGE_CFM_MEP_CREATE_DIRECTION, IFLA_BRIDGE_CFM_MEP_CREATE_IFINDEX, __IFLA_BRIDGE_CFM_MEP_CREATE_MAX, }; #define IFLA_BRIDGE_CFM_MEP_CREATE_MAX (__IFLA_BRIDGE_CFM_MEP_CREATE_MAX - 1) enum { IFLA_BRIDGE_CFM_MEP_DELETE_UNSPEC, IFLA_BRIDGE_CFM_MEP_DELETE_INSTANCE, __IFLA_BRIDGE_CFM_MEP_DELETE_MAX, }; #define IFLA_BRIDGE_CFM_MEP_DELETE_MAX (__IFLA_BRIDGE_CFM_MEP_DELETE_MAX - 1) enum { IFLA_BRIDGE_CFM_MEP_CONFIG_UNSPEC, IFLA_BRIDGE_CFM_MEP_CONFIG_INSTANCE, IFLA_BRIDGE_CFM_MEP_CONFIG_UNICAST_MAC, IFLA_BRIDGE_CFM_MEP_CONFIG_MDLEVEL, IFLA_BRIDGE_CFM_MEP_CONFIG_MEPID, __IFLA_BRIDGE_CFM_MEP_CONFIG_MAX, }; #define IFLA_BRIDGE_CFM_MEP_CONFIG_MAX (__IFLA_BRIDGE_CFM_MEP_CONFIG_MAX - 1) enum { IFLA_BRIDGE_CFM_CC_CONFIG_UNSPEC, IFLA_BRIDGE_CFM_CC_CONFIG_INSTANCE, IFLA_BRIDGE_CFM_CC_CONFIG_ENABLE, IFLA_BRIDGE_CFM_CC_CONFIG_EXP_INTERVAL, IFLA_BRIDGE_CFM_CC_CONFIG_EXP_MAID, __IFLA_BRIDGE_CFM_CC_CONFIG_MAX, }; #define IFLA_BRIDGE_CFM_CC_CONFIG_MAX (__IFLA_BRIDGE_CFM_CC_CONFIG_MAX - 1) enum { IFLA_BRIDGE_CFM_CC_PEER_MEP_UNSPEC, IFLA_BRIDGE_CFM_CC_PEER_MEP_INSTANCE, IFLA_BRIDGE_CFM_CC_PEER_MEPID, __IFLA_BRIDGE_CFM_CC_PEER_MEP_MAX, }; #define IFLA_BRIDGE_CFM_CC_PEER_MEP_MAX (__IFLA_BRIDGE_CFM_CC_PEER_MEP_MAX - 1) enum { IFLA_BRIDGE_CFM_CC_RDI_UNSPEC, IFLA_BRIDGE_CFM_CC_RDI_INSTANCE, IFLA_BRIDGE_CFM_CC_RDI_RDI, __IFLA_BRIDGE_CFM_CC_RDI_MAX, }; #define IFLA_BRIDGE_CFM_CC_RDI_MAX (__IFLA_BRIDGE_CFM_CC_RDI_MAX - 1) enum { IFLA_BRIDGE_CFM_CC_CCM_TX_UNSPEC, IFLA_BRIDGE_CFM_CC_CCM_TX_INSTANCE, IFLA_BRIDGE_CFM_CC_CCM_TX_DMAC, IFLA_BRIDGE_CFM_CC_CCM_TX_SEQ_NO_UPDATE, IFLA_BRIDGE_CFM_CC_CCM_TX_PERIOD, IFLA_BRIDGE_CFM_CC_CCM_TX_IF_TLV, IFLA_BRIDGE_CFM_CC_CCM_TX_IF_TLV_VALUE, IFLA_BRIDGE_CFM_CC_CCM_TX_PORT_TLV, IFLA_BRIDGE_CFM_CC_CCM_TX_PORT_TLV_VALUE, __IFLA_BRIDGE_CFM_CC_CCM_TX_MAX, }; #define IFLA_BRIDGE_CFM_CC_CCM_TX_MAX (__IFLA_BRIDGE_CFM_CC_CCM_TX_MAX - 1) enum { IFLA_BRIDGE_CFM_MEP_STATUS_UNSPEC, IFLA_BRIDGE_CFM_MEP_STATUS_INSTANCE, IFLA_BRIDGE_CFM_MEP_STATUS_OPCODE_UNEXP_SEEN, IFLA_BRIDGE_CFM_MEP_STATUS_VERSION_UNEXP_SEEN, IFLA_BRIDGE_CFM_MEP_STATUS_RX_LEVEL_LOW_SEEN, __IFLA_BRIDGE_CFM_MEP_STATUS_MAX, }; #define IFLA_BRIDGE_CFM_MEP_STATUS_MAX (__IFLA_BRIDGE_CFM_MEP_STATUS_MAX - 1) enum { IFLA_BRIDGE_CFM_CC_PEER_STATUS_UNSPEC, IFLA_BRIDGE_CFM_CC_PEER_STATUS_INSTANCE, IFLA_BRIDGE_CFM_CC_PEER_STATUS_PEER_MEPID, IFLA_BRIDGE_CFM_CC_PEER_STATUS_CCM_DEFECT, IFLA_BRIDGE_CFM_CC_PEER_STATUS_RDI, IFLA_BRIDGE_CFM_CC_PEER_STATUS_PORT_TLV_VALUE, IFLA_BRIDGE_CFM_CC_PEER_STATUS_IF_TLV_VALUE, IFLA_BRIDGE_CFM_CC_PEER_STATUS_SEEN, IFLA_BRIDGE_CFM_CC_PEER_STATUS_TLV_SEEN, IFLA_BRIDGE_CFM_CC_PEER_STATUS_SEQ_UNEXP_SEEN, __IFLA_BRIDGE_CFM_CC_PEER_STATUS_MAX, }; #define IFLA_BRIDGE_CFM_CC_PEER_STATUS_MAX (__IFLA_BRIDGE_CFM_CC_PEER_STATUS_MAX - 1) enum { IFLA_BRIDGE_MST_UNSPEC, IFLA_BRIDGE_MST_ENTRY, __IFLA_BRIDGE_MST_MAX, }; #define IFLA_BRIDGE_MST_MAX (__IFLA_BRIDGE_MST_MAX - 1) enum { IFLA_BRIDGE_MST_ENTRY_UNSPEC, IFLA_BRIDGE_MST_ENTRY_MSTI, IFLA_BRIDGE_MST_ENTRY_STATE, __IFLA_BRIDGE_MST_ENTRY_MAX, }; #define IFLA_BRIDGE_MST_ENTRY_MAX (__IFLA_BRIDGE_MST_ENTRY_MAX - 1) struct bridge_stp_xstats { __u64 transition_blk; __u64 transition_fwd; __u64 rx_bpdu; __u64 tx_bpdu; __u64 rx_tcn; __u64 tx_tcn; }; /* Bridge vlan RTM header */ struct br_vlan_msg { __u8 family; __u8 reserved1; __u16 reserved2; __u32 ifindex; }; enum { BRIDGE_VLANDB_DUMP_UNSPEC, BRIDGE_VLANDB_DUMP_FLAGS, __BRIDGE_VLANDB_DUMP_MAX, }; #define BRIDGE_VLANDB_DUMP_MAX (__BRIDGE_VLANDB_DUMP_MAX - 1) /* flags used in BRIDGE_VLANDB_DUMP_FLAGS attribute to affect dumps */ #define BRIDGE_VLANDB_DUMPF_STATS (1 << 0) /* Include stats in the dump */ #define BRIDGE_VLANDB_DUMPF_GLOBAL (1 << 1) /* Dump global vlan options only */ /* Bridge vlan RTM attributes * [BRIDGE_VLANDB_ENTRY] = { * [BRIDGE_VLANDB_ENTRY_INFO] * ... * } * [BRIDGE_VLANDB_GLOBAL_OPTIONS] = { * [BRIDGE_VLANDB_GOPTS_ID] * ... * } */ enum { BRIDGE_VLANDB_UNSPEC, BRIDGE_VLANDB_ENTRY, BRIDGE_VLANDB_GLOBAL_OPTIONS, __BRIDGE_VLANDB_MAX, }; #define BRIDGE_VLANDB_MAX (__BRIDGE_VLANDB_MAX - 1) enum { BRIDGE_VLANDB_ENTRY_UNSPEC, BRIDGE_VLANDB_ENTRY_INFO, BRIDGE_VLANDB_ENTRY_RANGE, BRIDGE_VLANDB_ENTRY_STATE, BRIDGE_VLANDB_ENTRY_TUNNEL_INFO, BRIDGE_VLANDB_ENTRY_STATS, BRIDGE_VLANDB_ENTRY_MCAST_ROUTER, __BRIDGE_VLANDB_ENTRY_MAX, }; #define BRIDGE_VLANDB_ENTRY_MAX (__BRIDGE_VLANDB_ENTRY_MAX - 1) /* [BRIDGE_VLANDB_ENTRY] = { * [BRIDGE_VLANDB_ENTRY_TUNNEL_INFO] = { * [BRIDGE_VLANDB_TINFO_ID] * ... * } * } */ enum { BRIDGE_VLANDB_TINFO_UNSPEC, BRIDGE_VLANDB_TINFO_ID, BRIDGE_VLANDB_TINFO_CMD, __BRIDGE_VLANDB_TINFO_MAX, }; #define BRIDGE_VLANDB_TINFO_MAX (__BRIDGE_VLANDB_TINFO_MAX - 1) /* [BRIDGE_VLANDB_ENTRY] = { * [BRIDGE_VLANDB_ENTRY_STATS] = { * [BRIDGE_VLANDB_STATS_RX_BYTES] * ... * } * ... * } */ enum { BRIDGE_VLANDB_STATS_UNSPEC, BRIDGE_VLANDB_STATS_RX_BYTES, BRIDGE_VLANDB_STATS_RX_PACKETS, BRIDGE_VLANDB_STATS_TX_BYTES, BRIDGE_VLANDB_STATS_TX_PACKETS, BRIDGE_VLANDB_STATS_PAD, __BRIDGE_VLANDB_STATS_MAX, }; #define BRIDGE_VLANDB_STATS_MAX (__BRIDGE_VLANDB_STATS_MAX - 1) enum { BRIDGE_VLANDB_GOPTS_UNSPEC, BRIDGE_VLANDB_GOPTS_ID, BRIDGE_VLANDB_GOPTS_RANGE, BRIDGE_VLANDB_GOPTS_MCAST_SNOOPING, BRIDGE_VLANDB_GOPTS_MCAST_IGMP_VERSION, BRIDGE_VLANDB_GOPTS_MCAST_MLD_VERSION, BRIDGE_VLANDB_GOPTS_MCAST_LAST_MEMBER_CNT, BRIDGE_VLANDB_GOPTS_MCAST_STARTUP_QUERY_CNT, BRIDGE_VLANDB_GOPTS_MCAST_LAST_MEMBER_INTVL, BRIDGE_VLANDB_GOPTS_PAD, BRIDGE_VLANDB_GOPTS_MCAST_MEMBERSHIP_INTVL, BRIDGE_VLANDB_GOPTS_MCAST_QUERIER_INTVL, BRIDGE_VLANDB_GOPTS_MCAST_QUERY_INTVL, BRIDGE_VLANDB_GOPTS_MCAST_QUERY_RESPONSE_INTVL, BRIDGE_VLANDB_GOPTS_MCAST_STARTUP_QUERY_INTVL, BRIDGE_VLANDB_GOPTS_MCAST_QUERIER, BRIDGE_VLANDB_GOPTS_MCAST_ROUTER_PORTS, BRIDGE_VLANDB_GOPTS_MCAST_QUERIER_STATE, BRIDGE_VLANDB_GOPTS_MSTI, __BRIDGE_VLANDB_GOPTS_MAX }; #define BRIDGE_VLANDB_GOPTS_MAX (__BRIDGE_VLANDB_GOPTS_MAX - 1) /* Bridge multicast database attributes * [MDBA_MDB] = { * [MDBA_MDB_ENTRY] = { * [MDBA_MDB_ENTRY_INFO] { * struct br_mdb_entry * [MDBA_MDB_EATTR attributes] * } * } * } * [MDBA_ROUTER] = { * [MDBA_ROUTER_PORT] = { * u32 ifindex * [MDBA_ROUTER_PATTR attributes] * } * } */ enum { MDBA_UNSPEC, MDBA_MDB, MDBA_ROUTER, __MDBA_MAX, }; #define MDBA_MAX (__MDBA_MAX - 1) enum { MDBA_MDB_UNSPEC, MDBA_MDB_ENTRY, __MDBA_MDB_MAX, }; #define MDBA_MDB_MAX (__MDBA_MDB_MAX - 1) enum { MDBA_MDB_ENTRY_UNSPEC, MDBA_MDB_ENTRY_INFO, __MDBA_MDB_ENTRY_MAX, }; #define MDBA_MDB_ENTRY_MAX (__MDBA_MDB_ENTRY_MAX - 1) /* per mdb entry additional attributes */ enum { MDBA_MDB_EATTR_UNSPEC, MDBA_MDB_EATTR_TIMER, MDBA_MDB_EATTR_SRC_LIST, MDBA_MDB_EATTR_GROUP_MODE, MDBA_MDB_EATTR_SOURCE, MDBA_MDB_EATTR_RTPROT, __MDBA_MDB_EATTR_MAX }; #define MDBA_MDB_EATTR_MAX (__MDBA_MDB_EATTR_MAX - 1) /* per mdb entry source */ enum { MDBA_MDB_SRCLIST_UNSPEC, MDBA_MDB_SRCLIST_ENTRY, __MDBA_MDB_SRCLIST_MAX }; #define MDBA_MDB_SRCLIST_MAX (__MDBA_MDB_SRCLIST_MAX - 1) /* per mdb entry per source attributes * these are embedded in MDBA_MDB_SRCLIST_ENTRY */ enum { MDBA_MDB_SRCATTR_UNSPEC, MDBA_MDB_SRCATTR_ADDRESS, MDBA_MDB_SRCATTR_TIMER, __MDBA_MDB_SRCATTR_MAX }; #define MDBA_MDB_SRCATTR_MAX (__MDBA_MDB_SRCATTR_MAX - 1) /* multicast router types */ enum { MDB_RTR_TYPE_DISABLED, MDB_RTR_TYPE_TEMP_QUERY, MDB_RTR_TYPE_PERM, MDB_RTR_TYPE_TEMP }; enum { MDBA_ROUTER_UNSPEC, MDBA_ROUTER_PORT, __MDBA_ROUTER_MAX, }; #define MDBA_ROUTER_MAX (__MDBA_ROUTER_MAX - 1) /* router port attributes */ enum { MDBA_ROUTER_PATTR_UNSPEC, MDBA_ROUTER_PATTR_TIMER, MDBA_ROUTER_PATTR_TYPE, MDBA_ROUTER_PATTR_INET_TIMER, MDBA_ROUTER_PATTR_INET6_TIMER, MDBA_ROUTER_PATTR_VID, __MDBA_ROUTER_PATTR_MAX }; #define MDBA_ROUTER_PATTR_MAX (__MDBA_ROUTER_PATTR_MAX - 1) struct br_port_msg { __u8 family; __u32 ifindex; }; struct br_mdb_entry { __u32 ifindex; #define MDB_TEMPORARY 0 #define MDB_PERMANENT 1 __u8 state; #define MDB_FLAGS_OFFLOAD (1 << 0) #define MDB_FLAGS_FAST_LEAVE (1 << 1) #define MDB_FLAGS_STAR_EXCL (1 << 2) #define MDB_FLAGS_BLOCKED (1 << 3) __u8 flags; __u16 vid; struct { union { __be32 ip4; struct in6_addr ip6; unsigned char mac_addr[ETH_ALEN]; } u; __be16 proto; } addr; }; enum { MDBA_SET_ENTRY_UNSPEC, MDBA_SET_ENTRY, MDBA_SET_ENTRY_ATTRS, __MDBA_SET_ENTRY_MAX, }; #define MDBA_SET_ENTRY_MAX (__MDBA_SET_ENTRY_MAX - 1) /* [MDBA_SET_ENTRY_ATTRS] = { * [MDBE_ATTR_xxx] * ... * } */ enum { MDBE_ATTR_UNSPEC, MDBE_ATTR_SOURCE, MDBE_ATTR_SRC_LIST, MDBE_ATTR_GROUP_MODE, MDBE_ATTR_RTPROT, __MDBE_ATTR_MAX, }; #define MDBE_ATTR_MAX (__MDBE_ATTR_MAX - 1) /* per mdb entry source */ enum { MDBE_SRC_LIST_UNSPEC, MDBE_SRC_LIST_ENTRY, __MDBE_SRC_LIST_MAX, }; #define MDBE_SRC_LIST_MAX (__MDBE_SRC_LIST_MAX - 1) /* per mdb entry per source attributes * these are embedded in MDBE_SRC_LIST_ENTRY */ enum { MDBE_SRCATTR_UNSPEC, MDBE_SRCATTR_ADDRESS, __MDBE_SRCATTR_MAX, }; #define MDBE_SRCATTR_MAX (__MDBE_SRCATTR_MAX - 1) /* Embedded inside LINK_XSTATS_TYPE_BRIDGE */ enum { BRIDGE_XSTATS_UNSPEC, BRIDGE_XSTATS_VLAN, BRIDGE_XSTATS_MCAST, BRIDGE_XSTATS_PAD, BRIDGE_XSTATS_STP, __BRIDGE_XSTATS_MAX }; #define BRIDGE_XSTATS_MAX (__BRIDGE_XSTATS_MAX - 1) enum { BR_MCAST_DIR_RX, BR_MCAST_DIR_TX, BR_MCAST_DIR_SIZE }; /* IGMP/MLD statistics */ struct br_mcast_stats { __u64 igmp_v1queries[BR_MCAST_DIR_SIZE]; __u64 igmp_v2queries[BR_MCAST_DIR_SIZE]; __u64 igmp_v3queries[BR_MCAST_DIR_SIZE]; __u64 igmp_leaves[BR_MCAST_DIR_SIZE]; __u64 igmp_v1reports[BR_MCAST_DIR_SIZE]; __u64 igmp_v2reports[BR_MCAST_DIR_SIZE]; __u64 igmp_v3reports[BR_MCAST_DIR_SIZE]; __u64 igmp_parse_errors; __u64 mld_v1queries[BR_MCAST_DIR_SIZE]; __u64 mld_v2queries[BR_MCAST_DIR_SIZE]; __u64 mld_leaves[BR_MCAST_DIR_SIZE]; __u64 mld_v1reports[BR_MCAST_DIR_SIZE]; __u64 mld_v2reports[BR_MCAST_DIR_SIZE]; __u64 mld_parse_errors; __u64 mcast_bytes[BR_MCAST_DIR_SIZE]; __u64 mcast_packets[BR_MCAST_DIR_SIZE]; }; /* bridge boolean options * BR_BOOLOPT_NO_LL_LEARN - disable learning from link-local packets * BR_BOOLOPT_MCAST_VLAN_SNOOPING - control vlan multicast snooping * * IMPORTANT: if adding a new option do not forget to handle * it in br_boolopt_toggle/get and bridge sysfs */ enum br_boolopt_id { BR_BOOLOPT_NO_LL_LEARN, BR_BOOLOPT_MCAST_VLAN_SNOOPING, BR_BOOLOPT_MST_ENABLE, BR_BOOLOPT_MAX }; /* struct br_boolopt_multi - change multiple bridge boolean options * * @optval: new option values (bit per option) * @optmask: options to change (bit per option) */ struct br_boolopt_multi { __u32 optval; __u32 optmask; }; enum { BRIDGE_QUERIER_UNSPEC, BRIDGE_QUERIER_IP_ADDRESS, BRIDGE_QUERIER_IP_PORT, BRIDGE_QUERIER_IP_OTHER_TIMER, BRIDGE_QUERIER_PAD, BRIDGE_QUERIER_IPV6_ADDRESS, BRIDGE_QUERIER_IPV6_PORT, BRIDGE_QUERIER_IPV6_OTHER_TIMER, __BRIDGE_QUERIER_MAX }; #define BRIDGE_QUERIER_MAX (__BRIDGE_QUERIER_MAX - 1) #endif /* _UAPI_LINUX_IF_BRIDGE_H */
19,964
23.141475
85
h
null
systemd-main/src/basic/linux/if_ether.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Global definitions for the Ethernet IEEE 802.3 interface. * * Version: @(#)if_ether.h 1.0.1a 02/08/94 * * Author: Fred N. van Kempen, <[email protected]> * Donald Becker, <[email protected]> * Alan Cox, <[email protected]> * Steve Whitehouse, <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _UAPI_LINUX_IF_ETHER_H #define _UAPI_LINUX_IF_ETHER_H #include <linux/types.h> /* * IEEE 802.3 Ethernet magic constants. The frame sizes omit the preamble * and FCS/CRC (frame check sequence). */ #define ETH_ALEN 6 /* Octets in one ethernet addr */ #define ETH_TLEN 2 /* Octets in ethernet type field */ #define ETH_HLEN 14 /* Total octets in header. */ #define ETH_ZLEN 60 /* Min. octets in frame sans FCS */ #define ETH_DATA_LEN 1500 /* Max. octets in payload */ #define ETH_FRAME_LEN 1514 /* Max. octets in frame sans FCS */ #define ETH_FCS_LEN 4 /* Octets in the FCS */ #define ETH_MIN_MTU 68 /* Min IPv4 MTU per RFC791 */ #define ETH_MAX_MTU 0xFFFFU /* 65535, same as IP_MAX_MTU */ /* * These are the defined Ethernet Protocol ID's. */ #define ETH_P_LOOP 0x0060 /* Ethernet Loopback packet */ #define ETH_P_PUP 0x0200 /* Xerox PUP packet */ #define ETH_P_PUPAT 0x0201 /* Xerox PUP Addr Trans packet */ #define ETH_P_TSN 0x22F0 /* TSN (IEEE 1722) packet */ #define ETH_P_ERSPAN2 0x22EB /* ERSPAN version 2 (type III) */ #define ETH_P_IP 0x0800 /* Internet Protocol packet */ #define ETH_P_X25 0x0805 /* CCITT X.25 */ #define ETH_P_ARP 0x0806 /* Address Resolution packet */ #define ETH_P_BPQ 0x08FF /* G8BPQ AX.25 Ethernet Packet [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_IEEEPUP 0x0a00 /* Xerox IEEE802.3 PUP packet */ #define ETH_P_IEEEPUPAT 0x0a01 /* Xerox IEEE802.3 PUP Addr Trans packet */ #define ETH_P_BATMAN 0x4305 /* B.A.T.M.A.N.-Advanced packet [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_DEC 0x6000 /* DEC Assigned proto */ #define ETH_P_DNA_DL 0x6001 /* DEC DNA Dump/Load */ #define ETH_P_DNA_RC 0x6002 /* DEC DNA Remote Console */ #define ETH_P_DNA_RT 0x6003 /* DEC DNA Routing */ #define ETH_P_LAT 0x6004 /* DEC LAT */ #define ETH_P_DIAG 0x6005 /* DEC Diagnostics */ #define ETH_P_CUST 0x6006 /* DEC Customer use */ #define ETH_P_SCA 0x6007 /* DEC Systems Comms Arch */ #define ETH_P_TEB 0x6558 /* Trans Ether Bridging */ #define ETH_P_RARP 0x8035 /* Reverse Addr Res packet */ #define ETH_P_ATALK 0x809B /* Appletalk DDP */ #define ETH_P_AARP 0x80F3 /* Appletalk AARP */ #define ETH_P_8021Q 0x8100 /* 802.1Q VLAN Extended Header */ #define ETH_P_ERSPAN 0x88BE /* ERSPAN type II */ #define ETH_P_IPX 0x8137 /* IPX over DIX */ #define ETH_P_IPV6 0x86DD /* IPv6 over bluebook */ #define ETH_P_PAUSE 0x8808 /* IEEE Pause frames. See 802.3 31B */ #define ETH_P_SLOW 0x8809 /* Slow Protocol. See 802.3ad 43B */ #define ETH_P_WCCP 0x883E /* Web-cache coordination protocol * defined in draft-wilson-wrec-wccp-v2-00.txt */ #define ETH_P_MPLS_UC 0x8847 /* MPLS Unicast traffic */ #define ETH_P_MPLS_MC 0x8848 /* MPLS Multicast traffic */ #define ETH_P_ATMMPOA 0x884c /* MultiProtocol Over ATM */ #define ETH_P_PPP_DISC 0x8863 /* PPPoE discovery messages */ #define ETH_P_PPP_SES 0x8864 /* PPPoE session messages */ #define ETH_P_LINK_CTL 0x886c /* HPNA, wlan link local tunnel */ #define ETH_P_ATMFATE 0x8884 /* Frame-based ATM Transport * over Ethernet */ #define ETH_P_PAE 0x888E /* Port Access Entity (IEEE 802.1X) */ #define ETH_P_PROFINET 0x8892 /* PROFINET */ #define ETH_P_REALTEK 0x8899 /* Multiple proprietary protocols */ #define ETH_P_AOE 0x88A2 /* ATA over Ethernet */ #define ETH_P_ETHERCAT 0x88A4 /* EtherCAT */ #define ETH_P_8021AD 0x88A8 /* 802.1ad Service VLAN */ #define ETH_P_802_EX1 0x88B5 /* 802.1 Local Experimental 1. */ #define ETH_P_PREAUTH 0x88C7 /* 802.11 Preauthentication */ #define ETH_P_TIPC 0x88CA /* TIPC */ #define ETH_P_LLDP 0x88CC /* Link Layer Discovery Protocol */ #define ETH_P_MRP 0x88E3 /* Media Redundancy Protocol */ #define ETH_P_MACSEC 0x88E5 /* 802.1ae MACsec */ #define ETH_P_8021AH 0x88E7 /* 802.1ah Backbone Service Tag */ #define ETH_P_MVRP 0x88F5 /* 802.1Q MVRP */ #define ETH_P_1588 0x88F7 /* IEEE 1588 Timesync */ #define ETH_P_NCSI 0x88F8 /* NCSI protocol */ #define ETH_P_PRP 0x88FB /* IEC 62439-3 PRP/HSRv0 */ #define ETH_P_CFM 0x8902 /* Connectivity Fault Management */ #define ETH_P_FCOE 0x8906 /* Fibre Channel over Ethernet */ #define ETH_P_IBOE 0x8915 /* Infiniband over Ethernet */ #define ETH_P_TDLS 0x890D /* TDLS */ #define ETH_P_FIP 0x8914 /* FCoE Initialization Protocol */ #define ETH_P_80221 0x8917 /* IEEE 802.21 Media Independent Handover Protocol */ #define ETH_P_HSR 0x892F /* IEC 62439-3 HSRv1 */ #define ETH_P_NSH 0x894F /* Network Service Header */ #define ETH_P_LOOPBACK 0x9000 /* Ethernet loopback packet, per IEEE 802.3 */ #define ETH_P_QINQ1 0x9100 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_QINQ2 0x9200 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_QINQ3 0x9300 /* deprecated QinQ VLAN [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_EDSA 0xDADA /* Ethertype DSA [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_DSA_8021Q 0xDADB /* Fake VLAN Header for DSA [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_DSA_A5PSW 0xE001 /* A5PSW Tag Value [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_IFE 0xED3E /* ForCES inter-FE LFB type */ #define ETH_P_AF_IUCV 0xFBFB /* IBM af_iucv [ NOT AN OFFICIALLY REGISTERED ID ] */ #define ETH_P_802_3_MIN 0x0600 /* If the value in the ethernet type is more than this value * then the frame is Ethernet II. Else it is 802.3 */ /* * Non DIX types. Won't clash for 1500 types. */ #define ETH_P_802_3 0x0001 /* Dummy type for 802.3 frames */ #define ETH_P_AX25 0x0002 /* Dummy protocol id for AX.25 */ #define ETH_P_ALL 0x0003 /* Every packet (be careful!!!) */ #define ETH_P_802_2 0x0004 /* 802.2 frames */ #define ETH_P_SNAP 0x0005 /* Internal only */ #define ETH_P_DDCMP 0x0006 /* DEC DDCMP: Internal only */ #define ETH_P_WAN_PPP 0x0007 /* Dummy type for WAN PPP frames*/ #define ETH_P_PPP_MP 0x0008 /* Dummy type for PPP MP frames */ #define ETH_P_LOCALTALK 0x0009 /* Localtalk pseudo type */ #define ETH_P_CAN 0x000C /* CAN: Controller Area Network */ #define ETH_P_CANFD 0x000D /* CANFD: CAN flexible data rate*/ #define ETH_P_CANXL 0x000E /* CANXL: eXtended frame Length */ #define ETH_P_PPPTALK 0x0010 /* Dummy type for Atalk over PPP*/ #define ETH_P_TR_802_2 0x0011 /* 802.2 frames */ #define ETH_P_MOBITEX 0x0015 /* Mobitex ([email protected]) */ #define ETH_P_CONTROL 0x0016 /* Card specific control frames */ #define ETH_P_IRDA 0x0017 /* Linux-IrDA */ #define ETH_P_ECONET 0x0018 /* Acorn Econet */ #define ETH_P_HDLC 0x0019 /* HDLC frames */ #define ETH_P_ARCNET 0x001A /* 1A for ArcNet :-) */ #define ETH_P_DSA 0x001B /* Distributed Switch Arch. */ #define ETH_P_TRAILER 0x001C /* Trailer switch tagging */ #define ETH_P_PHONET 0x00F5 /* Nokia Phonet frames */ #define ETH_P_IEEE802154 0x00F6 /* IEEE802.15.4 frame */ #define ETH_P_CAIF 0x00F7 /* ST-Ericsson CAIF protocol */ #define ETH_P_XDSA 0x00F8 /* Multiplexed DSA protocol */ #define ETH_P_MAP 0x00F9 /* Qualcomm multiplexing and * aggregation protocol */ #define ETH_P_MCTP 0x00FA /* Management component transport * protocol packets */ /* * This is an Ethernet frame header. */ /* allow libcs like musl to deactivate this, glibc does not implement this. */ #ifndef __UAPI_DEF_ETHHDR #define __UAPI_DEF_ETHHDR 1 #endif #if __UAPI_DEF_ETHHDR struct ethhdr { unsigned char h_dest[ETH_ALEN]; /* destination eth addr */ unsigned char h_source[ETH_ALEN]; /* source ether addr */ __be16 h_proto; /* packet type ID field */ } __attribute__((packed)); #endif #endif /* _UAPI_LINUX_IF_ETHER_H */
8,781
47.252747
99
h
null
systemd-main/src/basic/linux/if_macsec.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * include/uapi/linux/if_macsec.h - MACsec device * * Copyright (c) 2015 Sabrina Dubroca <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. */ #ifndef _UAPI_MACSEC_H #define _UAPI_MACSEC_H #include <linux/types.h> #define MACSEC_GENL_NAME "macsec" #define MACSEC_GENL_VERSION 1 #define MACSEC_MAX_KEY_LEN 128 #define MACSEC_KEYID_LEN 16 #define MACSEC_SALT_LEN 12 /* cipher IDs as per IEEE802.1AE-2018 (Table 14-1) */ #define MACSEC_CIPHER_ID_GCM_AES_128 0x0080C20001000001ULL #define MACSEC_CIPHER_ID_GCM_AES_256 0x0080C20001000002ULL #define MACSEC_CIPHER_ID_GCM_AES_XPN_128 0x0080C20001000003ULL #define MACSEC_CIPHER_ID_GCM_AES_XPN_256 0x0080C20001000004ULL /* deprecated cipher ID for GCM-AES-128 */ #define MACSEC_DEFAULT_CIPHER_ID 0x0080020001000001ULL #define MACSEC_DEFAULT_CIPHER_ALT MACSEC_CIPHER_ID_GCM_AES_128 #define MACSEC_MIN_ICV_LEN 8 #define MACSEC_MAX_ICV_LEN 32 /* upper limit for ICV length as recommended by IEEE802.1AE-2006 */ #define MACSEC_STD_ICV_LEN 16 enum macsec_attrs { MACSEC_ATTR_UNSPEC, MACSEC_ATTR_IFINDEX, /* u32, ifindex of the MACsec netdevice */ MACSEC_ATTR_RXSC_CONFIG, /* config, nested macsec_rxsc_attrs */ MACSEC_ATTR_SA_CONFIG, /* config, nested macsec_sa_attrs */ MACSEC_ATTR_SECY, /* dump, nested macsec_secy_attrs */ MACSEC_ATTR_TXSA_LIST, /* dump, nested, macsec_sa_attrs for each TXSA */ MACSEC_ATTR_RXSC_LIST, /* dump, nested, macsec_rxsc_attrs for each RXSC */ MACSEC_ATTR_TXSC_STATS, /* dump, nested, macsec_txsc_stats_attr */ MACSEC_ATTR_SECY_STATS, /* dump, nested, macsec_secy_stats_attr */ MACSEC_ATTR_OFFLOAD, /* config, nested, macsec_offload_attrs */ __MACSEC_ATTR_END, NUM_MACSEC_ATTR = __MACSEC_ATTR_END, MACSEC_ATTR_MAX = __MACSEC_ATTR_END - 1, }; enum macsec_secy_attrs { MACSEC_SECY_ATTR_UNSPEC, MACSEC_SECY_ATTR_SCI, MACSEC_SECY_ATTR_ENCODING_SA, MACSEC_SECY_ATTR_WINDOW, MACSEC_SECY_ATTR_CIPHER_SUITE, MACSEC_SECY_ATTR_ICV_LEN, MACSEC_SECY_ATTR_PROTECT, MACSEC_SECY_ATTR_REPLAY, MACSEC_SECY_ATTR_OPER, MACSEC_SECY_ATTR_VALIDATE, MACSEC_SECY_ATTR_ENCRYPT, MACSEC_SECY_ATTR_INC_SCI, MACSEC_SECY_ATTR_ES, MACSEC_SECY_ATTR_SCB, MACSEC_SECY_ATTR_PAD, __MACSEC_SECY_ATTR_END, NUM_MACSEC_SECY_ATTR = __MACSEC_SECY_ATTR_END, MACSEC_SECY_ATTR_MAX = __MACSEC_SECY_ATTR_END - 1, }; enum macsec_rxsc_attrs { MACSEC_RXSC_ATTR_UNSPEC, MACSEC_RXSC_ATTR_SCI, /* config/dump, u64 */ MACSEC_RXSC_ATTR_ACTIVE, /* config/dump, u8 0..1 */ MACSEC_RXSC_ATTR_SA_LIST, /* dump, nested */ MACSEC_RXSC_ATTR_STATS, /* dump, nested, macsec_rxsc_stats_attr */ MACSEC_RXSC_ATTR_PAD, __MACSEC_RXSC_ATTR_END, NUM_MACSEC_RXSC_ATTR = __MACSEC_RXSC_ATTR_END, MACSEC_RXSC_ATTR_MAX = __MACSEC_RXSC_ATTR_END - 1, }; enum macsec_sa_attrs { MACSEC_SA_ATTR_UNSPEC, MACSEC_SA_ATTR_AN, /* config/dump, u8 0..3 */ MACSEC_SA_ATTR_ACTIVE, /* config/dump, u8 0..1 */ MACSEC_SA_ATTR_PN, /* config/dump, u32/u64 (u64 if XPN) */ MACSEC_SA_ATTR_KEY, /* config, data */ MACSEC_SA_ATTR_KEYID, /* config/dump, 128-bit */ MACSEC_SA_ATTR_STATS, /* dump, nested, macsec_sa_stats_attr */ MACSEC_SA_ATTR_PAD, MACSEC_SA_ATTR_SSCI, /* config/dump, u32 - XPN only */ MACSEC_SA_ATTR_SALT, /* config, 96-bit - XPN only */ __MACSEC_SA_ATTR_END, NUM_MACSEC_SA_ATTR = __MACSEC_SA_ATTR_END, MACSEC_SA_ATTR_MAX = __MACSEC_SA_ATTR_END - 1, }; enum macsec_offload_attrs { MACSEC_OFFLOAD_ATTR_UNSPEC, MACSEC_OFFLOAD_ATTR_TYPE, /* config/dump, u8 0..2 */ MACSEC_OFFLOAD_ATTR_PAD, __MACSEC_OFFLOAD_ATTR_END, NUM_MACSEC_OFFLOAD_ATTR = __MACSEC_OFFLOAD_ATTR_END, MACSEC_OFFLOAD_ATTR_MAX = __MACSEC_OFFLOAD_ATTR_END - 1, }; enum macsec_nl_commands { MACSEC_CMD_GET_TXSC, MACSEC_CMD_ADD_RXSC, MACSEC_CMD_DEL_RXSC, MACSEC_CMD_UPD_RXSC, MACSEC_CMD_ADD_TXSA, MACSEC_CMD_DEL_TXSA, MACSEC_CMD_UPD_TXSA, MACSEC_CMD_ADD_RXSA, MACSEC_CMD_DEL_RXSA, MACSEC_CMD_UPD_RXSA, MACSEC_CMD_UPD_OFFLOAD, }; /* u64 per-RXSC stats */ enum macsec_rxsc_stats_attr { MACSEC_RXSC_STATS_ATTR_UNSPEC, MACSEC_RXSC_STATS_ATTR_IN_OCTETS_VALIDATED, MACSEC_RXSC_STATS_ATTR_IN_OCTETS_DECRYPTED, MACSEC_RXSC_STATS_ATTR_IN_PKTS_UNCHECKED, MACSEC_RXSC_STATS_ATTR_IN_PKTS_DELAYED, MACSEC_RXSC_STATS_ATTR_IN_PKTS_OK, MACSEC_RXSC_STATS_ATTR_IN_PKTS_INVALID, MACSEC_RXSC_STATS_ATTR_IN_PKTS_LATE, MACSEC_RXSC_STATS_ATTR_IN_PKTS_NOT_VALID, MACSEC_RXSC_STATS_ATTR_IN_PKTS_NOT_USING_SA, MACSEC_RXSC_STATS_ATTR_IN_PKTS_UNUSED_SA, MACSEC_RXSC_STATS_ATTR_PAD, __MACSEC_RXSC_STATS_ATTR_END, NUM_MACSEC_RXSC_STATS_ATTR = __MACSEC_RXSC_STATS_ATTR_END, MACSEC_RXSC_STATS_ATTR_MAX = __MACSEC_RXSC_STATS_ATTR_END - 1, }; /* u32 per-{RX,TX}SA stats */ enum macsec_sa_stats_attr { MACSEC_SA_STATS_ATTR_UNSPEC, MACSEC_SA_STATS_ATTR_IN_PKTS_OK, MACSEC_SA_STATS_ATTR_IN_PKTS_INVALID, MACSEC_SA_STATS_ATTR_IN_PKTS_NOT_VALID, MACSEC_SA_STATS_ATTR_IN_PKTS_NOT_USING_SA, MACSEC_SA_STATS_ATTR_IN_PKTS_UNUSED_SA, MACSEC_SA_STATS_ATTR_OUT_PKTS_PROTECTED, MACSEC_SA_STATS_ATTR_OUT_PKTS_ENCRYPTED, __MACSEC_SA_STATS_ATTR_END, NUM_MACSEC_SA_STATS_ATTR = __MACSEC_SA_STATS_ATTR_END, MACSEC_SA_STATS_ATTR_MAX = __MACSEC_SA_STATS_ATTR_END - 1, }; /* u64 per-TXSC stats */ enum macsec_txsc_stats_attr { MACSEC_TXSC_STATS_ATTR_UNSPEC, MACSEC_TXSC_STATS_ATTR_OUT_PKTS_PROTECTED, MACSEC_TXSC_STATS_ATTR_OUT_PKTS_ENCRYPTED, MACSEC_TXSC_STATS_ATTR_OUT_OCTETS_PROTECTED, MACSEC_TXSC_STATS_ATTR_OUT_OCTETS_ENCRYPTED, MACSEC_TXSC_STATS_ATTR_PAD, __MACSEC_TXSC_STATS_ATTR_END, NUM_MACSEC_TXSC_STATS_ATTR = __MACSEC_TXSC_STATS_ATTR_END, MACSEC_TXSC_STATS_ATTR_MAX = __MACSEC_TXSC_STATS_ATTR_END - 1, }; /* u64 per-SecY stats */ enum macsec_secy_stats_attr { MACSEC_SECY_STATS_ATTR_UNSPEC, MACSEC_SECY_STATS_ATTR_OUT_PKTS_UNTAGGED, MACSEC_SECY_STATS_ATTR_IN_PKTS_UNTAGGED, MACSEC_SECY_STATS_ATTR_OUT_PKTS_TOO_LONG, MACSEC_SECY_STATS_ATTR_IN_PKTS_NO_TAG, MACSEC_SECY_STATS_ATTR_IN_PKTS_BAD_TAG, MACSEC_SECY_STATS_ATTR_IN_PKTS_UNKNOWN_SCI, MACSEC_SECY_STATS_ATTR_IN_PKTS_NO_SCI, MACSEC_SECY_STATS_ATTR_IN_PKTS_OVERRUN, MACSEC_SECY_STATS_ATTR_PAD, __MACSEC_SECY_STATS_ATTR_END, NUM_MACSEC_SECY_STATS_ATTR = __MACSEC_SECY_STATS_ATTR_END, MACSEC_SECY_STATS_ATTR_MAX = __MACSEC_SECY_STATS_ATTR_END - 1, }; #endif /* _UAPI_MACSEC_H */
6,518
32.430769
77
h
null
systemd-main/src/basic/linux/if_tun.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Universal TUN/TAP device driver. * Copyright (C) 1999-2000 Maxim Krasnyansky <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef _UAPI__IF_TUN_H #define _UAPI__IF_TUN_H #include <linux/types.h> #include <linux/if_ether.h> #include <linux/filter.h> /* Read queue size */ #define TUN_READQ_SIZE 500 /* TUN device type flags: deprecated. Use IFF_TUN/IFF_TAP instead. */ #define TUN_TUN_DEV IFF_TUN #define TUN_TAP_DEV IFF_TAP #define TUN_TYPE_MASK 0x000f /* Ioctl defines */ #define TUNSETNOCSUM _IOW('T', 200, int) #define TUNSETDEBUG _IOW('T', 201, int) #define TUNSETIFF _IOW('T', 202, int) #define TUNSETPERSIST _IOW('T', 203, int) #define TUNSETOWNER _IOW('T', 204, int) #define TUNSETLINK _IOW('T', 205, int) #define TUNSETGROUP _IOW('T', 206, int) #define TUNGETFEATURES _IOR('T', 207, unsigned int) #define TUNSETOFFLOAD _IOW('T', 208, unsigned int) #define TUNSETTXFILTER _IOW('T', 209, unsigned int) #define TUNGETIFF _IOR('T', 210, unsigned int) #define TUNGETSNDBUF _IOR('T', 211, int) #define TUNSETSNDBUF _IOW('T', 212, int) #define TUNATTACHFILTER _IOW('T', 213, struct sock_fprog) #define TUNDETACHFILTER _IOW('T', 214, struct sock_fprog) #define TUNGETVNETHDRSZ _IOR('T', 215, int) #define TUNSETVNETHDRSZ _IOW('T', 216, int) #define TUNSETQUEUE _IOW('T', 217, int) #define TUNSETIFINDEX _IOW('T', 218, unsigned int) #define TUNGETFILTER _IOR('T', 219, struct sock_fprog) #define TUNSETVNETLE _IOW('T', 220, int) #define TUNGETVNETLE _IOR('T', 221, int) /* The TUNSETVNETBE and TUNGETVNETBE ioctls are for cross-endian support on * little-endian hosts. Not all kernel configurations support them, but all * configurations that support SET also support GET. */ #define TUNSETVNETBE _IOW('T', 222, int) #define TUNGETVNETBE _IOR('T', 223, int) #define TUNSETSTEERINGEBPF _IOR('T', 224, int) #define TUNSETFILTEREBPF _IOR('T', 225, int) #define TUNSETCARRIER _IOW('T', 226, int) #define TUNGETDEVNETNS _IO('T', 227) /* TUNSETIFF ifr flags */ #define IFF_TUN 0x0001 #define IFF_TAP 0x0002 #define IFF_NAPI 0x0010 #define IFF_NAPI_FRAGS 0x0020 /* Used in TUNSETIFF to bring up tun/tap without carrier */ #define IFF_NO_CARRIER 0x0040 #define IFF_NO_PI 0x1000 /* This flag has no real effect */ #define IFF_ONE_QUEUE 0x2000 #define IFF_VNET_HDR 0x4000 #define IFF_TUN_EXCL 0x8000 #define IFF_MULTI_QUEUE 0x0100 #define IFF_ATTACH_QUEUE 0x0200 #define IFF_DETACH_QUEUE 0x0400 /* read-only flag */ #define IFF_PERSIST 0x0800 #define IFF_NOFILTER 0x1000 /* Socket options */ #define TUN_TX_TIMESTAMP 1 /* Features for GSO (TUNSETOFFLOAD). */ #define TUN_F_CSUM 0x01 /* You can hand me unchecksummed packets. */ #define TUN_F_TSO4 0x02 /* I can handle TSO for IPv4 packets */ #define TUN_F_TSO6 0x04 /* I can handle TSO for IPv6 packets */ #define TUN_F_TSO_ECN 0x08 /* I can handle TSO with ECN bits. */ #define TUN_F_UFO 0x10 /* I can handle UFO packets */ #define TUN_F_USO4 0x20 /* I can handle USO for IPv4 packets */ #define TUN_F_USO6 0x40 /* I can handle USO for IPv6 packets */ /* Protocol info prepended to the packets (when IFF_NO_PI is not set) */ #define TUN_PKT_STRIP 0x0001 struct tun_pi { __u16 flags; __be16 proto; }; /* * Filter spec (used for SETXXFILTER ioctls) * This stuff is applicable only to the TAP (Ethernet) devices. * If the count is zero the filter is disabled and the driver accepts * all packets (promisc mode). * If the filter is enabled in order to accept broadcast packets * broadcast addr must be explicitly included in the addr list. */ #define TUN_FLT_ALLMULTI 0x0001 /* Accept all multicast packets */ struct tun_filter { __u16 flags; /* TUN_FLT_ flags see above */ __u16 count; /* Number of addresses */ __u8 addr[][ETH_ALEN]; }; #endif /* _UAPI__IF_TUN_H */
4,330
35.394958
75
h
null
systemd-main/src/basic/linux/if_tunnel.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _UAPI_IF_TUNNEL_H_ #define _UAPI_IF_TUNNEL_H_ #include <linux/types.h> #include <linux/if.h> #include <linux/ip.h> #include <linux/in6.h> #include <asm/byteorder.h> #define SIOCGETTUNNEL (SIOCDEVPRIVATE + 0) #define SIOCADDTUNNEL (SIOCDEVPRIVATE + 1) #define SIOCDELTUNNEL (SIOCDEVPRIVATE + 2) #define SIOCCHGTUNNEL (SIOCDEVPRIVATE + 3) #define SIOCGETPRL (SIOCDEVPRIVATE + 4) #define SIOCADDPRL (SIOCDEVPRIVATE + 5) #define SIOCDELPRL (SIOCDEVPRIVATE + 6) #define SIOCCHGPRL (SIOCDEVPRIVATE + 7) #define SIOCGET6RD (SIOCDEVPRIVATE + 8) #define SIOCADD6RD (SIOCDEVPRIVATE + 9) #define SIOCDEL6RD (SIOCDEVPRIVATE + 10) #define SIOCCHG6RD (SIOCDEVPRIVATE + 11) #define GRE_CSUM __cpu_to_be16(0x8000) #define GRE_ROUTING __cpu_to_be16(0x4000) #define GRE_KEY __cpu_to_be16(0x2000) #define GRE_SEQ __cpu_to_be16(0x1000) #define GRE_STRICT __cpu_to_be16(0x0800) #define GRE_REC __cpu_to_be16(0x0700) #define GRE_ACK __cpu_to_be16(0x0080) #define GRE_FLAGS __cpu_to_be16(0x0078) #define GRE_VERSION __cpu_to_be16(0x0007) #define GRE_IS_CSUM(f) ((f) & GRE_CSUM) #define GRE_IS_ROUTING(f) ((f) & GRE_ROUTING) #define GRE_IS_KEY(f) ((f) & GRE_KEY) #define GRE_IS_SEQ(f) ((f) & GRE_SEQ) #define GRE_IS_STRICT(f) ((f) & GRE_STRICT) #define GRE_IS_REC(f) ((f) & GRE_REC) #define GRE_IS_ACK(f) ((f) & GRE_ACK) #define GRE_VERSION_0 __cpu_to_be16(0x0000) #define GRE_VERSION_1 __cpu_to_be16(0x0001) #define GRE_PROTO_PPP __cpu_to_be16(0x880b) #define GRE_PPTP_KEY_MASK __cpu_to_be32(0xffff) struct ip_tunnel_parm { char name[IFNAMSIZ]; int link; __be16 i_flags; __be16 o_flags; __be32 i_key; __be32 o_key; struct iphdr iph; }; enum { IFLA_IPTUN_UNSPEC, IFLA_IPTUN_LINK, IFLA_IPTUN_LOCAL, IFLA_IPTUN_REMOTE, IFLA_IPTUN_TTL, IFLA_IPTUN_TOS, IFLA_IPTUN_ENCAP_LIMIT, IFLA_IPTUN_FLOWINFO, IFLA_IPTUN_FLAGS, IFLA_IPTUN_PROTO, IFLA_IPTUN_PMTUDISC, IFLA_IPTUN_6RD_PREFIX, IFLA_IPTUN_6RD_RELAY_PREFIX, IFLA_IPTUN_6RD_PREFIXLEN, IFLA_IPTUN_6RD_RELAY_PREFIXLEN, IFLA_IPTUN_ENCAP_TYPE, IFLA_IPTUN_ENCAP_FLAGS, IFLA_IPTUN_ENCAP_SPORT, IFLA_IPTUN_ENCAP_DPORT, IFLA_IPTUN_COLLECT_METADATA, IFLA_IPTUN_FWMARK, __IFLA_IPTUN_MAX, }; #define IFLA_IPTUN_MAX (__IFLA_IPTUN_MAX - 1) enum tunnel_encap_types { TUNNEL_ENCAP_NONE, TUNNEL_ENCAP_FOU, TUNNEL_ENCAP_GUE, TUNNEL_ENCAP_MPLS, }; #define TUNNEL_ENCAP_FLAG_CSUM (1<<0) #define TUNNEL_ENCAP_FLAG_CSUM6 (1<<1) #define TUNNEL_ENCAP_FLAG_REMCSUM (1<<2) /* SIT-mode i_flags */ #define SIT_ISATAP 0x0001 struct ip_tunnel_prl { __be32 addr; __u16 flags; __u16 __reserved; __u32 datalen; __u32 __reserved2; /* data follows */ }; /* PRL flags */ #define PRL_DEFAULT 0x0001 struct ip_tunnel_6rd { struct in6_addr prefix; __be32 relay_prefix; __u16 prefixlen; __u16 relay_prefixlen; }; enum { IFLA_GRE_UNSPEC, IFLA_GRE_LINK, IFLA_GRE_IFLAGS, IFLA_GRE_OFLAGS, IFLA_GRE_IKEY, IFLA_GRE_OKEY, IFLA_GRE_LOCAL, IFLA_GRE_REMOTE, IFLA_GRE_TTL, IFLA_GRE_TOS, IFLA_GRE_PMTUDISC, IFLA_GRE_ENCAP_LIMIT, IFLA_GRE_FLOWINFO, IFLA_GRE_FLAGS, IFLA_GRE_ENCAP_TYPE, IFLA_GRE_ENCAP_FLAGS, IFLA_GRE_ENCAP_SPORT, IFLA_GRE_ENCAP_DPORT, IFLA_GRE_COLLECT_METADATA, IFLA_GRE_IGNORE_DF, IFLA_GRE_FWMARK, IFLA_GRE_ERSPAN_INDEX, IFLA_GRE_ERSPAN_VER, IFLA_GRE_ERSPAN_DIR, IFLA_GRE_ERSPAN_HWID, __IFLA_GRE_MAX, }; #define IFLA_GRE_MAX (__IFLA_GRE_MAX - 1) /* VTI-mode i_flags */ #define VTI_ISVTI ((__force __be16)0x0001) enum { IFLA_VTI_UNSPEC, IFLA_VTI_LINK, IFLA_VTI_IKEY, IFLA_VTI_OKEY, IFLA_VTI_LOCAL, IFLA_VTI_REMOTE, IFLA_VTI_FWMARK, __IFLA_VTI_MAX, }; #define IFLA_VTI_MAX (__IFLA_VTI_MAX - 1) #define TUNNEL_CSUM __cpu_to_be16(0x01) #define TUNNEL_ROUTING __cpu_to_be16(0x02) #define TUNNEL_KEY __cpu_to_be16(0x04) #define TUNNEL_SEQ __cpu_to_be16(0x08) #define TUNNEL_STRICT __cpu_to_be16(0x10) #define TUNNEL_REC __cpu_to_be16(0x20) #define TUNNEL_VERSION __cpu_to_be16(0x40) #define TUNNEL_NO_KEY __cpu_to_be16(0x80) #define TUNNEL_DONT_FRAGMENT __cpu_to_be16(0x0100) #define TUNNEL_OAM __cpu_to_be16(0x0200) #define TUNNEL_CRIT_OPT __cpu_to_be16(0x0400) #define TUNNEL_GENEVE_OPT __cpu_to_be16(0x0800) #define TUNNEL_VXLAN_OPT __cpu_to_be16(0x1000) #define TUNNEL_NOCACHE __cpu_to_be16(0x2000) #define TUNNEL_ERSPAN_OPT __cpu_to_be16(0x4000) #define TUNNEL_GTP_OPT __cpu_to_be16(0x8000) #define TUNNEL_OPTIONS_PRESENT \ (TUNNEL_GENEVE_OPT | TUNNEL_VXLAN_OPT | TUNNEL_ERSPAN_OPT | \ TUNNEL_GTP_OPT) #endif /* _UAPI_IF_TUNNEL_H_ */
4,602
23.747312
63
h
null
systemd-main/src/basic/linux/in.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions of the Internet Protocol. * * Version: @(#)in.h 1.0.1 04/21/93 * * Authors: Original taken from the GNU Project <netinet/in.h> file. * Fred N. van Kempen, <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _UAPI_LINUX_IN_H #define _UAPI_LINUX_IN_H #include <linux/types.h> #include <linux/stddef.h> #include <linux/libc-compat.h> #include <linux/socket.h> #if __UAPI_DEF_IN_IPPROTO /* Standard well-defined IP protocols. */ enum { IPPROTO_IP = 0, /* Dummy protocol for TCP */ #define IPPROTO_IP IPPROTO_IP IPPROTO_ICMP = 1, /* Internet Control Message Protocol */ #define IPPROTO_ICMP IPPROTO_ICMP IPPROTO_IGMP = 2, /* Internet Group Management Protocol */ #define IPPROTO_IGMP IPPROTO_IGMP IPPROTO_IPIP = 4, /* IPIP tunnels (older KA9Q tunnels use 94) */ #define IPPROTO_IPIP IPPROTO_IPIP IPPROTO_TCP = 6, /* Transmission Control Protocol */ #define IPPROTO_TCP IPPROTO_TCP IPPROTO_EGP = 8, /* Exterior Gateway Protocol */ #define IPPROTO_EGP IPPROTO_EGP IPPROTO_PUP = 12, /* PUP protocol */ #define IPPROTO_PUP IPPROTO_PUP IPPROTO_UDP = 17, /* User Datagram Protocol */ #define IPPROTO_UDP IPPROTO_UDP IPPROTO_IDP = 22, /* XNS IDP protocol */ #define IPPROTO_IDP IPPROTO_IDP IPPROTO_TP = 29, /* SO Transport Protocol Class 4 */ #define IPPROTO_TP IPPROTO_TP IPPROTO_DCCP = 33, /* Datagram Congestion Control Protocol */ #define IPPROTO_DCCP IPPROTO_DCCP IPPROTO_IPV6 = 41, /* IPv6-in-IPv4 tunnelling */ #define IPPROTO_IPV6 IPPROTO_IPV6 IPPROTO_RSVP = 46, /* RSVP Protocol */ #define IPPROTO_RSVP IPPROTO_RSVP IPPROTO_GRE = 47, /* Cisco GRE tunnels (rfc 1701,1702) */ #define IPPROTO_GRE IPPROTO_GRE IPPROTO_ESP = 50, /* Encapsulation Security Payload protocol */ #define IPPROTO_ESP IPPROTO_ESP IPPROTO_AH = 51, /* Authentication Header protocol */ #define IPPROTO_AH IPPROTO_AH IPPROTO_MTP = 92, /* Multicast Transport Protocol */ #define IPPROTO_MTP IPPROTO_MTP IPPROTO_BEETPH = 94, /* IP option pseudo header for BEET */ #define IPPROTO_BEETPH IPPROTO_BEETPH IPPROTO_ENCAP = 98, /* Encapsulation Header */ #define IPPROTO_ENCAP IPPROTO_ENCAP IPPROTO_PIM = 103, /* Protocol Independent Multicast */ #define IPPROTO_PIM IPPROTO_PIM IPPROTO_COMP = 108, /* Compression Header Protocol */ #define IPPROTO_COMP IPPROTO_COMP IPPROTO_L2TP = 115, /* Layer 2 Tunnelling Protocol */ #define IPPROTO_L2TP IPPROTO_L2TP IPPROTO_SCTP = 132, /* Stream Control Transport Protocol */ #define IPPROTO_SCTP IPPROTO_SCTP IPPROTO_UDPLITE = 136, /* UDP-Lite (RFC 3828) */ #define IPPROTO_UDPLITE IPPROTO_UDPLITE IPPROTO_MPLS = 137, /* MPLS in IP (RFC 4023) */ #define IPPROTO_MPLS IPPROTO_MPLS IPPROTO_ETHERNET = 143, /* Ethernet-within-IPv6 Encapsulation */ #define IPPROTO_ETHERNET IPPROTO_ETHERNET IPPROTO_RAW = 255, /* Raw IP packets */ #define IPPROTO_RAW IPPROTO_RAW IPPROTO_MPTCP = 262, /* Multipath TCP connection */ #define IPPROTO_MPTCP IPPROTO_MPTCP IPPROTO_MAX }; #endif #if __UAPI_DEF_IN_ADDR /* Internet address. */ struct in_addr { __be32 s_addr; }; #endif #define IP_TOS 1 #define IP_TTL 2 #define IP_HDRINCL 3 #define IP_OPTIONS 4 #define IP_ROUTER_ALERT 5 #define IP_RECVOPTS 6 #define IP_RETOPTS 7 #define IP_PKTINFO 8 #define IP_PKTOPTIONS 9 #define IP_MTU_DISCOVER 10 #define IP_RECVERR 11 #define IP_RECVTTL 12 #define IP_RECVTOS 13 #define IP_MTU 14 #define IP_FREEBIND 15 #define IP_IPSEC_POLICY 16 #define IP_XFRM_POLICY 17 #define IP_PASSSEC 18 #define IP_TRANSPARENT 19 /* BSD compatibility */ #define IP_RECVRETOPTS IP_RETOPTS /* TProxy original addresses */ #define IP_ORIGDSTADDR 20 #define IP_RECVORIGDSTADDR IP_ORIGDSTADDR #define IP_MINTTL 21 #define IP_NODEFRAG 22 #define IP_CHECKSUM 23 #define IP_BIND_ADDRESS_NO_PORT 24 #define IP_RECVFRAGSIZE 25 #define IP_RECVERR_RFC4884 26 /* IP_MTU_DISCOVER values */ #define IP_PMTUDISC_DONT 0 /* Never send DF frames */ #define IP_PMTUDISC_WANT 1 /* Use per route hints */ #define IP_PMTUDISC_DO 2 /* Always DF */ #define IP_PMTUDISC_PROBE 3 /* Ignore dst pmtu */ /* Always use interface mtu (ignores dst pmtu) but don't set DF flag. * Also incoming ICMP frag_needed notifications will be ignored on * this socket to prevent accepting spoofed ones. */ #define IP_PMTUDISC_INTERFACE 4 /* weaker version of IP_PMTUDISC_INTERFACE, which allows packets to get * fragmented if they exeed the interface mtu */ #define IP_PMTUDISC_OMIT 5 #define IP_MULTICAST_IF 32 #define IP_MULTICAST_TTL 33 #define IP_MULTICAST_LOOP 34 #define IP_ADD_MEMBERSHIP 35 #define IP_DROP_MEMBERSHIP 36 #define IP_UNBLOCK_SOURCE 37 #define IP_BLOCK_SOURCE 38 #define IP_ADD_SOURCE_MEMBERSHIP 39 #define IP_DROP_SOURCE_MEMBERSHIP 40 #define IP_MSFILTER 41 #define MCAST_JOIN_GROUP 42 #define MCAST_BLOCK_SOURCE 43 #define MCAST_UNBLOCK_SOURCE 44 #define MCAST_LEAVE_GROUP 45 #define MCAST_JOIN_SOURCE_GROUP 46 #define MCAST_LEAVE_SOURCE_GROUP 47 #define MCAST_MSFILTER 48 #define IP_MULTICAST_ALL 49 #define IP_UNICAST_IF 50 #define MCAST_EXCLUDE 0 #define MCAST_INCLUDE 1 /* These need to appear somewhere around here */ #define IP_DEFAULT_MULTICAST_TTL 1 #define IP_DEFAULT_MULTICAST_LOOP 1 /* Request struct for multicast socket ops */ #if __UAPI_DEF_IP_MREQ struct ip_mreq { struct in_addr imr_multiaddr; /* IP multicast address of group */ struct in_addr imr_interface; /* local IP address of interface */ }; struct ip_mreqn { struct in_addr imr_multiaddr; /* IP multicast address of group */ struct in_addr imr_address; /* local IP address of interface */ int imr_ifindex; /* Interface index */ }; struct ip_mreq_source { __be32 imr_multiaddr; __be32 imr_interface; __be32 imr_sourceaddr; }; struct ip_msfilter { __be32 imsf_multiaddr; __be32 imsf_interface; __u32 imsf_fmode; __u32 imsf_numsrc; union { __be32 imsf_slist[1]; __DECLARE_FLEX_ARRAY(__be32, imsf_slist_flex); }; }; #define IP_MSFILTER_SIZE(numsrc) \ (sizeof(struct ip_msfilter) - sizeof(__u32) \ + (numsrc) * sizeof(__u32)) struct group_req { __u32 gr_interface; /* interface index */ struct __kernel_sockaddr_storage gr_group; /* group address */ }; struct group_source_req { __u32 gsr_interface; /* interface index */ struct __kernel_sockaddr_storage gsr_group; /* group address */ struct __kernel_sockaddr_storage gsr_source; /* source address */ }; struct group_filter { union { struct { __u32 gf_interface_aux; /* interface index */ struct __kernel_sockaddr_storage gf_group_aux; /* multicast address */ __u32 gf_fmode_aux; /* filter mode */ __u32 gf_numsrc_aux; /* number of sources */ struct __kernel_sockaddr_storage gf_slist[1]; /* interface index */ }; struct { __u32 gf_interface; /* interface index */ struct __kernel_sockaddr_storage gf_group; /* multicast address */ __u32 gf_fmode; /* filter mode */ __u32 gf_numsrc; /* number of sources */ struct __kernel_sockaddr_storage gf_slist_flex[]; /* interface index */ }; }; }; #define GROUP_FILTER_SIZE(numsrc) \ (sizeof(struct group_filter) - sizeof(struct __kernel_sockaddr_storage) \ + (numsrc) * sizeof(struct __kernel_sockaddr_storage)) #endif #if __UAPI_DEF_IN_PKTINFO struct in_pktinfo { int ipi_ifindex; struct in_addr ipi_spec_dst; struct in_addr ipi_addr; }; #endif /* Structure describing an Internet (IP) socket address. */ #if __UAPI_DEF_SOCKADDR_IN #define __SOCK_SIZE__ 16 /* sizeof(struct sockaddr) */ struct sockaddr_in { __kernel_sa_family_t sin_family; /* Address family */ __be16 sin_port; /* Port number */ struct in_addr sin_addr; /* Internet address */ /* Pad to size of `struct sockaddr'. */ unsigned char __pad[__SOCK_SIZE__ - sizeof(short int) - sizeof(unsigned short int) - sizeof(struct in_addr)]; }; #define sin_zero __pad /* for BSD UNIX comp. -FvK */ #endif #if __UAPI_DEF_IN_CLASS /* * Definitions of the bits in an Internet address integer. * On subnets, host and network parts are found according * to the subnet mask, not these masks. */ #define IN_CLASSA(a) ((((long int) (a)) & 0x80000000) == 0) #define IN_CLASSA_NET 0xff000000 #define IN_CLASSA_NSHIFT 24 #define IN_CLASSA_HOST (0xffffffff & ~IN_CLASSA_NET) #define IN_CLASSA_MAX 128 #define IN_CLASSB(a) ((((long int) (a)) & 0xc0000000) == 0x80000000) #define IN_CLASSB_NET 0xffff0000 #define IN_CLASSB_NSHIFT 16 #define IN_CLASSB_HOST (0xffffffff & ~IN_CLASSB_NET) #define IN_CLASSB_MAX 65536 #define IN_CLASSC(a) ((((long int) (a)) & 0xe0000000) == 0xc0000000) #define IN_CLASSC_NET 0xffffff00 #define IN_CLASSC_NSHIFT 8 #define IN_CLASSC_HOST (0xffffffff & ~IN_CLASSC_NET) #define IN_CLASSD(a) ((((long int) (a)) & 0xf0000000) == 0xe0000000) #define IN_MULTICAST(a) IN_CLASSD(a) #define IN_MULTICAST_NET 0xe0000000 #define IN_BADCLASS(a) (((long int) (a) ) == (long int)0xffffffff) #define IN_EXPERIMENTAL(a) IN_BADCLASS((a)) #define IN_CLASSE(a) ((((long int) (a)) & 0xf0000000) == 0xf0000000) #define IN_CLASSE_NET 0xffffffff #define IN_CLASSE_NSHIFT 0 /* Address to accept any incoming messages. */ #define INADDR_ANY ((unsigned long int) 0x00000000) /* Address to send to all hosts. */ #define INADDR_BROADCAST ((unsigned long int) 0xffffffff) /* Address indicating an error return. */ #define INADDR_NONE ((unsigned long int) 0xffffffff) /* Dummy address for src of ICMP replies if no real address is set (RFC7600). */ #define INADDR_DUMMY ((unsigned long int) 0xc0000008) /* Network number for local host loopback. */ #define IN_LOOPBACKNET 127 /* Address to loopback in software to local host. */ #define INADDR_LOOPBACK 0x7f000001 /* 127.0.0.1 */ #define IN_LOOPBACK(a) ((((long int) (a)) & 0xff000000) == 0x7f000000) /* Defines for Multicast INADDR */ #define INADDR_UNSPEC_GROUP 0xe0000000U /* 224.0.0.0 */ #define INADDR_ALLHOSTS_GROUP 0xe0000001U /* 224.0.0.1 */ #define INADDR_ALLRTRS_GROUP 0xe0000002U /* 224.0.0.2 */ #define INADDR_ALLSNOOPERS_GROUP 0xe000006aU /* 224.0.0.106 */ #define INADDR_MAX_LOCAL_GROUP 0xe00000ffU /* 224.0.0.255 */ #endif /* <asm/byteorder.h> contains the htonl type stuff.. */ #include <asm/byteorder.h> #endif /* _UAPI_LINUX_IN_H */
10,822
31.599398
80
h
null
systemd-main/src/basic/linux/in6.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Types and definitions for AF_INET6 * Linux INET6 implementation * * Authors: * Pedro Roque <[email protected]> * * Sources: * IPv6 Program Interfaces for BSD Systems * <draft-ietf-ipngwg-bsd-api-05.txt> * * Advanced Sockets API for IPv6 * <draft-stevens-advanced-api-00.txt> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _UAPI_LINUX_IN6_H #define _UAPI_LINUX_IN6_H #include <linux/types.h> #include <linux/libc-compat.h> /* * IPv6 address structure */ #if __UAPI_DEF_IN6_ADDR struct in6_addr { union { __u8 u6_addr8[16]; #if __UAPI_DEF_IN6_ADDR_ALT __be16 u6_addr16[8]; __be32 u6_addr32[4]; #endif } in6_u; #define s6_addr in6_u.u6_addr8 #if __UAPI_DEF_IN6_ADDR_ALT #define s6_addr16 in6_u.u6_addr16 #define s6_addr32 in6_u.u6_addr32 #endif }; #endif /* __UAPI_DEF_IN6_ADDR */ #if __UAPI_DEF_SOCKADDR_IN6 struct sockaddr_in6 { unsigned short int sin6_family; /* AF_INET6 */ __be16 sin6_port; /* Transport layer port # */ __be32 sin6_flowinfo; /* IPv6 flow information */ struct in6_addr sin6_addr; /* IPv6 address */ __u32 sin6_scope_id; /* scope id (new in RFC2553) */ }; #endif /* __UAPI_DEF_SOCKADDR_IN6 */ #if __UAPI_DEF_IPV6_MREQ struct ipv6_mreq { /* IPv6 multicast address of group */ struct in6_addr ipv6mr_multiaddr; /* local IPv6 address of interface */ int ipv6mr_ifindex; }; #endif /* __UAPI_DEF_IVP6_MREQ */ #define ipv6mr_acaddr ipv6mr_multiaddr struct in6_flowlabel_req { struct in6_addr flr_dst; __be32 flr_label; __u8 flr_action; __u8 flr_share; __u16 flr_flags; __u16 flr_expires; __u16 flr_linger; __u32 __flr_pad; /* Options in format of IPV6_PKTOPTIONS */ }; #define IPV6_FL_A_GET 0 #define IPV6_FL_A_PUT 1 #define IPV6_FL_A_RENEW 2 #define IPV6_FL_F_CREATE 1 #define IPV6_FL_F_EXCL 2 #define IPV6_FL_F_REFLECT 4 #define IPV6_FL_F_REMOTE 8 #define IPV6_FL_S_NONE 0 #define IPV6_FL_S_EXCL 1 #define IPV6_FL_S_PROCESS 2 #define IPV6_FL_S_USER 3 #define IPV6_FL_S_ANY 255 /* * Bitmask constant declarations to help applications select out the * flow label and priority fields. * * Note that this are in host byte order while the flowinfo field of * sockaddr_in6 is in network byte order. */ #define IPV6_FLOWINFO_FLOWLABEL 0x000fffff #define IPV6_FLOWINFO_PRIORITY 0x0ff00000 /* These definitions are obsolete */ #define IPV6_PRIORITY_UNCHARACTERIZED 0x0000 #define IPV6_PRIORITY_FILLER 0x0100 #define IPV6_PRIORITY_UNATTENDED 0x0200 #define IPV6_PRIORITY_RESERVED1 0x0300 #define IPV6_PRIORITY_BULK 0x0400 #define IPV6_PRIORITY_RESERVED2 0x0500 #define IPV6_PRIORITY_INTERACTIVE 0x0600 #define IPV6_PRIORITY_CONTROL 0x0700 #define IPV6_PRIORITY_8 0x0800 #define IPV6_PRIORITY_9 0x0900 #define IPV6_PRIORITY_10 0x0a00 #define IPV6_PRIORITY_11 0x0b00 #define IPV6_PRIORITY_12 0x0c00 #define IPV6_PRIORITY_13 0x0d00 #define IPV6_PRIORITY_14 0x0e00 #define IPV6_PRIORITY_15 0x0f00 /* * IPV6 extension headers */ #if __UAPI_DEF_IPPROTO_V6 #define IPPROTO_HOPOPTS 0 /* IPv6 hop-by-hop options */ #define IPPROTO_ROUTING 43 /* IPv6 routing header */ #define IPPROTO_FRAGMENT 44 /* IPv6 fragmentation header */ #define IPPROTO_ICMPV6 58 /* ICMPv6 */ #define IPPROTO_NONE 59 /* IPv6 no next header */ #define IPPROTO_DSTOPTS 60 /* IPv6 destination options */ #define IPPROTO_MH 135 /* IPv6 mobility header */ #endif /* __UAPI_DEF_IPPROTO_V6 */ /* * IPv6 TLV options. */ #define IPV6_TLV_PAD1 0 #define IPV6_TLV_PADN 1 #define IPV6_TLV_ROUTERALERT 5 #define IPV6_TLV_CALIPSO 7 /* RFC 5570 */ #define IPV6_TLV_IOAM 49 /* TEMPORARY IANA allocation for IOAM */ #define IPV6_TLV_JUMBO 194 #define IPV6_TLV_HAO 201 /* home address option */ /* * IPV6 socket options */ #if __UAPI_DEF_IPV6_OPTIONS #define IPV6_ADDRFORM 1 #define IPV6_2292PKTINFO 2 #define IPV6_2292HOPOPTS 3 #define IPV6_2292DSTOPTS 4 #define IPV6_2292RTHDR 5 #define IPV6_2292PKTOPTIONS 6 #define IPV6_CHECKSUM 7 #define IPV6_2292HOPLIMIT 8 #define IPV6_NEXTHOP 9 #define IPV6_AUTHHDR 10 /* obsolete */ #define IPV6_FLOWINFO 11 #define IPV6_UNICAST_HOPS 16 #define IPV6_MULTICAST_IF 17 #define IPV6_MULTICAST_HOPS 18 #define IPV6_MULTICAST_LOOP 19 #define IPV6_ADD_MEMBERSHIP 20 #define IPV6_DROP_MEMBERSHIP 21 #define IPV6_ROUTER_ALERT 22 #define IPV6_MTU_DISCOVER 23 #define IPV6_MTU 24 #define IPV6_RECVERR 25 #define IPV6_V6ONLY 26 #define IPV6_JOIN_ANYCAST 27 #define IPV6_LEAVE_ANYCAST 28 #define IPV6_MULTICAST_ALL 29 #define IPV6_ROUTER_ALERT_ISOLATE 30 #define IPV6_RECVERR_RFC4884 31 /* IPV6_MTU_DISCOVER values */ #define IPV6_PMTUDISC_DONT 0 #define IPV6_PMTUDISC_WANT 1 #define IPV6_PMTUDISC_DO 2 #define IPV6_PMTUDISC_PROBE 3 /* same as IPV6_PMTUDISC_PROBE, provided for symetry with IPv4 * also see comments on IP_PMTUDISC_INTERFACE */ #define IPV6_PMTUDISC_INTERFACE 4 /* weaker version of IPV6_PMTUDISC_INTERFACE, which allows packets to * get fragmented if they exceed the interface mtu */ #define IPV6_PMTUDISC_OMIT 5 /* Flowlabel */ #define IPV6_FLOWLABEL_MGR 32 #define IPV6_FLOWINFO_SEND 33 #define IPV6_IPSEC_POLICY 34 #define IPV6_XFRM_POLICY 35 #define IPV6_HDRINCL 36 #endif /* * Multicast: * Following socket options are shared between IPv4 and IPv6. * * MCAST_JOIN_GROUP 42 * MCAST_BLOCK_SOURCE 43 * MCAST_UNBLOCK_SOURCE 44 * MCAST_LEAVE_GROUP 45 * MCAST_JOIN_SOURCE_GROUP 46 * MCAST_LEAVE_SOURCE_GROUP 47 * MCAST_MSFILTER 48 */ /* * Advanced API (RFC3542) (1) * * Note: IPV6_RECVRTHDRDSTOPTS does not exist. see net/ipv6/datagram.c. */ #define IPV6_RECVPKTINFO 49 #define IPV6_PKTINFO 50 #define IPV6_RECVHOPLIMIT 51 #define IPV6_HOPLIMIT 52 #define IPV6_RECVHOPOPTS 53 #define IPV6_HOPOPTS 54 #define IPV6_RTHDRDSTOPTS 55 #define IPV6_RECVRTHDR 56 #define IPV6_RTHDR 57 #define IPV6_RECVDSTOPTS 58 #define IPV6_DSTOPTS 59 #define IPV6_RECVPATHMTU 60 #define IPV6_PATHMTU 61 #define IPV6_DONTFRAG 62 #if 0 /* not yet */ #define IPV6_USE_MIN_MTU 63 #endif /* * Netfilter (1) * * Following socket options are used in ip6_tables; * see include/linux/netfilter_ipv6/ip6_tables.h. * * IP6T_SO_SET_REPLACE / IP6T_SO_GET_INFO 64 * IP6T_SO_SET_ADD_COUNTERS / IP6T_SO_GET_ENTRIES 65 */ /* * Advanced API (RFC3542) (2) */ #define IPV6_RECVTCLASS 66 #define IPV6_TCLASS 67 /* * Netfilter (2) * * Following socket options are used in ip6_tables; * see include/linux/netfilter_ipv6/ip6_tables.h. * * IP6T_SO_GET_REVISION_MATCH 68 * IP6T_SO_GET_REVISION_TARGET 69 * IP6T_SO_ORIGINAL_DST 80 */ #define IPV6_AUTOFLOWLABEL 70 /* RFC5014: Source address selection */ #define IPV6_ADDR_PREFERENCES 72 #define IPV6_PREFER_SRC_TMP 0x0001 #define IPV6_PREFER_SRC_PUBLIC 0x0002 #define IPV6_PREFER_SRC_PUBTMP_DEFAULT 0x0100 #define IPV6_PREFER_SRC_COA 0x0004 #define IPV6_PREFER_SRC_HOME 0x0400 #define IPV6_PREFER_SRC_CGA 0x0008 #define IPV6_PREFER_SRC_NONCGA 0x0800 /* RFC5082: Generalized Ttl Security Mechanism */ #define IPV6_MINHOPCOUNT 73 #define IPV6_ORIGDSTADDR 74 #define IPV6_RECVORIGDSTADDR IPV6_ORIGDSTADDR #define IPV6_TRANSPARENT 75 #define IPV6_UNICAST_IF 76 #define IPV6_RECVFRAGSIZE 77 #define IPV6_FREEBIND 78 /* * Multicast Routing: * see include/uapi/linux/mroute6.h. * * MRT6_BASE 200 * ... * MRT6_MAX */ #endif /* _UAPI_LINUX_IN6_H */
7,619
24.148515
71
h
null
systemd-main/src/basic/linux/ipv6_route.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * Linux INET6 implementation * * Authors: * Pedro Roque <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. */ #ifndef _UAPI_LINUX_IPV6_ROUTE_H #define _UAPI_LINUX_IPV6_ROUTE_H #include <linux/types.h> #include <linux/in6.h> /* For struct in6_addr. */ #define RTF_DEFAULT 0x00010000 /* default - learned via ND */ #define RTF_ALLONLINK 0x00020000 /* (deprecated and will be removed) fallback, no routers on link */ #define RTF_ADDRCONF 0x00040000 /* addrconf route - RA */ #define RTF_PREFIX_RT 0x00080000 /* A prefix only route - RA */ #define RTF_ANYCAST 0x00100000 /* Anycast */ #define RTF_NONEXTHOP 0x00200000 /* route with no nexthop */ #define RTF_EXPIRES 0x00400000 #define RTF_ROUTEINFO 0x00800000 /* route information - RA */ #define RTF_CACHE 0x01000000 /* read-only: can not be set by user */ #define RTF_FLOW 0x02000000 /* flow significant route */ #define RTF_POLICY 0x04000000 /* policy route */ #define RTF_PREF(pref) ((pref) << 27) #define RTF_PREF_MASK 0x18000000 #define RTF_PCPU 0x40000000 /* read-only: can not be set by user */ #define RTF_LOCAL 0x80000000 struct in6_rtmsg { struct in6_addr rtmsg_dst; struct in6_addr rtmsg_src; struct in6_addr rtmsg_gateway; __u32 rtmsg_type; __u16 rtmsg_dst_len; __u16 rtmsg_src_len; __u32 rtmsg_metric; unsigned long rtmsg_info; __u32 rtmsg_flags; int rtmsg_ifindex; }; #define RTMSG_NEWDEVICE 0x11 #define RTMSG_DELDEVICE 0x12 #define RTMSG_NEWROUTE 0x21 #define RTMSG_DELROUTE 0x22 #define IP6_RT_PRIO_USER 1024 #define IP6_RT_PRIO_ADDRCONF 256 #endif /* _UAPI_LINUX_IPV6_ROUTE_H */
1,923
28.6
68
h
null
systemd-main/src/basic/linux/l2tp.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * L2TP-over-IP socket for L2TPv3. * * Author: James Chapman <[email protected]> */ #ifndef _UAPI_LINUX_L2TP_H_ #define _UAPI_LINUX_L2TP_H_ #include <linux/types.h> #include <linux/socket.h> #include <linux/in.h> #include <linux/in6.h> /** * struct sockaddr_l2tpip - the sockaddr structure for L2TP-over-IP sockets * @l2tp_family: address family number AF_L2TPIP. * @l2tp_addr: protocol specific address information * @l2tp_conn_id: connection id of tunnel */ #define __SOCK_SIZE__ 16 /* sizeof(struct sockaddr) */ struct sockaddr_l2tpip { /* The first fields must match struct sockaddr_in */ __kernel_sa_family_t l2tp_family; /* AF_INET */ __be16 l2tp_unused; /* INET port number (unused) */ struct in_addr l2tp_addr; /* Internet address */ __u32 l2tp_conn_id; /* Connection ID of tunnel */ /* Pad to size of `struct sockaddr'. */ unsigned char __pad[__SOCK_SIZE__ - sizeof(__kernel_sa_family_t) - sizeof(__be16) - sizeof(struct in_addr) - sizeof(__u32)]; }; /** * struct sockaddr_l2tpip6 - the sockaddr structure for L2TP-over-IPv6 sockets * @l2tp_family: address family number AF_L2TPIP. * @l2tp_addr: protocol specific address information * @l2tp_conn_id: connection id of tunnel */ struct sockaddr_l2tpip6 { /* The first fields must match struct sockaddr_in6 */ __kernel_sa_family_t l2tp_family; /* AF_INET6 */ __be16 l2tp_unused; /* INET port number (unused) */ __be32 l2tp_flowinfo; /* IPv6 flow information */ struct in6_addr l2tp_addr; /* IPv6 address */ __u32 l2tp_scope_id; /* scope id (new in RFC2553) */ __u32 l2tp_conn_id; /* Connection ID of tunnel */ }; /***************************************************************************** * NETLINK_GENERIC netlink family. *****************************************************************************/ /* * Commands. * Valid TLVs of each command are:- * TUNNEL_CREATE - CONN_ID, pw_type, netns, ifname, ipinfo, udpinfo, udpcsum * TUNNEL_DELETE - CONN_ID * TUNNEL_MODIFY - CONN_ID, udpcsum * TUNNEL_GETSTATS - CONN_ID, (stats) * TUNNEL_GET - CONN_ID, (...) * SESSION_CREATE - SESSION_ID, PW_TYPE, cookie, peer_cookie, l2spec * SESSION_DELETE - SESSION_ID * SESSION_MODIFY - SESSION_ID * SESSION_GET - SESSION_ID, (...) * SESSION_GETSTATS - SESSION_ID, (stats) * */ enum { L2TP_CMD_NOOP, L2TP_CMD_TUNNEL_CREATE, L2TP_CMD_TUNNEL_DELETE, L2TP_CMD_TUNNEL_MODIFY, L2TP_CMD_TUNNEL_GET, L2TP_CMD_SESSION_CREATE, L2TP_CMD_SESSION_DELETE, L2TP_CMD_SESSION_MODIFY, L2TP_CMD_SESSION_GET, __L2TP_CMD_MAX, }; #define L2TP_CMD_MAX (__L2TP_CMD_MAX - 1) /* * ATTR types defined for L2TP */ enum { L2TP_ATTR_NONE, /* no data */ L2TP_ATTR_PW_TYPE, /* u16, enum l2tp_pwtype */ L2TP_ATTR_ENCAP_TYPE, /* u16, enum l2tp_encap_type */ L2TP_ATTR_OFFSET, /* u16 (not used) */ L2TP_ATTR_DATA_SEQ, /* u16 (not used) */ L2TP_ATTR_L2SPEC_TYPE, /* u8, enum l2tp_l2spec_type */ L2TP_ATTR_L2SPEC_LEN, /* u8 (not used) */ L2TP_ATTR_PROTO_VERSION, /* u8 */ L2TP_ATTR_IFNAME, /* string */ L2TP_ATTR_CONN_ID, /* u32 */ L2TP_ATTR_PEER_CONN_ID, /* u32 */ L2TP_ATTR_SESSION_ID, /* u32 */ L2TP_ATTR_PEER_SESSION_ID, /* u32 */ L2TP_ATTR_UDP_CSUM, /* u8 */ L2TP_ATTR_VLAN_ID, /* u16 (not used) */ L2TP_ATTR_COOKIE, /* 0, 4 or 8 bytes */ L2TP_ATTR_PEER_COOKIE, /* 0, 4 or 8 bytes */ L2TP_ATTR_DEBUG, /* u32, enum l2tp_debug_flags (not used) */ L2TP_ATTR_RECV_SEQ, /* u8 */ L2TP_ATTR_SEND_SEQ, /* u8 */ L2TP_ATTR_LNS_MODE, /* u8 */ L2TP_ATTR_USING_IPSEC, /* u8 */ L2TP_ATTR_RECV_TIMEOUT, /* msec */ L2TP_ATTR_FD, /* int */ L2TP_ATTR_IP_SADDR, /* u32 */ L2TP_ATTR_IP_DADDR, /* u32 */ L2TP_ATTR_UDP_SPORT, /* u16 */ L2TP_ATTR_UDP_DPORT, /* u16 */ L2TP_ATTR_MTU, /* u16 (not used) */ L2TP_ATTR_MRU, /* u16 (not used) */ L2TP_ATTR_STATS, /* nested */ L2TP_ATTR_IP6_SADDR, /* struct in6_addr */ L2TP_ATTR_IP6_DADDR, /* struct in6_addr */ L2TP_ATTR_UDP_ZERO_CSUM6_TX, /* flag */ L2TP_ATTR_UDP_ZERO_CSUM6_RX, /* flag */ L2TP_ATTR_PAD, __L2TP_ATTR_MAX, }; #define L2TP_ATTR_MAX (__L2TP_ATTR_MAX - 1) /* Nested in L2TP_ATTR_STATS */ enum { L2TP_ATTR_STATS_NONE, /* no data */ L2TP_ATTR_TX_PACKETS, /* u64 */ L2TP_ATTR_TX_BYTES, /* u64 */ L2TP_ATTR_TX_ERRORS, /* u64 */ L2TP_ATTR_RX_PACKETS, /* u64 */ L2TP_ATTR_RX_BYTES, /* u64 */ L2TP_ATTR_RX_SEQ_DISCARDS, /* u64 */ L2TP_ATTR_RX_OOS_PACKETS, /* u64 */ L2TP_ATTR_RX_ERRORS, /* u64 */ L2TP_ATTR_STATS_PAD, L2TP_ATTR_RX_COOKIE_DISCARDS, /* u64 */ L2TP_ATTR_RX_INVALID, /* u64 */ __L2TP_ATTR_STATS_MAX, }; #define L2TP_ATTR_STATS_MAX (__L2TP_ATTR_STATS_MAX - 1) enum l2tp_pwtype { L2TP_PWTYPE_NONE = 0x0000, L2TP_PWTYPE_ETH_VLAN = 0x0004, L2TP_PWTYPE_ETH = 0x0005, L2TP_PWTYPE_PPP = 0x0007, L2TP_PWTYPE_PPP_AC = 0x0008, L2TP_PWTYPE_IP = 0x000b, __L2TP_PWTYPE_MAX }; enum l2tp_l2spec_type { L2TP_L2SPECTYPE_NONE, L2TP_L2SPECTYPE_DEFAULT, }; enum l2tp_encap_type { L2TP_ENCAPTYPE_UDP, L2TP_ENCAPTYPE_IP, }; /* For L2TP_ATTR_DATA_SEQ. Unused. */ enum l2tp_seqmode { L2TP_SEQ_NONE = 0, L2TP_SEQ_IP = 1, L2TP_SEQ_ALL = 2, }; /** * enum l2tp_debug_flags - debug message categories for L2TP tunnels/sessions. * * Unused. * * @L2TP_MSG_DEBUG: verbose debug (if compiled in) * @L2TP_MSG_CONTROL: userspace - kernel interface * @L2TP_MSG_SEQ: sequence numbers * @L2TP_MSG_DATA: data packets */ enum l2tp_debug_flags { L2TP_MSG_DEBUG = (1 << 0), L2TP_MSG_CONTROL = (1 << 1), L2TP_MSG_SEQ = (1 << 2), L2TP_MSG_DATA = (1 << 3), }; /* * NETLINK_GENERIC related info */ #define L2TP_GENL_NAME "l2tp" #define L2TP_GENL_VERSION 0x1 #define L2TP_GENL_MCGROUP "l2tp" #endif /* _UAPI_LINUX_L2TP_H_ */
5,761
27.245098
79
h
null
systemd-main/src/basic/linux/libc-compat.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ /* * Compatibility interface for userspace libc header coordination: * * Define compatibility macros that are used to control the inclusion or * exclusion of UAPI structures and definitions in coordination with another * userspace C library. * * This header is intended to solve the problem of UAPI definitions that * conflict with userspace definitions. If a UAPI header has such conflicting * definitions then the solution is as follows: * * * Synchronize the UAPI header and the libc headers so either one can be * used and such that the ABI is preserved. If this is not possible then * no simple compatibility interface exists (you need to write translating * wrappers and rename things) and you can't use this interface. * * Then follow this process: * * (a) Include libc-compat.h in the UAPI header. * e.g. #include <linux/libc-compat.h> * This include must be as early as possible. * * (b) In libc-compat.h add enough code to detect that the comflicting * userspace libc header has been included first. * * (c) If the userspace libc header has been included first define a set of * guard macros of the form __UAPI_DEF_FOO and set their values to 1, else * set their values to 0. * * (d) Back in the UAPI header with the conflicting definitions, guard the * definitions with: * #if __UAPI_DEF_FOO * ... * #endif * * This fixes the situation where the linux headers are included *after* the * libc headers. To fix the problem with the inclusion in the other order the * userspace libc headers must be fixed like this: * * * For all definitions that conflict with kernel definitions wrap those * defines in the following: * #if !__UAPI_DEF_FOO * ... * #endif * * This prevents the redefinition of a construct already defined by the kernel. */ #ifndef _UAPI_LIBC_COMPAT_H #define _UAPI_LIBC_COMPAT_H /* We have included glibc headers... */ #if defined(__GLIBC__) /* Coordinate with glibc net/if.h header. */ #if defined(_NET_IF_H) && defined(__USE_MISC) /* GLIBC headers included first so don't define anything * that would already be defined. */ #define __UAPI_DEF_IF_IFCONF 0 #define __UAPI_DEF_IF_IFMAP 0 #define __UAPI_DEF_IF_IFNAMSIZ 0 #define __UAPI_DEF_IF_IFREQ 0 /* Everything up to IFF_DYNAMIC, matches net/if.h until glibc 2.23 */ #define __UAPI_DEF_IF_NET_DEVICE_FLAGS 0 /* For the future if glibc adds IFF_LOWER_UP, IFF_DORMANT and IFF_ECHO */ #ifndef __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO #define __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO 1 #endif /* __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO */ #else /* _NET_IF_H */ /* Linux headers included first, and we must define everything * we need. The expectation is that glibc will check the * __UAPI_DEF_* defines and adjust appropriately. */ #define __UAPI_DEF_IF_IFCONF 1 #define __UAPI_DEF_IF_IFMAP 1 #define __UAPI_DEF_IF_IFNAMSIZ 1 #define __UAPI_DEF_IF_IFREQ 1 /* Everything up to IFF_DYNAMIC, matches net/if.h until glibc 2.23 */ #define __UAPI_DEF_IF_NET_DEVICE_FLAGS 1 /* For the future if glibc adds IFF_LOWER_UP, IFF_DORMANT and IFF_ECHO */ #define __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO 1 #endif /* _NET_IF_H */ /* Coordinate with glibc netinet/in.h header. */ #if defined(_NETINET_IN_H) /* GLIBC headers included first so don't define anything * that would already be defined. */ #define __UAPI_DEF_IN_ADDR 0 #define __UAPI_DEF_IN_IPPROTO 0 #define __UAPI_DEF_IN_PKTINFO 0 #define __UAPI_DEF_IP_MREQ 0 #define __UAPI_DEF_SOCKADDR_IN 0 #define __UAPI_DEF_IN_CLASS 0 #define __UAPI_DEF_IN6_ADDR 0 /* The exception is the in6_addr macros which must be defined * if the glibc code didn't define them. This guard matches * the guard in glibc/inet/netinet/in.h which defines the * additional in6_addr macros e.g. s6_addr16, and s6_addr32. */ #if defined(__USE_MISC) || defined (__USE_GNU) #define __UAPI_DEF_IN6_ADDR_ALT 0 #else #define __UAPI_DEF_IN6_ADDR_ALT 1 #endif #define __UAPI_DEF_SOCKADDR_IN6 0 #define __UAPI_DEF_IPV6_MREQ 0 #define __UAPI_DEF_IPPROTO_V6 0 #define __UAPI_DEF_IPV6_OPTIONS 0 #define __UAPI_DEF_IN6_PKTINFO 0 #define __UAPI_DEF_IP6_MTUINFO 0 #else /* Linux headers included first, and we must define everything * we need. The expectation is that glibc will check the * __UAPI_DEF_* defines and adjust appropriately. */ #define __UAPI_DEF_IN_ADDR 1 #define __UAPI_DEF_IN_IPPROTO 1 #define __UAPI_DEF_IN_PKTINFO 1 #define __UAPI_DEF_IP_MREQ 1 #define __UAPI_DEF_SOCKADDR_IN 1 #define __UAPI_DEF_IN_CLASS 1 #define __UAPI_DEF_IN6_ADDR 1 /* We unconditionally define the in6_addr macros and glibc must * coordinate. */ #define __UAPI_DEF_IN6_ADDR_ALT 1 #define __UAPI_DEF_SOCKADDR_IN6 1 #define __UAPI_DEF_IPV6_MREQ 1 #define __UAPI_DEF_IPPROTO_V6 1 #define __UAPI_DEF_IPV6_OPTIONS 1 #define __UAPI_DEF_IN6_PKTINFO 1 #define __UAPI_DEF_IP6_MTUINFO 1 #endif /* _NETINET_IN_H */ /* Coordinate with glibc netipx/ipx.h header. */ #if defined(__NETIPX_IPX_H) #define __UAPI_DEF_SOCKADDR_IPX 0 #define __UAPI_DEF_IPX_ROUTE_DEFINITION 0 #define __UAPI_DEF_IPX_INTERFACE_DEFINITION 0 #define __UAPI_DEF_IPX_CONFIG_DATA 0 #define __UAPI_DEF_IPX_ROUTE_DEF 0 #else /* defined(__NETIPX_IPX_H) */ #define __UAPI_DEF_SOCKADDR_IPX 1 #define __UAPI_DEF_IPX_ROUTE_DEFINITION 1 #define __UAPI_DEF_IPX_INTERFACE_DEFINITION 1 #define __UAPI_DEF_IPX_CONFIG_DATA 1 #define __UAPI_DEF_IPX_ROUTE_DEF 1 #endif /* defined(__NETIPX_IPX_H) */ /* Definitions for xattr.h */ #if defined(_SYS_XATTR_H) #define __UAPI_DEF_XATTR 0 #else #define __UAPI_DEF_XATTR 1 #endif /* If we did not see any headers from any supported C libraries, * or we are being included in the kernel, then define everything * that we need. Check for previous __UAPI_* definitions to give * unsupported C libraries a way to opt out of any kernel definition. */ #else /* !defined(__GLIBC__) */ /* Definitions for if.h */ #ifndef __UAPI_DEF_IF_IFCONF #define __UAPI_DEF_IF_IFCONF 1 #endif #ifndef __UAPI_DEF_IF_IFMAP #define __UAPI_DEF_IF_IFMAP 1 #endif #ifndef __UAPI_DEF_IF_IFNAMSIZ #define __UAPI_DEF_IF_IFNAMSIZ 1 #endif #ifndef __UAPI_DEF_IF_IFREQ #define __UAPI_DEF_IF_IFREQ 1 #endif /* Everything up to IFF_DYNAMIC, matches net/if.h until glibc 2.23 */ #ifndef __UAPI_DEF_IF_NET_DEVICE_FLAGS #define __UAPI_DEF_IF_NET_DEVICE_FLAGS 1 #endif /* For the future if glibc adds IFF_LOWER_UP, IFF_DORMANT and IFF_ECHO */ #ifndef __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO #define __UAPI_DEF_IF_NET_DEVICE_FLAGS_LOWER_UP_DORMANT_ECHO 1 #endif /* Definitions for in.h */ #ifndef __UAPI_DEF_IN_ADDR #define __UAPI_DEF_IN_ADDR 1 #endif #ifndef __UAPI_DEF_IN_IPPROTO #define __UAPI_DEF_IN_IPPROTO 1 #endif #ifndef __UAPI_DEF_IN_PKTINFO #define __UAPI_DEF_IN_PKTINFO 1 #endif #ifndef __UAPI_DEF_IP_MREQ #define __UAPI_DEF_IP_MREQ 1 #endif #ifndef __UAPI_DEF_SOCKADDR_IN #define __UAPI_DEF_SOCKADDR_IN 1 #endif #ifndef __UAPI_DEF_IN_CLASS #define __UAPI_DEF_IN_CLASS 1 #endif /* Definitions for in6.h */ #ifndef __UAPI_DEF_IN6_ADDR #define __UAPI_DEF_IN6_ADDR 1 #endif #ifndef __UAPI_DEF_IN6_ADDR_ALT #define __UAPI_DEF_IN6_ADDR_ALT 1 #endif #ifndef __UAPI_DEF_SOCKADDR_IN6 #define __UAPI_DEF_SOCKADDR_IN6 1 #endif #ifndef __UAPI_DEF_IPV6_MREQ #define __UAPI_DEF_IPV6_MREQ 1 #endif #ifndef __UAPI_DEF_IPPROTO_V6 #define __UAPI_DEF_IPPROTO_V6 1 #endif #ifndef __UAPI_DEF_IPV6_OPTIONS #define __UAPI_DEF_IPV6_OPTIONS 1 #endif #ifndef __UAPI_DEF_IN6_PKTINFO #define __UAPI_DEF_IN6_PKTINFO 1 #endif #ifndef __UAPI_DEF_IP6_MTUINFO #define __UAPI_DEF_IP6_MTUINFO 1 #endif /* Definitions for ipx.h */ #ifndef __UAPI_DEF_SOCKADDR_IPX #define __UAPI_DEF_SOCKADDR_IPX 1 #endif #ifndef __UAPI_DEF_IPX_ROUTE_DEFINITION #define __UAPI_DEF_IPX_ROUTE_DEFINITION 1 #endif #ifndef __UAPI_DEF_IPX_INTERFACE_DEFINITION #define __UAPI_DEF_IPX_INTERFACE_DEFINITION 1 #endif #ifndef __UAPI_DEF_IPX_CONFIG_DATA #define __UAPI_DEF_IPX_CONFIG_DATA 1 #endif #ifndef __UAPI_DEF_IPX_ROUTE_DEF #define __UAPI_DEF_IPX_ROUTE_DEF 1 #endif /* Definitions for xattr.h */ #ifndef __UAPI_DEF_XATTR #define __UAPI_DEF_XATTR 1 #endif #endif /* __GLIBC__ */ #endif /* _UAPI_LIBC_COMPAT_H */
8,304
29.988806
79
h
null
systemd-main/src/basic/linux/mrp_bridge.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ #ifndef _UAPI_LINUX_MRP_BRIDGE_H_ #define _UAPI_LINUX_MRP_BRIDGE_H_ #include <linux/types.h> #include <linux/if_ether.h> #define MRP_MAX_FRAME_LENGTH 200 #define MRP_DEFAULT_PRIO 0x8000 #define MRP_DOMAIN_UUID_LENGTH 16 #define MRP_VERSION 1 #define MRP_FRAME_PRIO 7 #define MRP_OUI_LENGTH 3 #define MRP_MANUFACTURE_DATA_LENGTH 2 enum br_mrp_ring_role_type { BR_MRP_RING_ROLE_DISABLED, BR_MRP_RING_ROLE_MRC, BR_MRP_RING_ROLE_MRM, BR_MRP_RING_ROLE_MRA, }; enum br_mrp_in_role_type { BR_MRP_IN_ROLE_DISABLED, BR_MRP_IN_ROLE_MIC, BR_MRP_IN_ROLE_MIM, }; enum br_mrp_ring_state_type { BR_MRP_RING_STATE_OPEN, BR_MRP_RING_STATE_CLOSED, }; enum br_mrp_in_state_type { BR_MRP_IN_STATE_OPEN, BR_MRP_IN_STATE_CLOSED, }; enum br_mrp_port_state_type { BR_MRP_PORT_STATE_DISABLED, BR_MRP_PORT_STATE_BLOCKED, BR_MRP_PORT_STATE_FORWARDING, BR_MRP_PORT_STATE_NOT_CONNECTED, }; enum br_mrp_port_role_type { BR_MRP_PORT_ROLE_PRIMARY, BR_MRP_PORT_ROLE_SECONDARY, BR_MRP_PORT_ROLE_INTER, }; enum br_mrp_tlv_header_type { BR_MRP_TLV_HEADER_END = 0x0, BR_MRP_TLV_HEADER_COMMON = 0x1, BR_MRP_TLV_HEADER_RING_TEST = 0x2, BR_MRP_TLV_HEADER_RING_TOPO = 0x3, BR_MRP_TLV_HEADER_RING_LINK_DOWN = 0x4, BR_MRP_TLV_HEADER_RING_LINK_UP = 0x5, BR_MRP_TLV_HEADER_IN_TEST = 0x6, BR_MRP_TLV_HEADER_IN_TOPO = 0x7, BR_MRP_TLV_HEADER_IN_LINK_DOWN = 0x8, BR_MRP_TLV_HEADER_IN_LINK_UP = 0x9, BR_MRP_TLV_HEADER_IN_LINK_STATUS = 0xa, BR_MRP_TLV_HEADER_OPTION = 0x7f, }; enum br_mrp_sub_tlv_header_type { BR_MRP_SUB_TLV_HEADER_TEST_MGR_NACK = 0x1, BR_MRP_SUB_TLV_HEADER_TEST_PROPAGATE = 0x2, BR_MRP_SUB_TLV_HEADER_TEST_AUTO_MGR = 0x3, }; #endif
1,718
21.92
63
h
null
systemd-main/src/basic/linux/netdevice.h
/* SPDX-License-Identifier: GPL-2.0+ WITH Linux-syscall-note */ /* * INET An implementation of the TCP/IP protocol suite for the LINUX * operating system. INET is implemented using the BSD Socket * interface as the means of communication with the user level. * * Definitions for the Interfaces handler. * * Version: @(#)dev.h 1.0.10 08/12/93 * * Authors: Ross Biro * Fred N. van Kempen, <[email protected]> * Corey Minyard <[email protected]> * Donald J. Becker, <[email protected]> * Alan Cox, <[email protected]> * Bjorn Ekwall. <[email protected]> * Pekka Riikonen <[email protected]> * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version * 2 of the License, or (at your option) any later version. * * Moved to /usr/include/linux for NET3 */ #ifndef _UAPI_LINUX_NETDEVICE_H #define _UAPI_LINUX_NETDEVICE_H #include <linux/if.h> #include <linux/if_ether.h> #include <linux/if_packet.h> #include <linux/if_link.h> #define MAX_ADDR_LEN 32 /* Largest hardware address length */ /* Initial net device group. All devices belong to group 0 by default. */ #define INIT_NETDEV_GROUP 0 /* interface name assignment types (sysfs name_assign_type attribute) */ #define NET_NAME_UNKNOWN 0 /* unknown origin (not exposed to userspace) */ #define NET_NAME_ENUM 1 /* enumerated by kernel */ #define NET_NAME_PREDICTABLE 2 /* predictably named by the kernel */ #define NET_NAME_USER 3 /* provided by user-space */ #define NET_NAME_RENAMED 4 /* renamed by user-space */ /* Media selection options. */ enum { IF_PORT_UNKNOWN = 0, IF_PORT_10BASE2, IF_PORT_10BASET, IF_PORT_AUI, IF_PORT_100BASET, IF_PORT_100BASETX, IF_PORT_100BASEFX }; /* hardware address assignment types */ #define NET_ADDR_PERM 0 /* address is permanent (default) */ #define NET_ADDR_RANDOM 1 /* address is generated randomly */ #define NET_ADDR_STOLEN 2 /* address is stolen from other device */ #define NET_ADDR_SET 3 /* address is set using * dev_set_mac_address() */ #endif /* _UAPI_LINUX_NETDEVICE_H */
2,268
32.865672
74
h
null
systemd-main/src/basic/linux/netlink.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _UAPI__LINUX_NETLINK_H #define _UAPI__LINUX_NETLINK_H #include <linux/const.h> #include <linux/socket.h> /* for __kernel_sa_family_t */ #include <linux/types.h> #define NETLINK_ROUTE 0 /* Routing/device hook */ #define NETLINK_UNUSED 1 /* Unused number */ #define NETLINK_USERSOCK 2 /* Reserved for user mode socket protocols */ #define NETLINK_FIREWALL 3 /* Unused number, formerly ip_queue */ #define NETLINK_SOCK_DIAG 4 /* socket monitoring */ #define NETLINK_NFLOG 5 /* netfilter/iptables ULOG */ #define NETLINK_XFRM 6 /* ipsec */ #define NETLINK_SELINUX 7 /* SELinux event notifications */ #define NETLINK_ISCSI 8 /* Open-iSCSI */ #define NETLINK_AUDIT 9 /* auditing */ #define NETLINK_FIB_LOOKUP 10 #define NETLINK_CONNECTOR 11 #define NETLINK_NETFILTER 12 /* netfilter subsystem */ #define NETLINK_IP6_FW 13 #define NETLINK_DNRTMSG 14 /* DECnet routing messages (obsolete) */ #define NETLINK_KOBJECT_UEVENT 15 /* Kernel messages to userspace */ #define NETLINK_GENERIC 16 /* leave room for NETLINK_DM (DM Events) */ #define NETLINK_SCSITRANSPORT 18 /* SCSI Transports */ #define NETLINK_ECRYPTFS 19 #define NETLINK_RDMA 20 #define NETLINK_CRYPTO 21 /* Crypto layer */ #define NETLINK_SMC 22 /* SMC monitoring */ #define NETLINK_INET_DIAG NETLINK_SOCK_DIAG #define MAX_LINKS 32 struct sockaddr_nl { __kernel_sa_family_t nl_family; /* AF_NETLINK */ unsigned short nl_pad; /* zero */ __u32 nl_pid; /* port ID */ __u32 nl_groups; /* multicast groups mask */ }; /** * struct nlmsghdr - fixed format metadata header of Netlink messages * @nlmsg_len: Length of message including header * @nlmsg_type: Message content type * @nlmsg_flags: Additional flags * @nlmsg_seq: Sequence number * @nlmsg_pid: Sending process port ID */ struct nlmsghdr { __u32 nlmsg_len; __u16 nlmsg_type; __u16 nlmsg_flags; __u32 nlmsg_seq; __u32 nlmsg_pid; }; /* Flags values */ #define NLM_F_REQUEST 0x01 /* It is request message. */ #define NLM_F_MULTI 0x02 /* Multipart message, terminated by NLMSG_DONE */ #define NLM_F_ACK 0x04 /* Reply with ack, with zero or error code */ #define NLM_F_ECHO 0x08 /* Receive resulting notifications */ #define NLM_F_DUMP_INTR 0x10 /* Dump was inconsistent due to sequence change */ #define NLM_F_DUMP_FILTERED 0x20 /* Dump was filtered as requested */ /* Modifiers to GET request */ #define NLM_F_ROOT 0x100 /* specify tree root */ #define NLM_F_MATCH 0x200 /* return all matching */ #define NLM_F_ATOMIC 0x400 /* atomic GET */ #define NLM_F_DUMP (NLM_F_ROOT|NLM_F_MATCH) /* Modifiers to NEW request */ #define NLM_F_REPLACE 0x100 /* Override existing */ #define NLM_F_EXCL 0x200 /* Do not touch, if it exists */ #define NLM_F_CREATE 0x400 /* Create, if it does not exist */ #define NLM_F_APPEND 0x800 /* Add to end of list */ /* Modifiers to DELETE request */ #define NLM_F_NONREC 0x100 /* Do not delete recursively */ #define NLM_F_BULK 0x200 /* Delete multiple objects */ /* Flags for ACK message */ #define NLM_F_CAPPED 0x100 /* request was capped */ #define NLM_F_ACK_TLVS 0x200 /* extended ACK TVLs were included */ /* 4.4BSD ADD NLM_F_CREATE|NLM_F_EXCL 4.4BSD CHANGE NLM_F_REPLACE True CHANGE NLM_F_CREATE|NLM_F_REPLACE Append NLM_F_CREATE Check NLM_F_EXCL */ #define NLMSG_ALIGNTO 4U #define NLMSG_ALIGN(len) ( ((len)+NLMSG_ALIGNTO-1) & ~(NLMSG_ALIGNTO-1) ) #define NLMSG_HDRLEN ((int) NLMSG_ALIGN(sizeof(struct nlmsghdr))) #define NLMSG_LENGTH(len) ((len) + NLMSG_HDRLEN) #define NLMSG_SPACE(len) NLMSG_ALIGN(NLMSG_LENGTH(len)) #define NLMSG_DATA(nlh) ((void *)(((char *)nlh) + NLMSG_HDRLEN)) #define NLMSG_NEXT(nlh,len) ((len) -= NLMSG_ALIGN((nlh)->nlmsg_len), \ (struct nlmsghdr *)(((char *)(nlh)) + \ NLMSG_ALIGN((nlh)->nlmsg_len))) #define NLMSG_OK(nlh,len) ((len) >= (int)sizeof(struct nlmsghdr) && \ (nlh)->nlmsg_len >= sizeof(struct nlmsghdr) && \ (nlh)->nlmsg_len <= (len)) #define NLMSG_PAYLOAD(nlh,len) ((nlh)->nlmsg_len - NLMSG_SPACE((len))) #define NLMSG_NOOP 0x1 /* Nothing. */ #define NLMSG_ERROR 0x2 /* Error */ #define NLMSG_DONE 0x3 /* End of a dump */ #define NLMSG_OVERRUN 0x4 /* Data lost */ #define NLMSG_MIN_TYPE 0x10 /* < 0x10: reserved control messages */ struct nlmsgerr { int error; struct nlmsghdr msg; /* * followed by the message contents unless NETLINK_CAP_ACK was set * or the ACK indicates success (error == 0) * message length is aligned with NLMSG_ALIGN() */ /* * followed by TLVs defined in enum nlmsgerr_attrs * if NETLINK_EXT_ACK was set */ }; /** * enum nlmsgerr_attrs - nlmsgerr attributes * @NLMSGERR_ATTR_UNUSED: unused * @NLMSGERR_ATTR_MSG: error message string (string) * @NLMSGERR_ATTR_OFFS: offset of the invalid attribute in the original * message, counting from the beginning of the header (u32) * @NLMSGERR_ATTR_COOKIE: arbitrary subsystem specific cookie to * be used - in the success case - to identify a created * object or operation or similar (binary) * @NLMSGERR_ATTR_POLICY: policy for a rejected attribute * @NLMSGERR_ATTR_MISS_TYPE: type of a missing required attribute, * %NLMSGERR_ATTR_MISS_NEST will not be present if the attribute was * missing at the message level * @NLMSGERR_ATTR_MISS_NEST: offset of the nest where attribute was missing * @__NLMSGERR_ATTR_MAX: number of attributes * @NLMSGERR_ATTR_MAX: highest attribute number */ enum nlmsgerr_attrs { NLMSGERR_ATTR_UNUSED, NLMSGERR_ATTR_MSG, NLMSGERR_ATTR_OFFS, NLMSGERR_ATTR_COOKIE, NLMSGERR_ATTR_POLICY, NLMSGERR_ATTR_MISS_TYPE, NLMSGERR_ATTR_MISS_NEST, __NLMSGERR_ATTR_MAX, NLMSGERR_ATTR_MAX = __NLMSGERR_ATTR_MAX - 1 }; #define NETLINK_ADD_MEMBERSHIP 1 #define NETLINK_DROP_MEMBERSHIP 2 #define NETLINK_PKTINFO 3 #define NETLINK_BROADCAST_ERROR 4 #define NETLINK_NO_ENOBUFS 5 #ifndef __KERNEL__ #define NETLINK_RX_RING 6 #define NETLINK_TX_RING 7 #endif #define NETLINK_LISTEN_ALL_NSID 8 #define NETLINK_LIST_MEMBERSHIPS 9 #define NETLINK_CAP_ACK 10 #define NETLINK_EXT_ACK 11 #define NETLINK_GET_STRICT_CHK 12 struct nl_pktinfo { __u32 group; }; struct nl_mmap_req { unsigned int nm_block_size; unsigned int nm_block_nr; unsigned int nm_frame_size; unsigned int nm_frame_nr; }; struct nl_mmap_hdr { unsigned int nm_status; unsigned int nm_len; __u32 nm_group; /* credentials */ __u32 nm_pid; __u32 nm_uid; __u32 nm_gid; }; #ifndef __KERNEL__ enum nl_mmap_status { NL_MMAP_STATUS_UNUSED, NL_MMAP_STATUS_RESERVED, NL_MMAP_STATUS_VALID, NL_MMAP_STATUS_COPY, NL_MMAP_STATUS_SKIP, }; #define NL_MMAP_MSG_ALIGNMENT NLMSG_ALIGNTO #define NL_MMAP_MSG_ALIGN(sz) __ALIGN_KERNEL(sz, NL_MMAP_MSG_ALIGNMENT) #define NL_MMAP_HDRLEN NL_MMAP_MSG_ALIGN(sizeof(struct nl_mmap_hdr)) #endif #define NET_MAJOR 36 /* Major 36 is reserved for networking */ enum { NETLINK_UNCONNECTED = 0, NETLINK_CONNECTED, }; /* * <------- NLA_HDRLEN ------> <-- NLA_ALIGN(payload)--> * +---------------------+- - -+- - - - - - - - - -+- - -+ * | Header | Pad | Payload | Pad | * | (struct nlattr) | ing | | ing | * +---------------------+- - -+- - - - - - - - - -+- - -+ * <-------------- nlattr->nla_len --------------> */ struct nlattr { __u16 nla_len; __u16 nla_type; }; /* * nla_type (16 bits) * +---+---+-------------------------------+ * | N | O | Attribute Type | * +---+---+-------------------------------+ * N := Carries nested attributes * O := Payload stored in network byte order * * Note: The N and O flag are mutually exclusive. */ #define NLA_F_NESTED (1 << 15) #define NLA_F_NET_BYTEORDER (1 << 14) #define NLA_TYPE_MASK ~(NLA_F_NESTED | NLA_F_NET_BYTEORDER) #define NLA_ALIGNTO 4 #define NLA_ALIGN(len) (((len) + NLA_ALIGNTO - 1) & ~(NLA_ALIGNTO - 1)) #define NLA_HDRLEN ((int) NLA_ALIGN(sizeof(struct nlattr))) /* Generic 32 bitflags attribute content sent to the kernel. * * The value is a bitmap that defines the values being set * The selector is a bitmask that defines which value is legit * * Examples: * value = 0x0, and selector = 0x1 * implies we are selecting bit 1 and we want to set its value to 0. * * value = 0x2, and selector = 0x2 * implies we are selecting bit 2 and we want to set its value to 1. * */ struct nla_bitfield32 { __u32 value; __u32 selector; }; /* * policy descriptions - it's specific to each family how this is used * Normally, it should be retrieved via a dump inside another attribute * specifying where it applies. */ /** * enum netlink_attribute_type - type of an attribute * @NL_ATTR_TYPE_INVALID: unused * @NL_ATTR_TYPE_FLAG: flag attribute (present/not present) * @NL_ATTR_TYPE_U8: 8-bit unsigned attribute * @NL_ATTR_TYPE_U16: 16-bit unsigned attribute * @NL_ATTR_TYPE_U32: 32-bit unsigned attribute * @NL_ATTR_TYPE_U64: 64-bit unsigned attribute * @NL_ATTR_TYPE_S8: 8-bit signed attribute * @NL_ATTR_TYPE_S16: 16-bit signed attribute * @NL_ATTR_TYPE_S32: 32-bit signed attribute * @NL_ATTR_TYPE_S64: 64-bit signed attribute * @NL_ATTR_TYPE_BINARY: binary data, min/max length may be specified * @NL_ATTR_TYPE_STRING: string, min/max length may be specified * @NL_ATTR_TYPE_NUL_STRING: NUL-terminated string, * min/max length may be specified * @NL_ATTR_TYPE_NESTED: nested, i.e. the content of this attribute * consists of sub-attributes. The nested policy and maxtype * inside may be specified. * @NL_ATTR_TYPE_NESTED_ARRAY: nested array, i.e. the content of this * attribute contains sub-attributes whose type is irrelevant * (just used to separate the array entries) and each such array * entry has attributes again, the policy for those inner ones * and the corresponding maxtype may be specified. * @NL_ATTR_TYPE_BITFIELD32: &struct nla_bitfield32 attribute */ enum netlink_attribute_type { NL_ATTR_TYPE_INVALID, NL_ATTR_TYPE_FLAG, NL_ATTR_TYPE_U8, NL_ATTR_TYPE_U16, NL_ATTR_TYPE_U32, NL_ATTR_TYPE_U64, NL_ATTR_TYPE_S8, NL_ATTR_TYPE_S16, NL_ATTR_TYPE_S32, NL_ATTR_TYPE_S64, NL_ATTR_TYPE_BINARY, NL_ATTR_TYPE_STRING, NL_ATTR_TYPE_NUL_STRING, NL_ATTR_TYPE_NESTED, NL_ATTR_TYPE_NESTED_ARRAY, NL_ATTR_TYPE_BITFIELD32, }; /** * enum netlink_policy_type_attr - policy type attributes * @NL_POLICY_TYPE_ATTR_UNSPEC: unused * @NL_POLICY_TYPE_ATTR_TYPE: type of the attribute, * &enum netlink_attribute_type (U32) * @NL_POLICY_TYPE_ATTR_MIN_VALUE_S: minimum value for signed * integers (S64) * @NL_POLICY_TYPE_ATTR_MAX_VALUE_S: maximum value for signed * integers (S64) * @NL_POLICY_TYPE_ATTR_MIN_VALUE_U: minimum value for unsigned * integers (U64) * @NL_POLICY_TYPE_ATTR_MAX_VALUE_U: maximum value for unsigned * integers (U64) * @NL_POLICY_TYPE_ATTR_MIN_LENGTH: minimum length for binary * attributes, no minimum if not given (U32) * @NL_POLICY_TYPE_ATTR_MAX_LENGTH: maximum length for binary * attributes, no maximum if not given (U32) * @NL_POLICY_TYPE_ATTR_POLICY_IDX: sub policy for nested and * nested array types (U32) * @NL_POLICY_TYPE_ATTR_POLICY_MAXTYPE: maximum sub policy * attribute for nested and nested array types, this can * in theory be < the size of the policy pointed to by * the index, if limited inside the nesting (U32) * @NL_POLICY_TYPE_ATTR_BITFIELD32_MASK: valid mask for the * bitfield32 type (U32) * @NL_POLICY_TYPE_ATTR_MASK: mask of valid bits for unsigned integers (U64) * @NL_POLICY_TYPE_ATTR_PAD: pad attribute for 64-bit alignment * * @__NL_POLICY_TYPE_ATTR_MAX: number of attributes * @NL_POLICY_TYPE_ATTR_MAX: highest attribute number */ enum netlink_policy_type_attr { NL_POLICY_TYPE_ATTR_UNSPEC, NL_POLICY_TYPE_ATTR_TYPE, NL_POLICY_TYPE_ATTR_MIN_VALUE_S, NL_POLICY_TYPE_ATTR_MAX_VALUE_S, NL_POLICY_TYPE_ATTR_MIN_VALUE_U, NL_POLICY_TYPE_ATTR_MAX_VALUE_U, NL_POLICY_TYPE_ATTR_MIN_LENGTH, NL_POLICY_TYPE_ATTR_MAX_LENGTH, NL_POLICY_TYPE_ATTR_POLICY_IDX, NL_POLICY_TYPE_ATTR_POLICY_MAXTYPE, NL_POLICY_TYPE_ATTR_BITFIELD32_MASK, NL_POLICY_TYPE_ATTR_PAD, NL_POLICY_TYPE_ATTR_MASK, /* keep last */ __NL_POLICY_TYPE_ATTR_MAX, NL_POLICY_TYPE_ATTR_MAX = __NL_POLICY_TYPE_ATTR_MAX - 1 }; #endif /* _UAPI__LINUX_NETLINK_H */
12,272
31.382586
80
h
null
systemd-main/src/basic/linux/nexthop.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _UAPI_LINUX_NEXTHOP_H #define _UAPI_LINUX_NEXTHOP_H #include <linux/types.h> struct nhmsg { unsigned char nh_family; unsigned char nh_scope; /* return only */ unsigned char nh_protocol; /* Routing protocol that installed nh */ unsigned char resvd; unsigned int nh_flags; /* RTNH_F flags */ }; /* entry in a nexthop group */ struct nexthop_grp { __u32 id; /* nexthop id - must exist */ __u8 weight; /* weight of this nexthop */ __u8 resvd1; __u16 resvd2; }; enum { NEXTHOP_GRP_TYPE_MPATH, /* hash-threshold nexthop group * default type if not specified */ NEXTHOP_GRP_TYPE_RES, /* resilient nexthop group */ __NEXTHOP_GRP_TYPE_MAX, }; #define NEXTHOP_GRP_TYPE_MAX (__NEXTHOP_GRP_TYPE_MAX - 1) enum { NHA_UNSPEC, NHA_ID, /* u32; id for nexthop. id == 0 means auto-assign */ NHA_GROUP, /* array of nexthop_grp */ NHA_GROUP_TYPE, /* u16 one of NEXTHOP_GRP_TYPE */ /* if NHA_GROUP attribute is added, no other attributes can be set */ NHA_BLACKHOLE, /* flag; nexthop used to blackhole packets */ /* if NHA_BLACKHOLE is added, OIF, GATEWAY, ENCAP can not be set */ NHA_OIF, /* u32; nexthop device */ NHA_GATEWAY, /* be32 (IPv4) or in6_addr (IPv6) gw address */ NHA_ENCAP_TYPE, /* u16; lwt encap type */ NHA_ENCAP, /* lwt encap data */ /* NHA_OIF can be appended to dump request to return only * nexthops using given device */ NHA_GROUPS, /* flag; only return nexthop groups in dump */ NHA_MASTER, /* u32; only return nexthops with given master dev */ NHA_FDB, /* flag; nexthop belongs to a bridge fdb */ /* if NHA_FDB is added, OIF, BLACKHOLE, ENCAP cannot be set */ /* nested; resilient nexthop group attributes */ NHA_RES_GROUP, /* nested; nexthop bucket attributes */ NHA_RES_BUCKET, __NHA_MAX, }; #define NHA_MAX (__NHA_MAX - 1) enum { NHA_RES_GROUP_UNSPEC, /* Pad attribute for 64-bit alignment. */ NHA_RES_GROUP_PAD = NHA_RES_GROUP_UNSPEC, /* u16; number of nexthop buckets in a resilient nexthop group */ NHA_RES_GROUP_BUCKETS, /* clock_t as u32; nexthop bucket idle timer (per-group) */ NHA_RES_GROUP_IDLE_TIMER, /* clock_t as u32; nexthop unbalanced timer */ NHA_RES_GROUP_UNBALANCED_TIMER, /* clock_t as u64; nexthop unbalanced time */ NHA_RES_GROUP_UNBALANCED_TIME, __NHA_RES_GROUP_MAX, }; #define NHA_RES_GROUP_MAX (__NHA_RES_GROUP_MAX - 1) enum { NHA_RES_BUCKET_UNSPEC, /* Pad attribute for 64-bit alignment. */ NHA_RES_BUCKET_PAD = NHA_RES_BUCKET_UNSPEC, /* u16; nexthop bucket index */ NHA_RES_BUCKET_INDEX, /* clock_t as u64; nexthop bucket idle time */ NHA_RES_BUCKET_IDLE_TIME, /* u32; nexthop id assigned to the nexthop bucket */ NHA_RES_BUCKET_NH_ID, __NHA_RES_BUCKET_MAX, }; #define NHA_RES_BUCKET_MAX (__NHA_RES_BUCKET_MAX - 1) #endif
2,835
26.009524
70
h
null
systemd-main/src/basic/linux/rtnetlink.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _UAPI__LINUX_RTNETLINK_H #define _UAPI__LINUX_RTNETLINK_H #include <linux/types.h> #include <linux/netlink.h> #include <linux/if_link.h> #include <linux/if_addr.h> #include <linux/neighbour.h> /* rtnetlink families. Values up to 127 are reserved for real address * families, values above 128 may be used arbitrarily. */ #define RTNL_FAMILY_IPMR 128 #define RTNL_FAMILY_IP6MR 129 #define RTNL_FAMILY_MAX 129 /**** * Routing/neighbour discovery messages. ****/ /* Types of messages */ enum { RTM_BASE = 16, #define RTM_BASE RTM_BASE RTM_NEWLINK = 16, #define RTM_NEWLINK RTM_NEWLINK RTM_DELLINK, #define RTM_DELLINK RTM_DELLINK RTM_GETLINK, #define RTM_GETLINK RTM_GETLINK RTM_SETLINK, #define RTM_SETLINK RTM_SETLINK RTM_NEWADDR = 20, #define RTM_NEWADDR RTM_NEWADDR RTM_DELADDR, #define RTM_DELADDR RTM_DELADDR RTM_GETADDR, #define RTM_GETADDR RTM_GETADDR RTM_NEWROUTE = 24, #define RTM_NEWROUTE RTM_NEWROUTE RTM_DELROUTE, #define RTM_DELROUTE RTM_DELROUTE RTM_GETROUTE, #define RTM_GETROUTE RTM_GETROUTE RTM_NEWNEIGH = 28, #define RTM_NEWNEIGH RTM_NEWNEIGH RTM_DELNEIGH, #define RTM_DELNEIGH RTM_DELNEIGH RTM_GETNEIGH, #define RTM_GETNEIGH RTM_GETNEIGH RTM_NEWRULE = 32, #define RTM_NEWRULE RTM_NEWRULE RTM_DELRULE, #define RTM_DELRULE RTM_DELRULE RTM_GETRULE, #define RTM_GETRULE RTM_GETRULE RTM_NEWQDISC = 36, #define RTM_NEWQDISC RTM_NEWQDISC RTM_DELQDISC, #define RTM_DELQDISC RTM_DELQDISC RTM_GETQDISC, #define RTM_GETQDISC RTM_GETQDISC RTM_NEWTCLASS = 40, #define RTM_NEWTCLASS RTM_NEWTCLASS RTM_DELTCLASS, #define RTM_DELTCLASS RTM_DELTCLASS RTM_GETTCLASS, #define RTM_GETTCLASS RTM_GETTCLASS RTM_NEWTFILTER = 44, #define RTM_NEWTFILTER RTM_NEWTFILTER RTM_DELTFILTER, #define RTM_DELTFILTER RTM_DELTFILTER RTM_GETTFILTER, #define RTM_GETTFILTER RTM_GETTFILTER RTM_NEWACTION = 48, #define RTM_NEWACTION RTM_NEWACTION RTM_DELACTION, #define RTM_DELACTION RTM_DELACTION RTM_GETACTION, #define RTM_GETACTION RTM_GETACTION RTM_NEWPREFIX = 52, #define RTM_NEWPREFIX RTM_NEWPREFIX RTM_GETMULTICAST = 58, #define RTM_GETMULTICAST RTM_GETMULTICAST RTM_GETANYCAST = 62, #define RTM_GETANYCAST RTM_GETANYCAST RTM_NEWNEIGHTBL = 64, #define RTM_NEWNEIGHTBL RTM_NEWNEIGHTBL RTM_GETNEIGHTBL = 66, #define RTM_GETNEIGHTBL RTM_GETNEIGHTBL RTM_SETNEIGHTBL, #define RTM_SETNEIGHTBL RTM_SETNEIGHTBL RTM_NEWNDUSEROPT = 68, #define RTM_NEWNDUSEROPT RTM_NEWNDUSEROPT RTM_NEWADDRLABEL = 72, #define RTM_NEWADDRLABEL RTM_NEWADDRLABEL RTM_DELADDRLABEL, #define RTM_DELADDRLABEL RTM_DELADDRLABEL RTM_GETADDRLABEL, #define RTM_GETADDRLABEL RTM_GETADDRLABEL RTM_GETDCB = 78, #define RTM_GETDCB RTM_GETDCB RTM_SETDCB, #define RTM_SETDCB RTM_SETDCB RTM_NEWNETCONF = 80, #define RTM_NEWNETCONF RTM_NEWNETCONF RTM_DELNETCONF, #define RTM_DELNETCONF RTM_DELNETCONF RTM_GETNETCONF = 82, #define RTM_GETNETCONF RTM_GETNETCONF RTM_NEWMDB = 84, #define RTM_NEWMDB RTM_NEWMDB RTM_DELMDB = 85, #define RTM_DELMDB RTM_DELMDB RTM_GETMDB = 86, #define RTM_GETMDB RTM_GETMDB RTM_NEWNSID = 88, #define RTM_NEWNSID RTM_NEWNSID RTM_DELNSID = 89, #define RTM_DELNSID RTM_DELNSID RTM_GETNSID = 90, #define RTM_GETNSID RTM_GETNSID RTM_NEWSTATS = 92, #define RTM_NEWSTATS RTM_NEWSTATS RTM_GETSTATS = 94, #define RTM_GETSTATS RTM_GETSTATS RTM_SETSTATS, #define RTM_SETSTATS RTM_SETSTATS RTM_NEWCACHEREPORT = 96, #define RTM_NEWCACHEREPORT RTM_NEWCACHEREPORT RTM_NEWCHAIN = 100, #define RTM_NEWCHAIN RTM_NEWCHAIN RTM_DELCHAIN, #define RTM_DELCHAIN RTM_DELCHAIN RTM_GETCHAIN, #define RTM_GETCHAIN RTM_GETCHAIN RTM_NEWNEXTHOP = 104, #define RTM_NEWNEXTHOP RTM_NEWNEXTHOP RTM_DELNEXTHOP, #define RTM_DELNEXTHOP RTM_DELNEXTHOP RTM_GETNEXTHOP, #define RTM_GETNEXTHOP RTM_GETNEXTHOP RTM_NEWLINKPROP = 108, #define RTM_NEWLINKPROP RTM_NEWLINKPROP RTM_DELLINKPROP, #define RTM_DELLINKPROP RTM_DELLINKPROP RTM_GETLINKPROP, #define RTM_GETLINKPROP RTM_GETLINKPROP RTM_NEWVLAN = 112, #define RTM_NEWNVLAN RTM_NEWVLAN RTM_DELVLAN, #define RTM_DELVLAN RTM_DELVLAN RTM_GETVLAN, #define RTM_GETVLAN RTM_GETVLAN RTM_NEWNEXTHOPBUCKET = 116, #define RTM_NEWNEXTHOPBUCKET RTM_NEWNEXTHOPBUCKET RTM_DELNEXTHOPBUCKET, #define RTM_DELNEXTHOPBUCKET RTM_DELNEXTHOPBUCKET RTM_GETNEXTHOPBUCKET, #define RTM_GETNEXTHOPBUCKET RTM_GETNEXTHOPBUCKET RTM_NEWTUNNEL = 120, #define RTM_NEWTUNNEL RTM_NEWTUNNEL RTM_DELTUNNEL, #define RTM_DELTUNNEL RTM_DELTUNNEL RTM_GETTUNNEL, #define RTM_GETTUNNEL RTM_GETTUNNEL __RTM_MAX, #define RTM_MAX (((__RTM_MAX + 3) & ~3) - 1) }; #define RTM_NR_MSGTYPES (RTM_MAX + 1 - RTM_BASE) #define RTM_NR_FAMILIES (RTM_NR_MSGTYPES >> 2) #define RTM_FAM(cmd) (((cmd) - RTM_BASE) >> 2) /* Generic structure for encapsulation of optional route information. It is reminiscent of sockaddr, but with sa_family replaced with attribute type. */ struct rtattr { unsigned short rta_len; unsigned short rta_type; }; /* Macros to handle rtattributes */ #define RTA_ALIGNTO 4U #define RTA_ALIGN(len) ( ((len)+RTA_ALIGNTO-1) & ~(RTA_ALIGNTO-1) ) #define RTA_OK(rta,len) ((len) >= (int)sizeof(struct rtattr) && \ (rta)->rta_len >= sizeof(struct rtattr) && \ (rta)->rta_len <= (len)) #define RTA_NEXT(rta,attrlen) ((attrlen) -= RTA_ALIGN((rta)->rta_len), \ (struct rtattr*)(((char*)(rta)) + RTA_ALIGN((rta)->rta_len))) #define RTA_LENGTH(len) (RTA_ALIGN(sizeof(struct rtattr)) + (len)) #define RTA_SPACE(len) RTA_ALIGN(RTA_LENGTH(len)) #define RTA_DATA(rta) ((void*)(((char*)(rta)) + RTA_LENGTH(0))) #define RTA_PAYLOAD(rta) ((int)((rta)->rta_len) - RTA_LENGTH(0)) /****************************************************************************** * Definitions used in routing table administration. ****/ struct rtmsg { unsigned char rtm_family; unsigned char rtm_dst_len; unsigned char rtm_src_len; unsigned char rtm_tos; unsigned char rtm_table; /* Routing table id */ unsigned char rtm_protocol; /* Routing protocol; see below */ unsigned char rtm_scope; /* See below */ unsigned char rtm_type; /* See below */ unsigned rtm_flags; }; /* rtm_type */ enum { RTN_UNSPEC, RTN_UNICAST, /* Gateway or direct route */ RTN_LOCAL, /* Accept locally */ RTN_BROADCAST, /* Accept locally as broadcast, send as broadcast */ RTN_ANYCAST, /* Accept locally as broadcast, but send as unicast */ RTN_MULTICAST, /* Multicast route */ RTN_BLACKHOLE, /* Drop */ RTN_UNREACHABLE, /* Destination is unreachable */ RTN_PROHIBIT, /* Administratively prohibited */ RTN_THROW, /* Not in this table */ RTN_NAT, /* Translate this address */ RTN_XRESOLVE, /* Use external resolver */ __RTN_MAX }; #define RTN_MAX (__RTN_MAX - 1) /* rtm_protocol */ #define RTPROT_UNSPEC 0 #define RTPROT_REDIRECT 1 /* Route installed by ICMP redirects; not used by current IPv4 */ #define RTPROT_KERNEL 2 /* Route installed by kernel */ #define RTPROT_BOOT 3 /* Route installed during boot */ #define RTPROT_STATIC 4 /* Route installed by administrator */ /* Values of protocol >= RTPROT_STATIC are not interpreted by kernel; they are just passed from user and back as is. It will be used by hypothetical multiple routing daemons. Note that protocol values should be standardized in order to avoid conflicts. */ #define RTPROT_GATED 8 /* Apparently, GateD */ #define RTPROT_RA 9 /* RDISC/ND router advertisements */ #define RTPROT_MRT 10 /* Merit MRT */ #define RTPROT_ZEBRA 11 /* Zebra */ #define RTPROT_BIRD 12 /* BIRD */ #define RTPROT_DNROUTED 13 /* DECnet routing daemon */ #define RTPROT_XORP 14 /* XORP */ #define RTPROT_NTK 15 /* Netsukuku */ #define RTPROT_DHCP 16 /* DHCP client */ #define RTPROT_MROUTED 17 /* Multicast daemon */ #define RTPROT_KEEPALIVED 18 /* Keepalived daemon */ #define RTPROT_BABEL 42 /* Babel daemon */ #define RTPROT_OPENR 99 /* Open Routing (Open/R) Routes */ #define RTPROT_BGP 186 /* BGP Routes */ #define RTPROT_ISIS 187 /* ISIS Routes */ #define RTPROT_OSPF 188 /* OSPF Routes */ #define RTPROT_RIP 189 /* RIP Routes */ #define RTPROT_EIGRP 192 /* EIGRP Routes */ /* rtm_scope Really it is not scope, but sort of distance to the destination. NOWHERE are reserved for not existing destinations, HOST is our local addresses, LINK are destinations, located on directly attached link and UNIVERSE is everywhere in the Universe. Intermediate values are also possible f.e. interior routes could be assigned a value between UNIVERSE and LINK. */ enum rt_scope_t { RT_SCOPE_UNIVERSE=0, /* User defined values */ RT_SCOPE_SITE=200, RT_SCOPE_LINK=253, RT_SCOPE_HOST=254, RT_SCOPE_NOWHERE=255 }; /* rtm_flags */ #define RTM_F_NOTIFY 0x100 /* Notify user of route change */ #define RTM_F_CLONED 0x200 /* This route is cloned */ #define RTM_F_EQUALIZE 0x400 /* Multipath equalizer: NI */ #define RTM_F_PREFIX 0x800 /* Prefix addresses */ #define RTM_F_LOOKUP_TABLE 0x1000 /* set rtm_table to FIB lookup result */ #define RTM_F_FIB_MATCH 0x2000 /* return full fib lookup match */ #define RTM_F_OFFLOAD 0x4000 /* route is offloaded */ #define RTM_F_TRAP 0x8000 /* route is trapping packets */ #define RTM_F_OFFLOAD_FAILED 0x20000000 /* route offload failed, this value * is chosen to avoid conflicts with * other flags defined in * include/uapi/linux/ipv6_route.h */ /* Reserved table identifiers */ enum rt_class_t { RT_TABLE_UNSPEC=0, /* User defined values */ RT_TABLE_COMPAT=252, RT_TABLE_DEFAULT=253, RT_TABLE_MAIN=254, RT_TABLE_LOCAL=255, RT_TABLE_MAX=0xFFFFFFFF }; /* Routing message attributes */ enum rtattr_type_t { RTA_UNSPEC, RTA_DST, RTA_SRC, RTA_IIF, RTA_OIF, RTA_GATEWAY, RTA_PRIORITY, RTA_PREFSRC, RTA_METRICS, RTA_MULTIPATH, RTA_PROTOINFO, /* no longer used */ RTA_FLOW, RTA_CACHEINFO, RTA_SESSION, /* no longer used */ RTA_MP_ALGO, /* no longer used */ RTA_TABLE, RTA_MARK, RTA_MFC_STATS, RTA_VIA, RTA_NEWDST, RTA_PREF, RTA_ENCAP_TYPE, RTA_ENCAP, RTA_EXPIRES, RTA_PAD, RTA_UID, RTA_TTL_PROPAGATE, RTA_IP_PROTO, RTA_SPORT, RTA_DPORT, RTA_NH_ID, __RTA_MAX }; #define RTA_MAX (__RTA_MAX - 1) #define RTM_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct rtmsg)))) #define RTM_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct rtmsg)) /* RTM_MULTIPATH --- array of struct rtnexthop. * * "struct rtnexthop" describes all necessary nexthop information, * i.e. parameters of path to a destination via this nexthop. * * At the moment it is impossible to set different prefsrc, mtu, window * and rtt for different paths from multipath. */ struct rtnexthop { unsigned short rtnh_len; unsigned char rtnh_flags; unsigned char rtnh_hops; int rtnh_ifindex; }; /* rtnh_flags */ #define RTNH_F_DEAD 1 /* Nexthop is dead (used by multipath) */ #define RTNH_F_PERVASIVE 2 /* Do recursive gateway lookup */ #define RTNH_F_ONLINK 4 /* Gateway is forced on link */ #define RTNH_F_OFFLOAD 8 /* Nexthop is offloaded */ #define RTNH_F_LINKDOWN 16 /* carrier-down on nexthop */ #define RTNH_F_UNRESOLVED 32 /* The entry is unresolved (ipmr) */ #define RTNH_F_TRAP 64 /* Nexthop is trapping packets */ #define RTNH_COMPARE_MASK (RTNH_F_DEAD | RTNH_F_LINKDOWN | \ RTNH_F_OFFLOAD | RTNH_F_TRAP) /* Macros to handle hexthops */ #define RTNH_ALIGNTO 4 #define RTNH_ALIGN(len) ( ((len)+RTNH_ALIGNTO-1) & ~(RTNH_ALIGNTO-1) ) #define RTNH_OK(rtnh,len) ((rtnh)->rtnh_len >= sizeof(struct rtnexthop) && \ ((int)(rtnh)->rtnh_len) <= (len)) #define RTNH_NEXT(rtnh) ((struct rtnexthop*)(((char*)(rtnh)) + RTNH_ALIGN((rtnh)->rtnh_len))) #define RTNH_LENGTH(len) (RTNH_ALIGN(sizeof(struct rtnexthop)) + (len)) #define RTNH_SPACE(len) RTNH_ALIGN(RTNH_LENGTH(len)) #define RTNH_DATA(rtnh) ((struct rtattr*)(((char*)(rtnh)) + RTNH_LENGTH(0))) /* RTA_VIA */ struct rtvia { __kernel_sa_family_t rtvia_family; __u8 rtvia_addr[]; }; /* RTM_CACHEINFO */ struct rta_cacheinfo { __u32 rta_clntref; __u32 rta_lastuse; __s32 rta_expires; __u32 rta_error; __u32 rta_used; #define RTNETLINK_HAVE_PEERINFO 1 __u32 rta_id; __u32 rta_ts; __u32 rta_tsage; }; /* RTM_METRICS --- array of struct rtattr with types of RTAX_* */ enum { RTAX_UNSPEC, #define RTAX_UNSPEC RTAX_UNSPEC RTAX_LOCK, #define RTAX_LOCK RTAX_LOCK RTAX_MTU, #define RTAX_MTU RTAX_MTU RTAX_WINDOW, #define RTAX_WINDOW RTAX_WINDOW RTAX_RTT, #define RTAX_RTT RTAX_RTT RTAX_RTTVAR, #define RTAX_RTTVAR RTAX_RTTVAR RTAX_SSTHRESH, #define RTAX_SSTHRESH RTAX_SSTHRESH RTAX_CWND, #define RTAX_CWND RTAX_CWND RTAX_ADVMSS, #define RTAX_ADVMSS RTAX_ADVMSS RTAX_REORDERING, #define RTAX_REORDERING RTAX_REORDERING RTAX_HOPLIMIT, #define RTAX_HOPLIMIT RTAX_HOPLIMIT RTAX_INITCWND, #define RTAX_INITCWND RTAX_INITCWND RTAX_FEATURES, #define RTAX_FEATURES RTAX_FEATURES RTAX_RTO_MIN, #define RTAX_RTO_MIN RTAX_RTO_MIN RTAX_INITRWND, #define RTAX_INITRWND RTAX_INITRWND RTAX_QUICKACK, #define RTAX_QUICKACK RTAX_QUICKACK RTAX_CC_ALGO, #define RTAX_CC_ALGO RTAX_CC_ALGO RTAX_FASTOPEN_NO_COOKIE, #define RTAX_FASTOPEN_NO_COOKIE RTAX_FASTOPEN_NO_COOKIE __RTAX_MAX }; #define RTAX_MAX (__RTAX_MAX - 1) #define RTAX_FEATURE_ECN (1 << 0) #define RTAX_FEATURE_SACK (1 << 1) #define RTAX_FEATURE_TIMESTAMP (1 << 2) #define RTAX_FEATURE_ALLFRAG (1 << 3) #define RTAX_FEATURE_MASK (RTAX_FEATURE_ECN | RTAX_FEATURE_SACK | \ RTAX_FEATURE_TIMESTAMP | RTAX_FEATURE_ALLFRAG) struct rta_session { __u8 proto; __u8 pad1; __u16 pad2; union { struct { __u16 sport; __u16 dport; } ports; struct { __u8 type; __u8 code; __u16 ident; } icmpt; __u32 spi; } u; }; struct rta_mfc_stats { __u64 mfcs_packets; __u64 mfcs_bytes; __u64 mfcs_wrong_if; }; /**** * General form of address family dependent message. ****/ struct rtgenmsg { unsigned char rtgen_family; }; /***************************************************************** * Link layer specific messages. ****/ /* struct ifinfomsg * passes link level specific information, not dependent * on network protocol. */ struct ifinfomsg { unsigned char ifi_family; unsigned char __ifi_pad; unsigned short ifi_type; /* ARPHRD_* */ int ifi_index; /* Link index */ unsigned ifi_flags; /* IFF_* flags */ unsigned ifi_change; /* IFF_* change mask */ }; /******************************************************************** * prefix information ****/ struct prefixmsg { unsigned char prefix_family; unsigned char prefix_pad1; unsigned short prefix_pad2; int prefix_ifindex; unsigned char prefix_type; unsigned char prefix_len; unsigned char prefix_flags; unsigned char prefix_pad3; }; enum { PREFIX_UNSPEC, PREFIX_ADDRESS, PREFIX_CACHEINFO, __PREFIX_MAX }; #define PREFIX_MAX (__PREFIX_MAX - 1) struct prefix_cacheinfo { __u32 preferred_time; __u32 valid_time; }; /***************************************************************** * Traffic control messages. ****/ struct tcmsg { unsigned char tcm_family; unsigned char tcm__pad1; unsigned short tcm__pad2; int tcm_ifindex; __u32 tcm_handle; __u32 tcm_parent; /* tcm_block_index is used instead of tcm_parent * in case tcm_ifindex == TCM_IFINDEX_MAGIC_BLOCK */ #define tcm_block_index tcm_parent __u32 tcm_info; }; /* For manipulation of filters in shared block, tcm_ifindex is set to * TCM_IFINDEX_MAGIC_BLOCK, and tcm_parent is aliased to tcm_block_index * which is the block index. */ #define TCM_IFINDEX_MAGIC_BLOCK (0xFFFFFFFFU) enum { TCA_UNSPEC, TCA_KIND, TCA_OPTIONS, TCA_STATS, TCA_XSTATS, TCA_RATE, TCA_FCNT, TCA_STATS2, TCA_STAB, TCA_PAD, TCA_DUMP_INVISIBLE, TCA_CHAIN, TCA_HW_OFFLOAD, TCA_INGRESS_BLOCK, TCA_EGRESS_BLOCK, TCA_DUMP_FLAGS, __TCA_MAX }; #define TCA_MAX (__TCA_MAX - 1) #define TCA_DUMP_FLAGS_TERSE (1 << 0) /* Means that in dump user gets only basic * data necessary to identify the objects * (handle, cookie, etc.) and stats. */ #define TCA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct tcmsg)))) #define TCA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct tcmsg)) /******************************************************************** * Neighbor Discovery userland options ****/ struct nduseroptmsg { unsigned char nduseropt_family; unsigned char nduseropt_pad1; unsigned short nduseropt_opts_len; /* Total length of options */ int nduseropt_ifindex; __u8 nduseropt_icmp_type; __u8 nduseropt_icmp_code; unsigned short nduseropt_pad2; unsigned int nduseropt_pad3; /* Followed by one or more ND options */ }; enum { NDUSEROPT_UNSPEC, NDUSEROPT_SRCADDR, __NDUSEROPT_MAX }; #define NDUSEROPT_MAX (__NDUSEROPT_MAX - 1) #ifndef __KERNEL__ /* RTnetlink multicast groups - backwards compatibility for userspace */ #define RTMGRP_LINK 1 #define RTMGRP_NOTIFY 2 #define RTMGRP_NEIGH 4 #define RTMGRP_TC 8 #define RTMGRP_IPV4_IFADDR 0x10 #define RTMGRP_IPV4_MROUTE 0x20 #define RTMGRP_IPV4_ROUTE 0x40 #define RTMGRP_IPV4_RULE 0x80 #define RTMGRP_IPV6_IFADDR 0x100 #define RTMGRP_IPV6_MROUTE 0x200 #define RTMGRP_IPV6_ROUTE 0x400 #define RTMGRP_IPV6_IFINFO 0x800 #define RTMGRP_DECnet_IFADDR 0x1000 #define RTMGRP_DECnet_ROUTE 0x4000 #define RTMGRP_IPV6_PREFIX 0x20000 #endif /* RTnetlink multicast groups */ enum rtnetlink_groups { RTNLGRP_NONE, #define RTNLGRP_NONE RTNLGRP_NONE RTNLGRP_LINK, #define RTNLGRP_LINK RTNLGRP_LINK RTNLGRP_NOTIFY, #define RTNLGRP_NOTIFY RTNLGRP_NOTIFY RTNLGRP_NEIGH, #define RTNLGRP_NEIGH RTNLGRP_NEIGH RTNLGRP_TC, #define RTNLGRP_TC RTNLGRP_TC RTNLGRP_IPV4_IFADDR, #define RTNLGRP_IPV4_IFADDR RTNLGRP_IPV4_IFADDR RTNLGRP_IPV4_MROUTE, #define RTNLGRP_IPV4_MROUTE RTNLGRP_IPV4_MROUTE RTNLGRP_IPV4_ROUTE, #define RTNLGRP_IPV4_ROUTE RTNLGRP_IPV4_ROUTE RTNLGRP_IPV4_RULE, #define RTNLGRP_IPV4_RULE RTNLGRP_IPV4_RULE RTNLGRP_IPV6_IFADDR, #define RTNLGRP_IPV6_IFADDR RTNLGRP_IPV6_IFADDR RTNLGRP_IPV6_MROUTE, #define RTNLGRP_IPV6_MROUTE RTNLGRP_IPV6_MROUTE RTNLGRP_IPV6_ROUTE, #define RTNLGRP_IPV6_ROUTE RTNLGRP_IPV6_ROUTE RTNLGRP_IPV6_IFINFO, #define RTNLGRP_IPV6_IFINFO RTNLGRP_IPV6_IFINFO RTNLGRP_DECnet_IFADDR, #define RTNLGRP_DECnet_IFADDR RTNLGRP_DECnet_IFADDR RTNLGRP_NOP2, RTNLGRP_DECnet_ROUTE, #define RTNLGRP_DECnet_ROUTE RTNLGRP_DECnet_ROUTE RTNLGRP_DECnet_RULE, #define RTNLGRP_DECnet_RULE RTNLGRP_DECnet_RULE RTNLGRP_NOP4, RTNLGRP_IPV6_PREFIX, #define RTNLGRP_IPV6_PREFIX RTNLGRP_IPV6_PREFIX RTNLGRP_IPV6_RULE, #define RTNLGRP_IPV6_RULE RTNLGRP_IPV6_RULE RTNLGRP_ND_USEROPT, #define RTNLGRP_ND_USEROPT RTNLGRP_ND_USEROPT RTNLGRP_PHONET_IFADDR, #define RTNLGRP_PHONET_IFADDR RTNLGRP_PHONET_IFADDR RTNLGRP_PHONET_ROUTE, #define RTNLGRP_PHONET_ROUTE RTNLGRP_PHONET_ROUTE RTNLGRP_DCB, #define RTNLGRP_DCB RTNLGRP_DCB RTNLGRP_IPV4_NETCONF, #define RTNLGRP_IPV4_NETCONF RTNLGRP_IPV4_NETCONF RTNLGRP_IPV6_NETCONF, #define RTNLGRP_IPV6_NETCONF RTNLGRP_IPV6_NETCONF RTNLGRP_MDB, #define RTNLGRP_MDB RTNLGRP_MDB RTNLGRP_MPLS_ROUTE, #define RTNLGRP_MPLS_ROUTE RTNLGRP_MPLS_ROUTE RTNLGRP_NSID, #define RTNLGRP_NSID RTNLGRP_NSID RTNLGRP_MPLS_NETCONF, #define RTNLGRP_MPLS_NETCONF RTNLGRP_MPLS_NETCONF RTNLGRP_IPV4_MROUTE_R, #define RTNLGRP_IPV4_MROUTE_R RTNLGRP_IPV4_MROUTE_R RTNLGRP_IPV6_MROUTE_R, #define RTNLGRP_IPV6_MROUTE_R RTNLGRP_IPV6_MROUTE_R RTNLGRP_NEXTHOP, #define RTNLGRP_NEXTHOP RTNLGRP_NEXTHOP RTNLGRP_BRVLAN, #define RTNLGRP_BRVLAN RTNLGRP_BRVLAN RTNLGRP_MCTP_IFADDR, #define RTNLGRP_MCTP_IFADDR RTNLGRP_MCTP_IFADDR RTNLGRP_TUNNEL, #define RTNLGRP_TUNNEL RTNLGRP_TUNNEL RTNLGRP_STATS, #define RTNLGRP_STATS RTNLGRP_STATS __RTNLGRP_MAX }; #define RTNLGRP_MAX (__RTNLGRP_MAX - 1) /* TC action piece */ struct tcamsg { unsigned char tca_family; unsigned char tca__pad1; unsigned short tca__pad2; }; enum { TCA_ROOT_UNSPEC, TCA_ROOT_TAB, #define TCA_ACT_TAB TCA_ROOT_TAB #define TCAA_MAX TCA_ROOT_TAB TCA_ROOT_FLAGS, TCA_ROOT_COUNT, TCA_ROOT_TIME_DELTA, /* in msecs */ __TCA_ROOT_MAX, #define TCA_ROOT_MAX (__TCA_ROOT_MAX - 1) }; #define TA_RTA(r) ((struct rtattr*)(((char*)(r)) + NLMSG_ALIGN(sizeof(struct tcamsg)))) #define TA_PAYLOAD(n) NLMSG_PAYLOAD(n,sizeof(struct tcamsg)) /* tcamsg flags stored in attribute TCA_ROOT_FLAGS * * TCA_ACT_FLAG_LARGE_DUMP_ON user->kernel to request for larger than * TCA_ACT_MAX_PRIO actions in a dump. All dump responses will contain the * number of actions being dumped stored in for user app's consumption in * TCA_ROOT_COUNT * * TCA_ACT_FLAG_TERSE_DUMP user->kernel to request terse (brief) dump that only * includes essential action info (kind, index, etc.) * */ #define TCA_FLAG_LARGE_DUMP_ON (1 << 0) #define TCA_ACT_FLAG_LARGE_DUMP_ON TCA_FLAG_LARGE_DUMP_ON #define TCA_ACT_FLAG_TERSE_DUMP (1 << 1) /* New extended info filters for IFLA_EXT_MASK */ #define RTEXT_FILTER_VF (1 << 0) #define RTEXT_FILTER_BRVLAN (1 << 1) #define RTEXT_FILTER_BRVLAN_COMPRESSED (1 << 2) #define RTEXT_FILTER_SKIP_STATS (1 << 3) #define RTEXT_FILTER_MRP (1 << 4) #define RTEXT_FILTER_CFM_CONFIG (1 << 5) #define RTEXT_FILTER_CFM_STATUS (1 << 6) #define RTEXT_FILTER_MST (1 << 7) /* End of information exported to user level */ #endif /* _UAPI__LINUX_RTNETLINK_H */
21,209
24.646917
93
h
null
systemd-main/src/basic/linux/stddef.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _UAPI_LINUX_STDDEF_H #define _UAPI_LINUX_STDDEF_H #ifndef __always_inline #define __always_inline inline #endif /** * __struct_group() - Create a mirrored named and anonyomous struct * * @TAG: The tag name for the named sub-struct (usually empty) * @NAME: The identifier name of the mirrored sub-struct * @ATTRS: Any struct attributes (usually empty) * @MEMBERS: The member declarations for the mirrored structs * * Used to create an anonymous union of two structs with identical layout * and size: one anonymous and one named. The former's members can be used * normally without sub-struct naming, and the latter can be used to * reason about the start, end, and size of the group of struct members. * The named struct can also be explicitly tagged for layer reuse, as well * as both having struct attributes appended. */ #define __struct_group(TAG, NAME, ATTRS, MEMBERS...) \ union { \ struct { MEMBERS } ATTRS; \ struct TAG { MEMBERS } ATTRS NAME; \ } /** * __DECLARE_FLEX_ARRAY() - Declare a flexible array usable in a union * * @TYPE: The type of each flexible array element * @NAME: The name of the flexible array member * * In order to have a flexible array member in a union or alone in a * struct, it needs to be wrapped in an anonymous struct with at least 1 * named member, but that member can be empty. */ #define __DECLARE_FLEX_ARRAY(TYPE, NAME) \ struct { \ struct { } __empty_ ## NAME; \ TYPE NAME[]; \ } #endif
1,537
31.723404
74
h
null
systemd-main/src/basic/linux/wireguard.h
/* SPDX-License-Identifier: (GPL-2.0 WITH Linux-syscall-note) OR MIT */ /* * Copyright (C) 2015-2019 Jason A. Donenfeld <[email protected]>. All Rights Reserved. * * Documentation * ============= * * The below enums and macros are for interfacing with WireGuard, using generic * netlink, with family WG_GENL_NAME and version WG_GENL_VERSION. It defines two * methods: get and set. Note that while they share many common attributes, * these two functions actually accept a slightly different set of inputs and * outputs. * * WG_CMD_GET_DEVICE * ----------------- * * May only be called via NLM_F_REQUEST | NLM_F_DUMP. The command should contain * one but not both of: * * WGDEVICE_A_IFINDEX: NLA_U32 * WGDEVICE_A_IFNAME: NLA_NUL_STRING, maxlen IFNAMSIZ - 1 * * The kernel will then return several messages (NLM_F_MULTI) containing the * following tree of nested items: * * WGDEVICE_A_IFINDEX: NLA_U32 * WGDEVICE_A_IFNAME: NLA_NUL_STRING, maxlen IFNAMSIZ - 1 * WGDEVICE_A_PRIVATE_KEY: NLA_EXACT_LEN, len WG_KEY_LEN * WGDEVICE_A_PUBLIC_KEY: NLA_EXACT_LEN, len WG_KEY_LEN * WGDEVICE_A_LISTEN_PORT: NLA_U16 * WGDEVICE_A_FWMARK: NLA_U32 * WGDEVICE_A_PEERS: NLA_NESTED * 0: NLA_NESTED * WGPEER_A_PUBLIC_KEY: NLA_EXACT_LEN, len WG_KEY_LEN * WGPEER_A_PRESHARED_KEY: NLA_EXACT_LEN, len WG_KEY_LEN * WGPEER_A_ENDPOINT: NLA_MIN_LEN(struct sockaddr), struct sockaddr_in or struct sockaddr_in6 * WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL: NLA_U16 * WGPEER_A_LAST_HANDSHAKE_TIME: NLA_EXACT_LEN, struct __kernel_timespec * WGPEER_A_RX_BYTES: NLA_U64 * WGPEER_A_TX_BYTES: NLA_U64 * WGPEER_A_ALLOWEDIPS: NLA_NESTED * 0: NLA_NESTED * WGALLOWEDIP_A_FAMILY: NLA_U16 * WGALLOWEDIP_A_IPADDR: NLA_MIN_LEN(struct in_addr), struct in_addr or struct in6_addr * WGALLOWEDIP_A_CIDR_MASK: NLA_U8 * 0: NLA_NESTED * ... * 0: NLA_NESTED * ... * ... * WGPEER_A_PROTOCOL_VERSION: NLA_U32 * 0: NLA_NESTED * ... * ... * * It is possible that all of the allowed IPs of a single peer will not * fit within a single netlink message. In that case, the same peer will * be written in the following message, except it will only contain * WGPEER_A_PUBLIC_KEY and WGPEER_A_ALLOWEDIPS. This may occur several * times in a row for the same peer. It is then up to the receiver to * coalesce adjacent peers. Likewise, it is possible that all peers will * not fit within a single message. So, subsequent peers will be sent * in following messages, except those will only contain WGDEVICE_A_IFNAME * and WGDEVICE_A_PEERS. It is then up to the receiver to coalesce these * messages to form the complete list of peers. * * Since this is an NLA_F_DUMP command, the final message will always be * NLMSG_DONE, even if an error occurs. However, this NLMSG_DONE message * contains an integer error code. It is either zero or a negative error * code corresponding to the errno. * * WG_CMD_SET_DEVICE * ----------------- * * May only be called via NLM_F_REQUEST. The command should contain the * following tree of nested items, containing one but not both of * WGDEVICE_A_IFINDEX and WGDEVICE_A_IFNAME: * * WGDEVICE_A_IFINDEX: NLA_U32 * WGDEVICE_A_IFNAME: NLA_NUL_STRING, maxlen IFNAMSIZ - 1 * WGDEVICE_A_FLAGS: NLA_U32, 0 or WGDEVICE_F_REPLACE_PEERS if all current * peers should be removed prior to adding the list below. * WGDEVICE_A_PRIVATE_KEY: len WG_KEY_LEN, all zeros to remove * WGDEVICE_A_LISTEN_PORT: NLA_U16, 0 to choose randomly * WGDEVICE_A_FWMARK: NLA_U32, 0 to disable * WGDEVICE_A_PEERS: NLA_NESTED * 0: NLA_NESTED * WGPEER_A_PUBLIC_KEY: len WG_KEY_LEN * WGPEER_A_FLAGS: NLA_U32, 0 and/or WGPEER_F_REMOVE_ME if the * specified peer should not exist at the end of the * operation, rather than added/updated and/or * WGPEER_F_REPLACE_ALLOWEDIPS if all current allowed * IPs of this peer should be removed prior to adding * the list below and/or WGPEER_F_UPDATE_ONLY if the * peer should only be set if it already exists. * WGPEER_A_PRESHARED_KEY: len WG_KEY_LEN, all zeros to remove * WGPEER_A_ENDPOINT: struct sockaddr_in or struct sockaddr_in6 * WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL: NLA_U16, 0 to disable * WGPEER_A_ALLOWEDIPS: NLA_NESTED * 0: NLA_NESTED * WGALLOWEDIP_A_FAMILY: NLA_U16 * WGALLOWEDIP_A_IPADDR: struct in_addr or struct in6_addr * WGALLOWEDIP_A_CIDR_MASK: NLA_U8 * 0: NLA_NESTED * ... * 0: NLA_NESTED * ... * ... * WGPEER_A_PROTOCOL_VERSION: NLA_U32, should not be set or used at * all by most users of this API, as the * most recent protocol will be used when * this is unset. Otherwise, must be set * to 1. * 0: NLA_NESTED * ... * ... * * It is possible that the amount of configuration data exceeds that of * the maximum message length accepted by the kernel. In that case, several * messages should be sent one after another, with each successive one * filling in information not contained in the prior. Note that if * WGDEVICE_F_REPLACE_PEERS is specified in the first message, it probably * should not be specified in fragments that come after, so that the list * of peers is only cleared the first time but appended after. Likewise for * peers, if WGPEER_F_REPLACE_ALLOWEDIPS is specified in the first message * of a peer, it likely should not be specified in subsequent fragments. * * If an error occurs, NLMSG_ERROR will reply containing an errno. */ #ifndef _WG_UAPI_WIREGUARD_H #define _WG_UAPI_WIREGUARD_H #define WG_GENL_NAME "wireguard" #define WG_GENL_VERSION 1 #define WG_KEY_LEN 32 enum wg_cmd { WG_CMD_GET_DEVICE, WG_CMD_SET_DEVICE, __WG_CMD_MAX }; #define WG_CMD_MAX (__WG_CMD_MAX - 1) enum wgdevice_flag { WGDEVICE_F_REPLACE_PEERS = 1U << 0, __WGDEVICE_F_ALL = WGDEVICE_F_REPLACE_PEERS }; enum wgdevice_attribute { WGDEVICE_A_UNSPEC, WGDEVICE_A_IFINDEX, WGDEVICE_A_IFNAME, WGDEVICE_A_PRIVATE_KEY, WGDEVICE_A_PUBLIC_KEY, WGDEVICE_A_FLAGS, WGDEVICE_A_LISTEN_PORT, WGDEVICE_A_FWMARK, WGDEVICE_A_PEERS, __WGDEVICE_A_LAST }; #define WGDEVICE_A_MAX (__WGDEVICE_A_LAST - 1) enum wgpeer_flag { WGPEER_F_REMOVE_ME = 1U << 0, WGPEER_F_REPLACE_ALLOWEDIPS = 1U << 1, WGPEER_F_UPDATE_ONLY = 1U << 2, __WGPEER_F_ALL = WGPEER_F_REMOVE_ME | WGPEER_F_REPLACE_ALLOWEDIPS | WGPEER_F_UPDATE_ONLY }; enum wgpeer_attribute { WGPEER_A_UNSPEC, WGPEER_A_PUBLIC_KEY, WGPEER_A_PRESHARED_KEY, WGPEER_A_FLAGS, WGPEER_A_ENDPOINT, WGPEER_A_PERSISTENT_KEEPALIVE_INTERVAL, WGPEER_A_LAST_HANDSHAKE_TIME, WGPEER_A_RX_BYTES, WGPEER_A_TX_BYTES, WGPEER_A_ALLOWEDIPS, WGPEER_A_PROTOCOL_VERSION, __WGPEER_A_LAST }; #define WGPEER_A_MAX (__WGPEER_A_LAST - 1) enum wgallowedip_attribute { WGALLOWEDIP_A_UNSPEC, WGALLOWEDIP_A_FAMILY, WGALLOWEDIP_A_IPADDR, WGALLOWEDIP_A_CIDR_MASK, __WGALLOWEDIP_A_LAST }; #define WGALLOWEDIP_A_MAX (__WGALLOWEDIP_A_LAST - 1) #endif /* _WG_UAPI_WIREGUARD_H */
7,748
38.335025
106
h
null
systemd-main/src/basic/linux/can/netlink.h
/* SPDX-License-Identifier: GPL-2.0-only WITH Linux-syscall-note */ /* * linux/can/netlink.h * * Definitions for the CAN netlink interface * * Copyright (c) 2009 Wolfgang Grandegger <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the version 2 of the GNU General Public License * as published by the Free Software Foundation * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #ifndef _UAPI_CAN_NETLINK_H #define _UAPI_CAN_NETLINK_H #include <linux/types.h> /* * CAN bit-timing parameters * * For further information, please read chapter "8 BIT TIMING * REQUIREMENTS" of the "Bosch CAN Specification version 2.0" * at http://www.semiconductors.bosch.de/pdf/can2spec.pdf. */ struct can_bittiming { __u32 bitrate; /* Bit-rate in bits/second */ __u32 sample_point; /* Sample point in one-tenth of a percent */ __u32 tq; /* Time quanta (TQ) in nanoseconds */ __u32 prop_seg; /* Propagation segment in TQs */ __u32 phase_seg1; /* Phase buffer segment 1 in TQs */ __u32 phase_seg2; /* Phase buffer segment 2 in TQs */ __u32 sjw; /* Synchronisation jump width in TQs */ __u32 brp; /* Bit-rate prescaler */ }; /* * CAN hardware-dependent bit-timing constant * * Used for calculating and checking bit-timing parameters */ struct can_bittiming_const { char name[16]; /* Name of the CAN controller hardware */ __u32 tseg1_min; /* Time segment 1 = prop_seg + phase_seg1 */ __u32 tseg1_max; __u32 tseg2_min; /* Time segment 2 = phase_seg2 */ __u32 tseg2_max; __u32 sjw_max; /* Synchronisation jump width */ __u32 brp_min; /* Bit-rate prescaler */ __u32 brp_max; __u32 brp_inc; }; /* * CAN clock parameters */ struct can_clock { __u32 freq; /* CAN system clock frequency in Hz */ }; /* * CAN operational and error states */ enum can_state { CAN_STATE_ERROR_ACTIVE = 0, /* RX/TX error count < 96 */ CAN_STATE_ERROR_WARNING, /* RX/TX error count < 128 */ CAN_STATE_ERROR_PASSIVE, /* RX/TX error count < 256 */ CAN_STATE_BUS_OFF, /* RX/TX error count >= 256 */ CAN_STATE_STOPPED, /* Device is stopped */ CAN_STATE_SLEEPING, /* Device is sleeping */ CAN_STATE_MAX }; /* * CAN bus error counters */ struct can_berr_counter { __u16 txerr; __u16 rxerr; }; /* * CAN controller mode */ struct can_ctrlmode { __u32 mask; __u32 flags; }; #define CAN_CTRLMODE_LOOPBACK 0x01 /* Loopback mode */ #define CAN_CTRLMODE_LISTENONLY 0x02 /* Listen-only mode */ #define CAN_CTRLMODE_3_SAMPLES 0x04 /* Triple sampling mode */ #define CAN_CTRLMODE_ONE_SHOT 0x08 /* One-Shot mode */ #define CAN_CTRLMODE_BERR_REPORTING 0x10 /* Bus-error reporting */ #define CAN_CTRLMODE_FD 0x20 /* CAN FD mode */ #define CAN_CTRLMODE_PRESUME_ACK 0x40 /* Ignore missing CAN ACKs */ #define CAN_CTRLMODE_FD_NON_ISO 0x80 /* CAN FD in non-ISO mode */ #define CAN_CTRLMODE_CC_LEN8_DLC 0x100 /* Classic CAN DLC option */ #define CAN_CTRLMODE_TDC_AUTO 0x200 /* CAN transiver automatically calculates TDCV */ #define CAN_CTRLMODE_TDC_MANUAL 0x400 /* TDCV is manually set up by user */ /* * CAN device statistics */ struct can_device_stats { __u32 bus_error; /* Bus errors */ __u32 error_warning; /* Changes to error warning state */ __u32 error_passive; /* Changes to error passive state */ __u32 bus_off; /* Changes to bus off state */ __u32 arbitration_lost; /* Arbitration lost errors */ __u32 restarts; /* CAN controller re-starts */ }; /* * CAN netlink interface */ enum { IFLA_CAN_UNSPEC, IFLA_CAN_BITTIMING, IFLA_CAN_BITTIMING_CONST, IFLA_CAN_CLOCK, IFLA_CAN_STATE, IFLA_CAN_CTRLMODE, IFLA_CAN_RESTART_MS, IFLA_CAN_RESTART, IFLA_CAN_BERR_COUNTER, IFLA_CAN_DATA_BITTIMING, IFLA_CAN_DATA_BITTIMING_CONST, IFLA_CAN_TERMINATION, IFLA_CAN_TERMINATION_CONST, IFLA_CAN_BITRATE_CONST, IFLA_CAN_DATA_BITRATE_CONST, IFLA_CAN_BITRATE_MAX, IFLA_CAN_TDC, IFLA_CAN_CTRLMODE_EXT, /* add new constants above here */ __IFLA_CAN_MAX, IFLA_CAN_MAX = __IFLA_CAN_MAX - 1 }; /* * CAN FD Transmitter Delay Compensation (TDC) * * Please refer to struct can_tdc_const and can_tdc in * include/linux/can/bittiming.h for further details. */ enum { IFLA_CAN_TDC_UNSPEC, IFLA_CAN_TDC_TDCV_MIN, /* u32 */ IFLA_CAN_TDC_TDCV_MAX, /* u32 */ IFLA_CAN_TDC_TDCO_MIN, /* u32 */ IFLA_CAN_TDC_TDCO_MAX, /* u32 */ IFLA_CAN_TDC_TDCF_MIN, /* u32 */ IFLA_CAN_TDC_TDCF_MAX, /* u32 */ IFLA_CAN_TDC_TDCV, /* u32 */ IFLA_CAN_TDC_TDCO, /* u32 */ IFLA_CAN_TDC_TDCF, /* u32 */ /* add new constants above here */ __IFLA_CAN_TDC, IFLA_CAN_TDC_MAX = __IFLA_CAN_TDC - 1 }; /* * IFLA_CAN_CTRLMODE_EXT nest: controller mode extended parameters */ enum { IFLA_CAN_CTRLMODE_UNSPEC, IFLA_CAN_CTRLMODE_SUPPORTED, /* u32 */ /* add new constants above here */ __IFLA_CAN_CTRLMODE, IFLA_CAN_CTRLMODE_MAX = __IFLA_CAN_CTRLMODE - 1 }; /* u16 termination range: 1..65535 Ohms */ #define CAN_TERMINATION_DISABLED 0 #endif /* !_UAPI_CAN_NETLINK_H */
5,150
26.693548
86
h
null
systemd-main/src/basic/linux/hdlc/ioctl.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef __HDLC_IOCTL_H__ #define __HDLC_IOCTL_H__ #define GENERIC_HDLC_VERSION 4 /* For synchronization with sethdlc utility */ #define CLOCK_DEFAULT 0 /* Default setting */ #define CLOCK_EXT 1 /* External TX and RX clock - DTE */ #define CLOCK_INT 2 /* Internal TX and RX clock - DCE */ #define CLOCK_TXINT 3 /* Internal TX and external RX clock */ #define CLOCK_TXFROMRX 4 /* TX clock derived from external RX clock */ #define ENCODING_DEFAULT 0 /* Default setting */ #define ENCODING_NRZ 1 #define ENCODING_NRZI 2 #define ENCODING_FM_MARK 3 #define ENCODING_FM_SPACE 4 #define ENCODING_MANCHESTER 5 #define PARITY_DEFAULT 0 /* Default setting */ #define PARITY_NONE 1 /* No parity */ #define PARITY_CRC16_PR0 2 /* CRC16, initial value 0x0000 */ #define PARITY_CRC16_PR1 3 /* CRC16, initial value 0xFFFF */ #define PARITY_CRC16_PR0_CCITT 4 /* CRC16, initial 0x0000, ITU-T version */ #define PARITY_CRC16_PR1_CCITT 5 /* CRC16, initial 0xFFFF, ITU-T version */ #define PARITY_CRC32_PR0_CCITT 6 /* CRC32, initial value 0x00000000 */ #define PARITY_CRC32_PR1_CCITT 7 /* CRC32, initial value 0xFFFFFFFF */ #define LMI_DEFAULT 0 /* Default setting */ #define LMI_NONE 1 /* No LMI, all PVCs are static */ #define LMI_ANSI 2 /* ANSI Annex D */ #define LMI_CCITT 3 /* ITU-T Annex A */ #define LMI_CISCO 4 /* The "original" LMI, aka Gang of Four */ #ifndef __ASSEMBLY__ typedef struct { unsigned int clock_rate; /* bits per second */ unsigned int clock_type; /* internal, external, TX-internal etc. */ unsigned short loopback; } sync_serial_settings; /* V.35, V.24, X.21 */ typedef struct { unsigned int clock_rate; /* bits per second */ unsigned int clock_type; /* internal, external, TX-internal etc. */ unsigned short loopback; unsigned int slot_map; } te1_settings; /* T1, E1 */ typedef struct { unsigned short encoding; unsigned short parity; } raw_hdlc_proto; typedef struct { unsigned int t391; unsigned int t392; unsigned int n391; unsigned int n392; unsigned int n393; unsigned short lmi; unsigned short dce; /* 1 for DCE (network side) operation */ } fr_proto; typedef struct { unsigned int dlci; } fr_proto_pvc; /* for creating/deleting FR PVCs */ typedef struct { unsigned int dlci; char master[IFNAMSIZ]; /* Name of master FRAD device */ }fr_proto_pvc_info; /* for returning PVC information only */ typedef struct { unsigned int interval; unsigned int timeout; } cisco_proto; typedef struct { unsigned short dce; /* 1 for DCE (network side) operation */ unsigned int modulo; /* modulo (8 = basic / 128 = extended) */ unsigned int window; /* frame window size */ unsigned int t1; /* timeout t1 */ unsigned int t2; /* timeout t2 */ unsigned int n2; /* frame retry counter */ } x25_hdlc_proto; /* PPP doesn't need any info now - supply length = 0 to ioctl */ #endif /* __ASSEMBLY__ */ #endif /* __HDLC_IOCTL_H__ */
2,979
30.368421
77
h
null
systemd-main/src/basic/linux/netfilter/nfnetlink.h
/* SPDX-License-Identifier: GPL-2.0 WITH Linux-syscall-note */ #ifndef _UAPI_NFNETLINK_H #define _UAPI_NFNETLINK_H #include <linux/types.h> #include <linux/netfilter/nfnetlink_compat.h> enum nfnetlink_groups { NFNLGRP_NONE, #define NFNLGRP_NONE NFNLGRP_NONE NFNLGRP_CONNTRACK_NEW, #define NFNLGRP_CONNTRACK_NEW NFNLGRP_CONNTRACK_NEW NFNLGRP_CONNTRACK_UPDATE, #define NFNLGRP_CONNTRACK_UPDATE NFNLGRP_CONNTRACK_UPDATE NFNLGRP_CONNTRACK_DESTROY, #define NFNLGRP_CONNTRACK_DESTROY NFNLGRP_CONNTRACK_DESTROY NFNLGRP_CONNTRACK_EXP_NEW, #define NFNLGRP_CONNTRACK_EXP_NEW NFNLGRP_CONNTRACK_EXP_NEW NFNLGRP_CONNTRACK_EXP_UPDATE, #define NFNLGRP_CONNTRACK_EXP_UPDATE NFNLGRP_CONNTRACK_EXP_UPDATE NFNLGRP_CONNTRACK_EXP_DESTROY, #define NFNLGRP_CONNTRACK_EXP_DESTROY NFNLGRP_CONNTRACK_EXP_DESTROY NFNLGRP_NFTABLES, #define NFNLGRP_NFTABLES NFNLGRP_NFTABLES NFNLGRP_ACCT_QUOTA, #define NFNLGRP_ACCT_QUOTA NFNLGRP_ACCT_QUOTA NFNLGRP_NFTRACE, #define NFNLGRP_NFTRACE NFNLGRP_NFTRACE __NFNLGRP_MAX, }; #define NFNLGRP_MAX (__NFNLGRP_MAX - 1) /* General form of address family dependent message. */ struct nfgenmsg { __u8 nfgen_family; /* AF_xxx */ __u8 version; /* nfnetlink version */ __be16 res_id; /* resource id */ }; #define NFNETLINK_V0 0 /* netfilter netlink message types are split in two pieces: * 8 bit subsystem, 8bit operation. */ #define NFNL_SUBSYS_ID(x) ((x & 0xff00) >> 8) #define NFNL_MSG_TYPE(x) (x & 0x00ff) /* No enum here, otherwise __stringify() trick of MODULE_ALIAS_NFNL_SUBSYS() * won't work anymore */ #define NFNL_SUBSYS_NONE 0 #define NFNL_SUBSYS_CTNETLINK 1 #define NFNL_SUBSYS_CTNETLINK_EXP 2 #define NFNL_SUBSYS_QUEUE 3 #define NFNL_SUBSYS_ULOG 4 #define NFNL_SUBSYS_OSF 5 #define NFNL_SUBSYS_IPSET 6 #define NFNL_SUBSYS_ACCT 7 #define NFNL_SUBSYS_CTNETLINK_TIMEOUT 8 #define NFNL_SUBSYS_CTHELPER 9 #define NFNL_SUBSYS_NFTABLES 10 #define NFNL_SUBSYS_NFT_COMPAT 11 #define NFNL_SUBSYS_HOOK 12 #define NFNL_SUBSYS_COUNT 13 /* Reserved control nfnetlink messages */ #define NFNL_MSG_BATCH_BEGIN NLMSG_MIN_TYPE #define NFNL_MSG_BATCH_END NLMSG_MIN_TYPE+1 /** * enum nfnl_batch_attributes - nfnetlink batch netlink attributes * * @NFNL_BATCH_GENID: generation ID for this changeset (NLA_U32) */ enum nfnl_batch_attributes { NFNL_BATCH_UNSPEC, NFNL_BATCH_GENID, __NFNL_BATCH_MAX }; #define NFNL_BATCH_MAX (__NFNL_BATCH_MAX - 1) #endif /* _UAPI_NFNETLINK_H */
2,472
28.795181
76
h
null
systemd-main/src/binfmt/binfmt.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <getopt.h> #include <limits.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <sys/types.h> #include "alloc-util.h" #include "binfmt-util.h" #include "build.h" #include "conf-files.h" #include "constants.h" #include "fd-util.h" #include "fileio.h" #include "log.h" #include "main-func.h" #include "pager.h" #include "path-util.h" #include "pretty-print.h" #include "string-util.h" #include "strv.h" static bool arg_cat_config = false; static PagerFlags arg_pager_flags = 0; static bool arg_unregister = false; static int delete_rule(const char *rulename) { const char *fn = strjoina("/proc/sys/fs/binfmt_misc/", rulename); return write_string_file(fn, "-1", WRITE_STRING_FILE_DISABLE_BUFFER); } static int apply_rule(const char *filename, unsigned line, const char *rule) { assert(filename); assert(line > 0); assert(rule); assert(rule[0]); _cleanup_free_ char *rulename = NULL; int r; rulename = strdupcspn(rule + 1, CHAR_TO_STR(rule[0])); if (!rulename) return log_oom(); if (!filename_is_valid(rulename) || STR_IN_SET(rulename, "register", "status")) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "%s:%u: Rule name '%s' is not valid, refusing.", filename, line, rulename); r = delete_rule(rulename); if (r < 0 && r != -ENOENT) log_warning_errno(r, "%s:%u: Failed to delete rule '%s', ignoring: %m", filename, line, rulename); if (r >= 0) log_debug("%s:%u: Rule '%s' deleted.", filename, line, rulename); r = write_string_file("/proc/sys/fs/binfmt_misc/register", rule, WRITE_STRING_FILE_DISABLE_BUFFER); if (r < 0) return log_error_errno(r, "%s:%u: Failed to add binary format '%s': %m", filename, line, rulename); log_debug("%s:%u: Binary format '%s' registered.", filename, line, rulename); return 0; } static int apply_file(const char *filename, bool ignore_enoent) { _cleanup_fclose_ FILE *f = NULL; _cleanup_free_ char *pp = NULL; int r; assert(filename); r = search_and_fopen(filename, "re", NULL, (const char**) CONF_PATHS_STRV("binfmt.d"), &f, &pp); if (r < 0) { if (ignore_enoent && r == -ENOENT) return 0; return log_error_errno(r, "Failed to open file '%s': %m", filename); } log_debug("Applying %s%s", pp, special_glyph(SPECIAL_GLYPH_ELLIPSIS)); for (unsigned line = 1;; line++) { _cleanup_free_ char *text = NULL; char *p; int k; k = read_line(f, LONG_LINE_MAX, &text); if (k < 0) return log_error_errno(k, "Failed to read file '%s': %m", pp); if (k == 0) break; p = strstrip(text); if (isempty(p)) continue; if (strchr(COMMENTS, p[0])) continue; k = apply_rule(filename, line, p); if (k < 0 && r >= 0) r = k; } return r; } static int help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("systemd-binfmt.service", "8", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...] [CONFIGURATION FILE...]\n\n" "Registers binary formats with the kernel.\n\n" " -h --help Show this help\n" " --version Show package version\n" " --cat-config Show configuration files\n" " --no-pager Do not pipe output into a pager\n" " --unregister Unregister all existing entries\n" "\nSee the %s for details.\n", program_invocation_short_name, link); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_VERSION = 0x100, ARG_CAT_CONFIG, ARG_NO_PAGER, ARG_UNREGISTER, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "cat-config", no_argument, NULL, ARG_CAT_CONFIG }, { "no-pager", no_argument, NULL, ARG_NO_PAGER }, { "unregister", no_argument, NULL, ARG_UNREGISTER }, {} }; int c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': return help(); case ARG_VERSION: return version(); case ARG_CAT_CONFIG: arg_cat_config = true; break; case ARG_NO_PAGER: arg_pager_flags |= PAGER_DISABLE; break; case ARG_UNREGISTER: arg_unregister = true; break; case '?': return -EINVAL; default: assert_not_reached(); } if ((arg_unregister || arg_cat_config) && argc > optind) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Positional arguments are not allowed with --cat-config or --unregister"); return 1; } static int binfmt_mounted_warn(void) { int r; r = binfmt_mounted(); if (r < 0) return log_error_errno(r, "Failed to check if /proc/sys/fs/binfmt_misc is mounted: %m"); if (r == 0) log_debug("/proc/sys/fs/binfmt_misc is not mounted in read-write mode, skipping."); return r; } static int run(int argc, char *argv[]) { int r, k; r = parse_argv(argc, argv); if (r <= 0) return r; log_setup(); umask(0022); r = 0; if (arg_unregister) return disable_binfmt(); if (argc > optind) { r = binfmt_mounted_warn(); if (r <= 0) return r; for (int i = optind; i < argc; i++) { k = apply_file(argv[i], false); if (k < 0 && r >= 0) r = k; } } else { _cleanup_strv_free_ char **files = NULL; r = conf_files_list_strv(&files, ".conf", NULL, 0, (const char**) CONF_PATHS_STRV("binfmt.d")); if (r < 0) return log_error_errno(r, "Failed to enumerate binfmt.d files: %m"); if (arg_cat_config) { pager_open(arg_pager_flags); return cat_files(NULL, files, 0); } r = binfmt_mounted_warn(); if (r <= 0) return r; /* Flush out all rules */ r = write_string_file("/proc/sys/fs/binfmt_misc/status", "-1", WRITE_STRING_FILE_DISABLE_BUFFER); if (r < 0) log_warning_errno(r, "Failed to flush binfmt_misc rules, ignoring: %m"); else log_debug("Flushed all binfmt_misc rules."); STRV_FOREACH(f, files) { k = apply_file(*f, true); if (k < 0 && r >= 0) r = k; } } return r; } DEFINE_MAIN_FUNCTION(run);
8,215
30.121212
113
c
null
systemd-main/src/boot/bless-boot-generator.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <unistd.h> #include "efi-loader.h" #include "generator.h" #include "initrd-util.h" #include "log.h" #include "mkdir.h" #include "special.h" #include "string-util.h" #include "virt.h" /* This generator pulls systemd-bless-boot.service into the initial transaction if the "LoaderBootCountPath" * EFI variable is set, i.e. the system boots up with boot counting in effect, which means we should mark the * boot as "good" if we manage to boot up far enough. */ static int run(const char *dest, const char *dest_early, const char *dest_late) { if (in_initrd()) { log_debug("Skipping generator, running in the initrd."); return EXIT_SUCCESS; } if (detect_container() > 0) { log_debug("Skipping generator, running in a container."); return 0; } if (!is_efi_boot()) { log_debug("Skipping generator, not an EFI boot."); return 0; } if (access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderBootCountPath)), F_OK) < 0) { if (errno == ENOENT) { log_debug_errno(errno, "Skipping generator, not booted with boot counting in effect."); return 0; } return log_error_errno(errno, "Failed to check if LoaderBootCountPath EFI variable exists: %m"); } /* We pull this in from basic.target so that it ends up in all "regular" boot ups, but not in * rescue.target or even emergency.target. */ const char *p = strjoina(dest_early, "/" SPECIAL_BASIC_TARGET ".wants/systemd-bless-boot.service"); (void) mkdir_parents(p, 0755); if (symlink(SYSTEM_DATA_UNIT_DIR "/systemd-bless-boot.service", p) < 0) return log_error_errno(errno, "Failed to create symlink '%s': %m", p); return 0; } DEFINE_MAIN_GENERATOR_FUNCTION(run);
1,999
34.087719
112
c
null
systemd-main/src/boot/boot-check-no-failures.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include "sd-bus.h" #include "alloc-util.h" #include "build.h" #include "bus-error.h" #include "log.h" #include "main-func.h" #include "pretty-print.h" #include "terminal-util.h" static int help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("systemd-boot-check-no-failures.service", "8", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...]\n" "\n%sVerify system operational state.%s\n\n" " -h --help Show this help\n" " --version Print version\n" "\nSee the %s for details.\n", program_invocation_short_name, ansi_highlight(), ansi_normal(), link); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_PATH = 0x100, ARG_VERSION, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, {} }; int c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': help(); return 0; case ARG_VERSION: return version(); case '?': return -EINVAL; default: assert_not_reached(); } return 1; } static int run(int argc, char *argv[]) { _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; uint32_t n; int r; log_parse_environment(); log_open(); r = parse_argv(argc, argv); if (r <= 0) return r; r = sd_bus_open_system(&bus); if (r < 0) return log_error_errno(r, "Failed to connect to system bus: %m"); r = sd_bus_get_property_trivial( bus, "org.freedesktop.systemd1", "/org/freedesktop/systemd1", "org.freedesktop.systemd1.Manager", "NFailedUnits", &error, 'u', &n); if (r < 0) return log_error_errno(r, "Failed to get failed units counter: %s", bus_error_message(&error, r)); if (n > 0) log_notice("Health check: %" PRIu32 " units have failed.", n); else log_info("Health check: no failed units."); return n > 0; } DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
3,069
25.929825
114
c
null
systemd-main/src/boot/bootctl-reboot-to-firmware.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bootctl-reboot-to-firmware.h" #include "efi-api.h" #include "parse-util.h" int verb_reboot_to_firmware(int argc, char *argv[], void *userdata) { int r; if (argc < 2) { r = efi_get_reboot_to_firmware(); if (r > 0) { puts("active"); return 0; /* success */ } if (r == 0) { puts("supported"); return 1; /* recognizable error #1 */ } if (r == -EOPNOTSUPP) { puts("not supported"); return 2; /* recognizable error #2 */ } log_error_errno(r, "Failed to query reboot-to-firmware state: %m"); return 3; /* other kind of error */ } else { r = parse_boolean(argv[1]); if (r < 0) return log_error_errno(r, "Failed to parse argument: %s", argv[1]); r = efi_set_reboot_to_firmware(r); if (r < 0) return log_error_errno(r, "Failed to set reboot-to-firmware option: %m"); return 0; } }
1,284
31.948718
97
c
null
systemd-main/src/boot/bootctl-set-efivar.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <uchar.h> #include <unistd.h> #include "bootctl.h" #include "bootctl-set-efivar.h" #include "efivars.h" #include "stdio-util.h" #include "utf8.h" #include "virt.h" static int parse_timeout(const char *arg1, char16_t **ret_timeout, size_t *ret_timeout_size) { char utf8[DECIMAL_STR_MAX(usec_t)]; char16_t *encoded; usec_t timeout; int r; assert(arg1); assert(ret_timeout); assert(ret_timeout_size); if (streq(arg1, "menu-force")) timeout = USEC_INFINITY; else if (streq(arg1, "menu-hidden")) timeout = 0; else { r = parse_time(arg1, &timeout, USEC_PER_SEC); if (r < 0) return log_error_errno(r, "Failed to parse timeout '%s': %m", arg1); if (timeout != USEC_INFINITY && timeout > UINT32_MAX * USEC_PER_SEC) log_warning("Timeout is too long and will be treated as 'menu-force' instead."); } xsprintf(utf8, USEC_FMT, MIN(timeout / USEC_PER_SEC, UINT32_MAX)); encoded = utf8_to_utf16(utf8, strlen(utf8)); if (!encoded) return log_oom(); *ret_timeout = encoded; *ret_timeout_size = char16_strlen(encoded) * 2 + 2; return 0; } static int parse_loader_entry_target_arg(const char *arg1, char16_t **ret_target, size_t *ret_target_size) { char16_t *encoded = NULL; int r; assert(arg1); assert(ret_target); assert(ret_target_size); if (streq(arg1, "@current")) { r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntrySelected), NULL, (void *) ret_target, ret_target_size); if (r < 0) return log_error_errno(r, "Failed to get EFI variable 'LoaderEntrySelected': %m"); } else if (streq(arg1, "@oneshot")) { r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryOneShot), NULL, (void *) ret_target, ret_target_size); if (r < 0) return log_error_errno(r, "Failed to get EFI variable 'LoaderEntryOneShot': %m"); } else if (streq(arg1, "@default")) { r = efi_get_variable(EFI_LOADER_VARIABLE(LoaderEntryDefault), NULL, (void *) ret_target, ret_target_size); if (r < 0) return log_error_errno(r, "Failed to get EFI variable 'LoaderEntryDefault': %m"); } else if (arg1[0] == '@' && !streq(arg1, "@saved")) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unsupported special entry identifier: %s", arg1); else { encoded = utf8_to_utf16(arg1, strlen(arg1)); if (!encoded) return log_oom(); *ret_target = encoded; *ret_target_size = char16_strlen(encoded) * 2 + 2; } return 0; } int verb_set_efivar(int argc, char *argv[], void *userdata) { int r; if (arg_root) return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Acting on %s, skipping EFI variable setup.", arg_image ? "image" : "root directory"); if (!is_efi_boot()) return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "Not booted with UEFI."); if (access(EFIVAR_PATH(EFI_LOADER_VARIABLE(LoaderInfo)), F_OK) < 0) { if (errno == ENOENT) { log_error_errno(errno, "Not booted with a supported boot loader."); return -EOPNOTSUPP; } return log_error_errno(errno, "Failed to detect whether boot loader supports '%s' operation: %m", argv[0]); } if (detect_container() > 0) return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "'%s' operation not supported in a container.", argv[0]); if (!arg_touch_variables) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "'%s' operation cannot be combined with --no-variables.", argv[0]); const char *variable; int (* arg_parser)(const char *, char16_t **, size_t *); if (streq(argv[0], "set-default")) { variable = EFI_LOADER_VARIABLE(LoaderEntryDefault); arg_parser = parse_loader_entry_target_arg; } else if (streq(argv[0], "set-oneshot")) { variable = EFI_LOADER_VARIABLE(LoaderEntryOneShot); arg_parser = parse_loader_entry_target_arg; } else if (streq(argv[0], "set-timeout")) { variable = EFI_LOADER_VARIABLE(LoaderConfigTimeout); arg_parser = parse_timeout; } else if (streq(argv[0], "set-timeout-oneshot")) { variable = EFI_LOADER_VARIABLE(LoaderConfigTimeoutOneShot); arg_parser = parse_timeout; } else assert_not_reached(); if (isempty(argv[1])) { r = efi_set_variable(variable, NULL, 0); if (r < 0 && r != -ENOENT) return log_error_errno(r, "Failed to remove EFI variable '%s': %m", variable); } else { _cleanup_free_ char16_t *value = NULL; size_t value_size = 0; r = arg_parser(argv[1], &value, &value_size); if (r < 0) return r; r = efi_set_variable(variable, value, value_size); if (r < 0) return log_error_errno(r, "Failed to update EFI variable '%s': %m", variable); } return 0; }
5,913
38.426667
123
c
null
systemd-main/src/boot/bootctl-systemd-efi-options.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "bootctl-systemd-efi-options.h" #include "efi-loader.h" int verb_systemd_efi_options(int argc, char *argv[], void *userdata) { int r; if (argc == 1) { _cleanup_free_ char *line = NULL, *new = NULL; r = systemd_efi_options_variable(&line); if (r == -ENODATA) log_debug("No SystemdOptions EFI variable present in cache."); else if (r < 0) return log_error_errno(r, "Failed to read SystemdOptions EFI variable from cache: %m"); else puts(line); r = systemd_efi_options_efivarfs_if_newer(&new); if (r == -ENODATA) { if (line) log_notice("Note: SystemdOptions EFI variable has been removed since boot."); } else if (r < 0) log_warning_errno(r, "Failed to check SystemdOptions EFI variable in efivarfs, ignoring: %m"); else if (new && !streq_ptr(line, new)) log_notice("Note: SystemdOptions EFI variable has been modified since boot. New value: %s", new); } else { r = efi_set_variable_string(EFI_SYSTEMD_VARIABLE(SystemdOptions), argv[1]); if (r < 0) return log_error_errno(r, "Failed to set SystemdOptions EFI variable: %m"); } return 0; }
1,575
40.473684
118
c
null
systemd-main/src/boot/bootctl-uki.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include "alloc-util.h" #include "bootctl-uki.h" #include "kernel-image.h" int verb_kernel_identify(int argc, char *argv[], void *userdata) { KernelImageType t; int r; r = inspect_kernel(AT_FDCWD, argv[1], &t, NULL, NULL, NULL); if (r < 0) return r; puts(kernel_image_type_to_string(t)); return 0; } int verb_kernel_inspect(int argc, char *argv[], void *userdata) { _cleanup_free_ char *cmdline = NULL, *uname = NULL, *pname = NULL; KernelImageType t; int r; r = inspect_kernel(AT_FDCWD, argv[1], &t, &cmdline, &uname, &pname); if (r < 0) return r; printf("Kernel Type: %s\n", kernel_image_type_to_string(t)); if (cmdline) printf(" Cmdline: %s\n", cmdline); if (uname) printf(" Version: %s\n", uname); if (pname) printf(" OS: %s\n", pname); return 0; }
1,052
25.325
76
c
null
systemd-main/src/boot/bootctl-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/mman.h> #include "bootctl.h" #include "bootctl-util.h" #include "fileio.h" #include "stat-util.h" #include "sync-util.h" int sync_everything(void) { int ret = 0, k; if (arg_esp_path) { k = syncfs_path(AT_FDCWD, arg_esp_path); if (k < 0) ret = log_error_errno(k, "Failed to synchronize the ESP '%s': %m", arg_esp_path); } if (arg_xbootldr_path) { k = syncfs_path(AT_FDCWD, arg_xbootldr_path); if (k < 0) ret = log_error_errno(k, "Failed to synchronize $BOOT '%s': %m", arg_xbootldr_path); } return ret; } const char *get_efi_arch(void) { /* Detect EFI firmware architecture of the running system. On mixed mode systems, it could be 32-bit * while the kernel is running in 64-bit. */ #ifdef __x86_64__ _cleanup_free_ char *platform_size = NULL; int r; r = read_one_line_file("/sys/firmware/efi/fw_platform_size", &platform_size); if (r == -ENOENT) return EFI_MACHINE_TYPE_NAME; if (r < 0) { log_warning_errno(r, "Error reading EFI firmware word size, assuming machine type '%s': %m", EFI_MACHINE_TYPE_NAME); return EFI_MACHINE_TYPE_NAME; } if (streq(platform_size, "64")) return EFI_MACHINE_TYPE_NAME; if (streq(platform_size, "32")) return "ia32"; log_warning( "Unknown EFI firmware word size '%s', using machine type '%s'.", platform_size, EFI_MACHINE_TYPE_NAME); #endif return EFI_MACHINE_TYPE_NAME; } /* search for "#### LoaderInfo: systemd-boot 218 ####" string inside the binary */ int get_file_version(int fd, char **ret) { struct stat st; char *buf; const char *s, *e; char *marker = NULL; int r; assert(fd >= 0); assert(ret); if (fstat(fd, &st) < 0) return log_error_errno(errno, "Failed to stat EFI binary: %m"); r = stat_verify_regular(&st); if (r < 0) { log_debug_errno(r, "EFI binary is not a regular file, assuming no version information: %m"); return -ESRCH; } if (st.st_size < 27 || file_offset_beyond_memory_size(st.st_size)) return log_debug_errno(SYNTHETIC_ERRNO(ESRCH), "EFI binary size too %s: %"PRIi64, st.st_size < 27 ? "small" : "large", st.st_size); buf = mmap(NULL, st.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if (buf == MAP_FAILED) return log_error_errno(errno, "Failed to mmap EFI binary: %m"); s = mempmem_safe(buf, st.st_size - 8, "#### LoaderInfo: ", 17); if (!s) { r = log_debug_errno(SYNTHETIC_ERRNO(ESRCH), "EFI binary has no LoaderInfo marker."); goto finish; } e = memmem_safe(s, st.st_size - (s - buf), " ####", 5); if (!e || e - s < 3) { r = log_error_errno(SYNTHETIC_ERRNO(EINVAL), "EFI binary has malformed LoaderInfo marker."); goto finish; } marker = strndup(s, e - s); if (!marker) { r = log_oom(); goto finish; } log_debug("EFI binary LoaderInfo marker: \"%s\"", marker); r = 0; *ret = marker; finish: (void) munmap(buf, st.st_size); return r; } int settle_entry_token(void) { int r; r = boot_entry_token_ensure( arg_root, etc_kernel(), arg_machine_id, /* machine_id_is_random = */ false, &arg_entry_token_type, &arg_entry_token); if (r < 0) return r; log_debug("Using entry token: %s", arg_entry_token); return 0; }
4,158
30.507576
108
c
null
systemd-main/src/boot/efi/addon.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "efi.h" #include "version.h" /* Magic string for recognizing our own binaries */ _used_ _section_(".sdmagic") static const char magic[] = "#### LoaderInfo: systemd-addon " GIT_VERSION " ####"; /* This is intended to carry data, not to be executed */ EFIAPI EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *system_table); EFIAPI EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *system_table) { return EFI_UNSUPPORTED; }
507
30.75
78
c
null
systemd-main/src/boot/efi/bcd.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdalign.h> #include "bcd.h" #include "efi-string.h" enum { SIG_BASE_BLOCK = 1718052210, /* regf */ SIG_KEY = 27502, /* nk */ SIG_SUBKEY_FAST = 26220, /* lf */ SIG_KEY_VALUE = 27510, /* vk */ }; enum { REG_SZ = 1, REG_MULTI_SZ = 7, }; /* These structs contain a lot more members than we care for. They have all * been squashed into _padN for our convenience. */ typedef struct { uint32_t sig; uint32_t primary_seqnum; uint32_t secondary_seqnum; uint64_t _pad1; uint32_t version_major; uint32_t version_minor; uint32_t type; uint32_t _pad2; uint32_t root_cell_offset; uint64_t _pad3[507]; } _packed_ BaseBlock; assert_cc(sizeof(BaseBlock) == 4096); assert_cc(offsetof(BaseBlock, sig) == 0); assert_cc(offsetof(BaseBlock, primary_seqnum) == 4); assert_cc(offsetof(BaseBlock, secondary_seqnum) == 8); assert_cc(offsetof(BaseBlock, version_major) == 20); assert_cc(offsetof(BaseBlock, version_minor) == 24); assert_cc(offsetof(BaseBlock, type) == 28); assert_cc(offsetof(BaseBlock, root_cell_offset) == 36); /* All offsets are relative to the base block and technically point to a hive * cell struct. But for our usecase we don't need to bother about that one, * so skip over the cell_size uint32_t. */ #define HIVE_CELL_OFFSET (sizeof(BaseBlock) + 4) typedef struct { uint16_t sig; uint16_t _pad1[13]; uint32_t subkeys_offset; uint32_t _pad2; uint32_t n_key_values; uint32_t key_values_offset; uint32_t _pad3[7]; uint16_t key_name_len; uint16_t _pad4; char key_name[]; } _packed_ Key; assert_cc(offsetof(Key, sig) == 0); assert_cc(offsetof(Key, subkeys_offset) == 28); assert_cc(offsetof(Key, n_key_values) == 36); assert_cc(offsetof(Key, key_values_offset) == 40); assert_cc(offsetof(Key, key_name_len) == 72); assert_cc(offsetof(Key, key_name) == 76); typedef struct { uint16_t sig; uint16_t n_entries; struct SubkeyFastEntry { uint32_t key_offset; char name_hint[4]; } _packed_ entries[]; } _packed_ SubkeyFast; assert_cc(offsetof(SubkeyFast, sig) == 0); assert_cc(offsetof(SubkeyFast, n_entries) == 2); assert_cc(offsetof(SubkeyFast, entries) == 4); typedef struct { uint16_t sig; uint16_t name_len; uint32_t data_size; uint32_t data_offset; uint32_t data_type; uint32_t _pad; char name[]; } _packed_ KeyValue; assert_cc(offsetof(KeyValue, sig) == 0); assert_cc(offsetof(KeyValue, name_len) == 2); assert_cc(offsetof(KeyValue, data_size) == 4); assert_cc(offsetof(KeyValue, data_offset) == 8); assert_cc(offsetof(KeyValue, data_type) == 12); assert_cc(offsetof(KeyValue, name) == 20); #define BAD_OFFSET(offset, len, max) \ ((uint64_t) (offset) + (len) >= (max)) #define BAD_STRUCT(type, offset, max) \ ((uint64_t) (offset) + sizeof(type) >= (max)) #define BAD_ARRAY(type, array, offset, array_len, max) \ ((uint64_t) (offset) + offsetof(type, array) + \ sizeof((type){}.array[0]) * (uint64_t) (array_len) >= (max)) static const Key *get_key(const uint8_t *bcd, uint32_t bcd_len, uint32_t offset, const char *name); static const Key *get_subkey(const uint8_t *bcd, uint32_t bcd_len, uint32_t offset, const char *name) { assert(bcd); assert(name); if (BAD_STRUCT(SubkeyFast, offset, bcd_len)) return NULL; const SubkeyFast *subkey = (const SubkeyFast *) (bcd + offset); if (subkey->sig != SIG_SUBKEY_FAST) return NULL; if (BAD_ARRAY(SubkeyFast, entries, offset, subkey->n_entries, bcd_len)) return NULL; for (uint16_t i = 0; i < subkey->n_entries; i++) { if (!strncaseeq8(name, subkey->entries[i].name_hint, sizeof(subkey->entries[i].name_hint))) continue; const Key *key = get_key(bcd, bcd_len, subkey->entries[i].key_offset, name); if (key) return key; } return NULL; } /* We use NUL as registry path separators for convenience. To start from the root, begin * name with a NUL. Name must end with two NUL. The lookup depth is not restricted, so * name must be properly validated before calling get_key(). */ static const Key *get_key(const uint8_t *bcd, uint32_t bcd_len, uint32_t offset, const char *name) { assert(bcd); assert(name); if (BAD_STRUCT(Key, offset, bcd_len)) return NULL; const Key *key = (const Key *) (bcd + offset); if (key->sig != SIG_KEY) return NULL; if (BAD_ARRAY(Key, key_name, offset, key->key_name_len, bcd_len)) return NULL; if (*name) { if (strncaseeq8(name, key->key_name, key->key_name_len) && strlen8(name) == key->key_name_len) name += key->key_name_len; else return NULL; } name++; return *name ? get_subkey(bcd, bcd_len, key->subkeys_offset, name) : key; } static const KeyValue *get_key_value(const uint8_t *bcd, uint32_t bcd_len, const Key *key, const char *name) { assert(bcd); assert(key); assert(name); if (key->n_key_values == 0) return NULL; if (BAD_OFFSET(key->key_values_offset, sizeof(uint32_t) * (uint64_t) key->n_key_values, bcd_len) || (uintptr_t) (bcd + key->key_values_offset) % alignof(uint32_t) != 0) return NULL; const uint32_t *key_value_list = (const uint32_t *) (bcd + key->key_values_offset); for (uint32_t i = 0; i < key->n_key_values; i++) { uint32_t offset = *(key_value_list + i); if (BAD_STRUCT(KeyValue, offset, bcd_len)) continue; const KeyValue *kv = (const KeyValue *) (bcd + offset); if (kv->sig != SIG_KEY_VALUE) continue; if (BAD_ARRAY(KeyValue, name, offset, kv->name_len, bcd_len)) continue; /* If most significant bit is set, data is stored in data_offset itself, but * we are only interested in UTF16 strings. The only strings that could fit * would have just one char in it, so let's not bother with this. */ if (FLAGS_SET(kv->data_size, UINT32_C(1) << 31)) continue; if (BAD_OFFSET(kv->data_offset, kv->data_size, bcd_len)) continue; if (strncaseeq8(name, kv->name, kv->name_len) && strlen8(name) == kv->name_len) return kv; } return NULL; } /* The BCD store is really just a regular windows registry hive with a rather cryptic internal * key structure. On a running system it gets mounted to HKEY_LOCAL_MACHINE\BCD00000000. * * Of interest to us are these two keys: * - \Objects\{bootmgr}\Elements\24000001 * This key is the "displayorder" property and contains a value of type REG_MULTI_SZ * with the name "Element" that holds a {GUID} list (UTF16, NUL-separated). * - \Objects\{GUID}\Elements\12000004 * This key is the "description" property and contains a value of type REG_SZ with the * name "Element" that holds a NUL-terminated UTF16 string. * * The GUIDs and properties are as reported by "bcdedit.exe /v". * * To get a title for the BCD store we first look at the displayorder property of {bootmgr} * (it always has the GUID 9dea862c-5cdd-4e70-acc1-f32b344d4795). If it contains more than * one GUID, the BCD is multi-boot and we stop looking. Otherwise we take that GUID, look it * up, and return its description property. */ char16_t *get_bcd_title(uint8_t *bcd, size_t bcd_len) { assert(bcd); if (HIVE_CELL_OFFSET >= bcd_len) return NULL; BaseBlock *base_block = (BaseBlock *) bcd; if (base_block->sig != SIG_BASE_BLOCK || base_block->version_major != 1 || base_block->version_minor != 3 || base_block->type != 0 || base_block->primary_seqnum != base_block->secondary_seqnum) return NULL; bcd += HIVE_CELL_OFFSET; bcd_len -= HIVE_CELL_OFFSET; const Key *objects_key = get_key(bcd, bcd_len, base_block->root_cell_offset, "\0Objects\0"); if (!objects_key) return NULL; const Key *displayorder_key = get_subkey( bcd, bcd_len, objects_key->subkeys_offset, "{9dea862c-5cdd-4e70-acc1-f32b344d4795}\0Elements\00024000001\0"); if (!displayorder_key) return NULL; const KeyValue *displayorder_value = get_key_value(bcd, bcd_len, displayorder_key, "Element"); if (!displayorder_value) return NULL; char order_guid[sizeof("{00000000-0000-0000-0000-000000000000}\0")]; if (displayorder_value->data_type != REG_MULTI_SZ || displayorder_value->data_size != sizeof(char16_t[sizeof(order_guid)]) || (uintptr_t) (bcd + displayorder_value->data_offset) % alignof(char16_t) != 0) /* BCD is multi-boot. */ return NULL; /* Keys are stored as ASCII in registry hives if the data fits (and GUIDS always should). */ char16_t *order_guid_utf16 = (char16_t *) (bcd + displayorder_value->data_offset); for (size_t i = 0; i < sizeof(order_guid) - 2; i++) { char16_t c = order_guid_utf16[i]; switch (c) { case '-': case '{': case '}': case '0' ... '9': case 'a' ... 'f': case 'A' ... 'F': order_guid[i] = c; break; default: /* Not a valid GUID. */ return NULL; } } /* Our functions expect the lookup key to be double-derminated. */ order_guid[sizeof(order_guid) - 2] = '\0'; order_guid[sizeof(order_guid) - 1] = '\0'; const Key *default_key = get_subkey(bcd, bcd_len, objects_key->subkeys_offset, order_guid); if (!default_key) return NULL; const Key *description_key = get_subkey( bcd, bcd_len, default_key->subkeys_offset, "Elements\00012000004\0"); if (!description_key) return NULL; const KeyValue *description_value = get_key_value(bcd, bcd_len, description_key, "Element"); if (!description_value) return NULL; if (description_value->data_type != REG_SZ || description_value->data_size < sizeof(char16_t) || description_value->data_size % sizeof(char16_t) != 0 || (uintptr_t) (bcd + description_value->data_offset) % alignof(char16_t)) return NULL; /* The data should already be NUL-terminated. */ char16_t *title = (char16_t *) (bcd + description_value->data_offset); title[description_value->data_size / sizeof(char16_t) - 1] = '\0'; return title; }
11,528
36.553746
110
c
null
systemd-main/src/boot/efi/console.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "console.h" #include "proto/graphics-output.h" #include "util.h" #define SYSTEM_FONT_WIDTH 8 #define SYSTEM_FONT_HEIGHT 19 #define HORIZONTAL_MAX_OK 1920 #define VERTICAL_MAX_OK 1080 #define VIEWPORT_RATIO 10 static inline void event_closep(EFI_EVENT *event) { if (!*event) return; BS->CloseEvent(*event); } /* * Reading input from the console sounds like an easy task to do, but thanks to broken * firmware it is actually a nightmare. * * There is a SimpleTextInput and SimpleTextInputEx API for this. Ideally we want to use * TextInputEx, because that gives us Ctrl/Alt/Shift key state information. Unfortunately, * it is not always available and sometimes just non-functional. * * On some firmware, calling ReadKeyStroke or ReadKeyStrokeEx on the default console input * device will just freeze no matter what (even though it *reported* being ready). * Also, multiple input protocols can be backed by the same device, but they can be out of * sync. Falling back on a different protocol can end up with double input. * * Therefore, we will preferably use TextInputEx for ConIn if that is available. Additionally, * we look for the first TextInputEx device the firmware gives us as a fallback option. It * will replace ConInEx permanently if it ever reports a key press. * Lastly, a timer event allows us to provide a input timeout without having to call into * any input functions that can freeze on us or using a busy/stall loop. */ EFI_STATUS console_key_read(uint64_t *key, uint64_t timeout_usec) { static EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL *conInEx = NULL, *extraInEx = NULL; static bool checked = false; size_t index; EFI_STATUS err; _cleanup_(event_closep) EFI_EVENT timer = NULL; assert(key); if (!checked) { /* Get the *first* TextInputEx device. */ err = BS->LocateProtocol( MAKE_GUID_PTR(EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL), NULL, (void **) &extraInEx); if (err != EFI_SUCCESS || BS->CheckEvent(extraInEx->WaitForKeyEx) == EFI_INVALID_PARAMETER) /* If WaitForKeyEx fails here, the firmware pretends it talks this * protocol, but it really doesn't. */ extraInEx = NULL; /* Get the TextInputEx version of ST->ConIn. */ err = BS->HandleProtocol( ST->ConsoleInHandle, MAKE_GUID_PTR(EFI_SIMPLE_TEXT_INPUT_EX_PROTOCOL), (void **) &conInEx); if (err != EFI_SUCCESS || BS->CheckEvent(conInEx->WaitForKeyEx) == EFI_INVALID_PARAMETER) conInEx = NULL; if (conInEx == extraInEx) extraInEx = NULL; checked = true; } err = BS->CreateEvent(EVT_TIMER, 0, NULL, NULL, &timer); if (err != EFI_SUCCESS) return log_error_status(err, "Error creating timer event: %m"); EFI_EVENT events[] = { timer, conInEx ? conInEx->WaitForKeyEx : ST->ConIn->WaitForKey, extraInEx ? extraInEx->WaitForKeyEx : NULL, }; size_t n_events = extraInEx ? 3 : 2; /* Watchdog rearming loop in case the user never provides us with input or some * broken firmware never returns from WaitForEvent. */ for (;;) { uint64_t watchdog_timeout_sec = 5 * 60, watchdog_ping_usec = watchdog_timeout_sec / 2 * 1000 * 1000; /* SetTimer expects 100ns units for some reason. */ err = BS->SetTimer( timer, TimerRelative, MIN(timeout_usec, watchdog_ping_usec) * 10); if (err != EFI_SUCCESS) return log_error_status(err, "Error arming timer event: %m"); (void) BS->SetWatchdogTimer(watchdog_timeout_sec, 0x10000, 0, NULL); err = BS->WaitForEvent(n_events, events, &index); (void) BS->SetWatchdogTimer(watchdog_timeout_sec, 0x10000, 0, NULL); if (err != EFI_SUCCESS) return log_error_status(err, "Error waiting for events: %m"); /* We have keyboard input, process it after this loop. */ if (timer != events[index]) break; /* The EFI timer fired instead. If this was a watchdog timeout, loop again. */ if (timeout_usec == UINT64_MAX) continue; else if (timeout_usec > watchdog_ping_usec) { timeout_usec -= watchdog_ping_usec; continue; } /* The caller requested a timeout? They shall have one! */ return EFI_TIMEOUT; } /* If the extra input device we found returns something, always use that instead * to work around broken firmware freezing on ConIn/ConInEx. */ if (extraInEx && BS->CheckEvent(extraInEx->WaitForKeyEx) == EFI_SUCCESS) { conInEx = extraInEx; extraInEx = NULL; } /* Do not fall back to ConIn if we have a ConIn that supports TextInputEx. * The two may be out of sync on some firmware, giving us double input. */ if (conInEx) { EFI_KEY_DATA keydata; uint32_t shift = 0; err = conInEx->ReadKeyStrokeEx(conInEx, &keydata); if (err != EFI_SUCCESS) return err; if (FLAGS_SET(keydata.KeyState.KeyShiftState, EFI_SHIFT_STATE_VALID)) { /* Do not distinguish between left and right keys (set both flags). */ if (keydata.KeyState.KeyShiftState & EFI_CONTROL_PRESSED) shift |= EFI_CONTROL_PRESSED; if (keydata.KeyState.KeyShiftState & EFI_ALT_PRESSED) shift |= EFI_ALT_PRESSED; if (keydata.KeyState.KeyShiftState & EFI_LOGO_PRESSED) shift |= EFI_LOGO_PRESSED; /* Shift is not supposed to be reported for keys that can be represented as uppercase * unicode chars (Shift+f is reported as F instead). Some firmware does it anyway, so * filter those out. */ if ((keydata.KeyState.KeyShiftState & EFI_SHIFT_PRESSED) && keydata.Key.UnicodeChar == 0) shift |= EFI_SHIFT_PRESSED; } /* 32 bit modifier keys + 16 bit scan code + 16 bit unicode */ *key = KEYPRESS(shift, keydata.Key.ScanCode, keydata.Key.UnicodeChar); return EFI_SUCCESS; } else if (BS->CheckEvent(ST->ConIn->WaitForKey) == EFI_SUCCESS) { EFI_INPUT_KEY k; err = ST->ConIn->ReadKeyStroke(ST->ConIn, &k); if (err != EFI_SUCCESS) return err; *key = KEYPRESS(0, k.ScanCode, k.UnicodeChar); return EFI_SUCCESS; } return EFI_NOT_READY; } static EFI_STATUS change_mode(int64_t mode) { EFI_STATUS err; int32_t old_mode; /* SetMode expects a size_t, so make sure these values are sane. */ mode = CLAMP(mode, CONSOLE_MODE_RANGE_MIN, CONSOLE_MODE_RANGE_MAX); old_mode = MAX(CONSOLE_MODE_RANGE_MIN, ST->ConOut->Mode->Mode); log_wait(); err = ST->ConOut->SetMode(ST->ConOut, mode); if (err == EFI_SUCCESS) return EFI_SUCCESS; /* Something went wrong. Output is probably borked, so try to revert to previous mode. */ if (ST->ConOut->SetMode(ST->ConOut, old_mode) == EFI_SUCCESS) return err; /* Maybe the device is on fire? */ ST->ConOut->Reset(ST->ConOut, true); ST->ConOut->SetMode(ST->ConOut, CONSOLE_MODE_RANGE_MIN); return err; } EFI_STATUS query_screen_resolution(uint32_t *ret_w, uint32_t *ret_h) { EFI_STATUS err; EFI_GRAPHICS_OUTPUT_PROTOCOL *go; err = BS->LocateProtocol(MAKE_GUID_PTR(EFI_GRAPHICS_OUTPUT_PROTOCOL), NULL, (void **) &go); if (err != EFI_SUCCESS) return err; if (!go->Mode || !go->Mode->Info) return EFI_DEVICE_ERROR; *ret_w = go->Mode->Info->HorizontalResolution; *ret_h = go->Mode->Info->VerticalResolution; return EFI_SUCCESS; } static int64_t get_auto_mode(void) { uint32_t screen_width, screen_height; if (query_screen_resolution(&screen_width, &screen_height) == EFI_SUCCESS) { bool keep = false; /* Start verifying if we are in a resolution larger than Full HD * (1920x1080). If we're not, assume we're in a good mode and do not * try to change it. */ if (screen_width <= HORIZONTAL_MAX_OK && screen_height <= VERTICAL_MAX_OK) keep = true; /* For larger resolutions, calculate the ratio of the total screen * area to the text viewport area. If it's less than 10 times bigger, * then assume the text is readable and keep the text mode. */ else { uint64_t text_area; size_t x_max, y_max; uint64_t screen_area = (uint64_t)screen_width * (uint64_t)screen_height; console_query_mode(&x_max, &y_max); text_area = SYSTEM_FONT_WIDTH * SYSTEM_FONT_HEIGHT * (uint64_t)x_max * (uint64_t)y_max; if (text_area != 0 && screen_area/text_area < VIEWPORT_RATIO) keep = true; } if (keep) return ST->ConOut->Mode->Mode; } /* If we reached here, then we have a high resolution screen and the text * viewport is less than 10% the screen area, so the firmware developer * screwed up. Try to switch to a better mode. Mode number 2 is first non * standard mode, which is provided by the device manufacturer, so it should * be a good mode. * Note: MaxMode is the number of modes, not the last mode. */ if (ST->ConOut->Mode->MaxMode > CONSOLE_MODE_FIRMWARE_FIRST) return CONSOLE_MODE_FIRMWARE_FIRST; /* Try again with mode different than zero (assume user requests * auto mode due to some problem with mode zero). */ if (ST->ConOut->Mode->MaxMode > CONSOLE_MODE_80_50) return CONSOLE_MODE_80_50; return CONSOLE_MODE_80_25; } EFI_STATUS console_set_mode(int64_t mode) { switch (mode) { case CONSOLE_MODE_KEEP: /* If the firmware indicates the current mode is invalid, change it anyway. */ if (ST->ConOut->Mode->Mode < CONSOLE_MODE_RANGE_MIN) return change_mode(CONSOLE_MODE_RANGE_MIN); return EFI_SUCCESS; case CONSOLE_MODE_NEXT: if (ST->ConOut->Mode->MaxMode <= CONSOLE_MODE_RANGE_MIN) return EFI_UNSUPPORTED; mode = MAX(CONSOLE_MODE_RANGE_MIN, ST->ConOut->Mode->Mode); do { mode = (mode + 1) % ST->ConOut->Mode->MaxMode; if (change_mode(mode) == EFI_SUCCESS) break; /* If this mode is broken/unsupported, try the next. * If mode is 0, we wrapped around and should stop. */ } while (mode > CONSOLE_MODE_RANGE_MIN); return EFI_SUCCESS; case CONSOLE_MODE_AUTO: return change_mode(get_auto_mode()); case CONSOLE_MODE_FIRMWARE_MAX: /* Note: MaxMode is the number of modes, not the last mode. */ return change_mode(ST->ConOut->Mode->MaxMode - 1LL); default: return change_mode(mode); } } EFI_STATUS console_query_mode(size_t *x_max, size_t *y_max) { EFI_STATUS err; assert(x_max); assert(y_max); err = ST->ConOut->QueryMode(ST->ConOut, ST->ConOut->Mode->Mode, x_max, y_max); if (err != EFI_SUCCESS) { /* Fallback values mandated by UEFI spec. */ switch (ST->ConOut->Mode->Mode) { case CONSOLE_MODE_80_50: *x_max = 80; *y_max = 50; break; case CONSOLE_MODE_80_25: default: *x_max = 80; *y_max = 25; } } return err; }
13,195
41.159744
111
c
null
systemd-main/src/boot/efi/console.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "efi.h" #include "proto/simple-text-io.h" enum { EFI_SHIFT_PRESSED = EFI_RIGHT_SHIFT_PRESSED|EFI_LEFT_SHIFT_PRESSED, EFI_CONTROL_PRESSED = EFI_RIGHT_CONTROL_PRESSED|EFI_LEFT_CONTROL_PRESSED, EFI_ALT_PRESSED = EFI_RIGHT_ALT_PRESSED|EFI_LEFT_ALT_PRESSED, EFI_LOGO_PRESSED = EFI_RIGHT_LOGO_PRESSED|EFI_LEFT_LOGO_PRESSED, }; #define KEYPRESS(keys, scan, uni) ((((uint64_t)keys) << 32) | (((uint64_t)scan) << 16) | (uni)) #define KEYCHAR(k) ((char16_t)(k)) #define CHAR_CTRL(c) ((c) - 'a' + 1) enum { /* Console mode is a int32_t in EFI. We use int64_t to make room for our special values. */ CONSOLE_MODE_RANGE_MIN = 0, CONSOLE_MODE_RANGE_MAX = INT32_MAX, /* This is just the theoretical limit. */ CONSOLE_MODE_INVALID = -1, /* UEFI uses -1 if the device is not in a valid text mode. */ CONSOLE_MODE_80_25 = 0, /* 80x25 is required by UEFI spec. */ CONSOLE_MODE_80_50 = 1, /* 80x50 may be supported. */ CONSOLE_MODE_FIRMWARE_FIRST = 2, /* First custom mode, if supported. */ /* These are our own mode values that map to concrete values at runtime. */ CONSOLE_MODE_KEEP = CONSOLE_MODE_RANGE_MAX + 1LL, CONSOLE_MODE_NEXT, CONSOLE_MODE_AUTO, CONSOLE_MODE_FIRMWARE_MAX, /* 'max' in config. */ }; EFI_STATUS console_key_read(uint64_t *key, uint64_t timeout_usec); EFI_STATUS console_set_mode(int64_t mode); EFI_STATUS console_query_mode(size_t *x_max, size_t *y_max); EFI_STATUS query_screen_resolution(uint32_t *ret_width, uint32_t *ret_height);
1,689
42.333333
105
h
null
systemd-main/src/boot/efi/cpio.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "cpio.h" #include "device-path-util.h" #include "measure.h" #include "proto/device-path.h" #include "util.h" static char *write_cpio_word(char *p, uint32_t v) { static const char hex[] = "0123456789abcdef"; assert(p); /* Writes a CPIO header 8 character hex value */ for (size_t i = 0; i < 8; i++) p[7-i] = hex[(v >> (4 * i)) & 0xF]; return p + 8; } static char *mangle_filename(char *p, const char16_t *f) { char* w; assert(p); assert(f); /* Basically converts UTF-16 to plain ASCII (note that we filtered non-ASCII filenames beforehand, so * this operation is always safe) */ for (w = p; *f != 0; f++) { assert(*f <= 0x7fu); *(w++) = *f; } *(w++) = 0; return w; } static char *pad4(char *p, const char *start) { assert(p); assert(start); assert(p >= start); /* Appends NUL bytes to 'p', until the address is divisible by 4, when taken relative to 'start' */ while ((p - start) % 4 != 0) *(p++) = 0; return p; } static EFI_STATUS pack_cpio_one( const char16_t *fname, const void *contents, size_t contents_size, const char *target_dir_prefix, uint32_t access_mode, uint32_t *inode_counter, void **cpio_buffer, size_t *cpio_buffer_size) { size_t l, target_dir_prefix_size, fname_size, q; char *a; assert(fname); assert(contents_size || contents_size == 0); assert(target_dir_prefix); assert(inode_counter); assert(cpio_buffer); assert(cpio_buffer_size); /* Serializes one file in the cpio format understood by the kernel initrd logic. * * See: https://docs.kernel.org/driver-api/early-userspace/buffer-format.html */ if (contents_size > UINT32_MAX) /* cpio cannot deal with > 32-bit file sizes */ return EFI_LOAD_ERROR; if (*inode_counter == UINT32_MAX) /* more than 2^32-1 inodes? yikes. cpio doesn't support that either */ return EFI_OUT_OF_RESOURCES; l = 6 + 13*8 + 1 + 1; /* Fixed CPIO header size, slash separator, and NUL byte after the file name */ target_dir_prefix_size = strlen8(target_dir_prefix); if (l > SIZE_MAX - target_dir_prefix_size) return EFI_OUT_OF_RESOURCES; l += target_dir_prefix_size; fname_size = strlen16(fname); if (l > SIZE_MAX - fname_size) return EFI_OUT_OF_RESOURCES; l += fname_size; /* append space for file name */ /* CPIO can't deal with fnames longer than 2^32-1 */ if (target_dir_prefix_size + fname_size >= UINT32_MAX) return EFI_OUT_OF_RESOURCES; /* Align the whole header to 4 byte size */ l = ALIGN4(l); if (l == SIZE_MAX) /* overflow check */ return EFI_OUT_OF_RESOURCES; /* Align the contents to 4 byte size */ q = ALIGN4(contents_size); if (q == SIZE_MAX) /* overflow check */ return EFI_OUT_OF_RESOURCES; if (l > SIZE_MAX - q) /* overflow check */ return EFI_OUT_OF_RESOURCES; l += q; /* Add contents to header */ if (*cpio_buffer_size > SIZE_MAX - l) /* overflow check */ return EFI_OUT_OF_RESOURCES; a = xrealloc(*cpio_buffer, *cpio_buffer_size, *cpio_buffer_size + l); *cpio_buffer = a; a = (char *) *cpio_buffer + *cpio_buffer_size; a = mempcpy(a, "070701", 6); /* magic ID */ a = write_cpio_word(a, (*inode_counter)++); /* inode */ a = write_cpio_word(a, access_mode | 0100000 /* = S_IFREG */); /* mode */ a = write_cpio_word(a, 0); /* uid */ a = write_cpio_word(a, 0); /* gid */ a = write_cpio_word(a, 1); /* nlink */ /* Note: we don't make any attempt to propagate the mtime here, for two reasons: it's a mess given * that FAT usually is assumed to operate with timezoned timestamps, while UNIX does not. More * importantly though: the modifications times would hamper our goals of providing stable * measurements for the same boots. After all we extend the initrds we generate here into TPM2 * PCRs. */ a = write_cpio_word(a, 0); /* mtime */ a = write_cpio_word(a, contents_size); /* size */ a = write_cpio_word(a, 0); /* major(dev) */ a = write_cpio_word(a, 0); /* minor(dev) */ a = write_cpio_word(a, 0); /* major(rdev) */ a = write_cpio_word(a, 0); /* minor(rdev) */ a = write_cpio_word(a, target_dir_prefix_size + fname_size + 2); /* fname size */ a = write_cpio_word(a, 0); /* "crc" */ a = mempcpy(a, target_dir_prefix, target_dir_prefix_size); *(a++) = '/'; a = mangle_filename(a, fname); /* Pad to next multiple of 4 */ a = pad4(a, *cpio_buffer); a = mempcpy(a, contents, contents_size); /* Pad to next multiple of 4 */ a = pad4(a, *cpio_buffer); assert(a == (char *) *cpio_buffer + *cpio_buffer_size + l); *cpio_buffer_size += l; return EFI_SUCCESS; } static EFI_STATUS pack_cpio_dir( const char *path, uint32_t access_mode, uint32_t *inode_counter, void **cpio_buffer, size_t *cpio_buffer_size) { size_t l, path_size; char *a; assert(path); assert(inode_counter); assert(cpio_buffer); assert(cpio_buffer_size); /* Serializes one directory inode in cpio format. Note that cpio archives must first create the dirs * they want to place files in. */ if (*inode_counter == UINT32_MAX) return EFI_OUT_OF_RESOURCES; l = 6 + 13*8 + 1; /* Fixed CPIO header size, and NUL byte after the file name */ path_size = strlen8(path); if (l > SIZE_MAX - path_size) return EFI_OUT_OF_RESOURCES; l += path_size; /* Align the whole header to 4 byte size */ l = ALIGN4(l); if (l == SIZE_MAX) /* overflow check */ return EFI_OUT_OF_RESOURCES; if (*cpio_buffer_size > SIZE_MAX - l) /* overflow check */ return EFI_OUT_OF_RESOURCES; *cpio_buffer = a = xrealloc(*cpio_buffer, *cpio_buffer_size, *cpio_buffer_size + l); a = (char *) *cpio_buffer + *cpio_buffer_size; a = mempcpy(a, "070701", 6); /* magic ID */ a = write_cpio_word(a, (*inode_counter)++); /* inode */ a = write_cpio_word(a, access_mode | 0040000 /* = S_IFDIR */); /* mode */ a = write_cpio_word(a, 0); /* uid */ a = write_cpio_word(a, 0); /* gid */ a = write_cpio_word(a, 1); /* nlink */ a = write_cpio_word(a, 0); /* mtime */ a = write_cpio_word(a, 0); /* size */ a = write_cpio_word(a, 0); /* major(dev) */ a = write_cpio_word(a, 0); /* minor(dev) */ a = write_cpio_word(a, 0); /* major(rdev) */ a = write_cpio_word(a, 0); /* minor(rdev) */ a = write_cpio_word(a, path_size + 1); /* fname size */ a = write_cpio_word(a, 0); /* "crc" */ a = mempcpy(a, path, path_size + 1); /* Pad to next multiple of 4 */ a = pad4(a, *cpio_buffer); assert(a == (char *) *cpio_buffer + *cpio_buffer_size + l); *cpio_buffer_size += l; return EFI_SUCCESS; } static EFI_STATUS pack_cpio_prefix( const char *path, uint32_t dir_mode, uint32_t *inode_counter, void **cpio_buffer, size_t *cpio_buffer_size) { EFI_STATUS err; assert(path); assert(inode_counter); assert(cpio_buffer); assert(cpio_buffer_size); /* Serializes directory inodes of all prefix paths of the specified path in cpio format. Note that * (similar to mkdir -p behaviour) all leading paths are created with 0555 access mode, only the * final dir is created with the specified directory access mode. */ for (const char *p = path;;) { const char *e; e = strchr8(p, '/'); if (!e) break; if (e > p) { _cleanup_free_ char *t = NULL; t = xstrndup8(path, e - path); if (!t) return EFI_OUT_OF_RESOURCES; err = pack_cpio_dir(t, 0555, inode_counter, cpio_buffer, cpio_buffer_size); if (err != EFI_SUCCESS) return err; } p = e + 1; } return pack_cpio_dir(path, dir_mode, inode_counter, cpio_buffer, cpio_buffer_size); } static EFI_STATUS pack_cpio_trailer( void **cpio_buffer, size_t *cpio_buffer_size) { static const char trailer[] = "070701" "00000000" "00000000" "00000000" "00000000" "00000001" "00000000" "00000000" "00000000" "00000000" "00000000" "00000000" "0000000B" "00000000" "TRAILER!!!\0\0\0"; /* There's a fourth NUL byte appended here, because this is a string */ /* Generates the cpio trailer record that indicates the end of our initrd cpio archive */ assert(cpio_buffer); assert(cpio_buffer_size); assert_cc(sizeof(trailer) % 4 == 0); *cpio_buffer = xrealloc(*cpio_buffer, *cpio_buffer_size, *cpio_buffer_size + sizeof(trailer)); memcpy((uint8_t*) *cpio_buffer + *cpio_buffer_size, trailer, sizeof(trailer)); *cpio_buffer_size += sizeof(trailer); return EFI_SUCCESS; } EFI_STATUS pack_cpio( EFI_LOADED_IMAGE_PROTOCOL *loaded_image, const char16_t *dropin_dir, const char16_t *match_suffix, const char *target_dir_prefix, uint32_t dir_mode, uint32_t access_mode, uint32_t tpm_pcr, const char16_t *tpm_description, void **ret_buffer, size_t *ret_buffer_size, bool *ret_measured) { _cleanup_(file_closep) EFI_FILE *root = NULL, *extra_dir = NULL; size_t dirent_size = 0, buffer_size = 0, n_items = 0, n_allocated = 0; _cleanup_free_ char16_t *rel_dropin_dir = NULL; _cleanup_free_ EFI_FILE_INFO *dirent = NULL; _cleanup_(strv_freep) char16_t **items = NULL; _cleanup_free_ void *buffer = NULL; uint32_t inode = 1; /* inode counter, so that each item gets a new inode */ EFI_STATUS err; assert(loaded_image); assert(target_dir_prefix); assert(ret_buffer); assert(ret_buffer_size); if (!loaded_image->DeviceHandle) goto nothing; err = open_volume(loaded_image->DeviceHandle, &root); if (err == EFI_UNSUPPORTED) /* Error will be unsupported if the bootloader doesn't implement the file system protocol on * its file handles. */ goto nothing; if (err != EFI_SUCCESS) return log_error_status(err, "Unable to open root directory: %m"); if (!dropin_dir) dropin_dir = rel_dropin_dir = get_extra_dir(loaded_image->FilePath); err = open_directory(root, dropin_dir, &extra_dir); if (err == EFI_NOT_FOUND) /* No extra subdir, that's totally OK */ goto nothing; if (err != EFI_SUCCESS) return log_error_status(err, "Failed to open extra directory of loaded image: %m"); for (;;) { _cleanup_free_ char16_t *d = NULL; err = readdir(extra_dir, &dirent, &dirent_size); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to read extra directory of loaded image: %m"); if (!dirent) /* End of directory */ break; if (dirent->FileName[0] == '.') continue; if (FLAGS_SET(dirent->Attribute, EFI_FILE_DIRECTORY)) continue; if (match_suffix && !endswith_no_case(dirent->FileName, match_suffix)) continue; if (!is_ascii(dirent->FileName)) continue; if (strlen16(dirent->FileName) > 255) /* Max filename size on Linux */ continue; d = xstrdup16(dirent->FileName); if (n_items+2 > n_allocated) { /* We allocate 16 entries at a time, as a matter of optimization */ if (n_items > (SIZE_MAX / sizeof(uint16_t)) - 16) /* Overflow check, just in case */ return log_oom(); size_t m = n_items + 16; items = xrealloc(items, n_allocated * sizeof(uint16_t *), m * sizeof(uint16_t *)); n_allocated = m; } items[n_items++] = TAKE_PTR(d); items[n_items] = NULL; /* Let's always NUL terminate, to make freeing via strv_free() easy */ } if (n_items == 0) /* Empty directory */ goto nothing; /* Now, sort the files we found, to make this uniform and stable (and to ensure the TPM measurements * are not dependent on read order) */ sort_pointer_array((void**) items, n_items, (compare_pointer_func_t) strcmp16); /* Generate the leading directory inodes right before adding the first files, to the * archive. Otherwise the cpio archive cannot be unpacked, since the leading dirs won't exist. */ err = pack_cpio_prefix(target_dir_prefix, dir_mode, &inode, &buffer, &buffer_size); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to pack cpio prefix: %m"); for (size_t i = 0; i < n_items; i++) { _cleanup_free_ char *content = NULL; size_t contentsize = 0; /* avoid false maybe-uninitialized warning */ err = file_read(extra_dir, items[i], 0, 0, &content, &contentsize); if (err != EFI_SUCCESS) { log_error_status(err, "Failed to read %ls, ignoring: %m", items[i]); continue; } err = pack_cpio_one( items[i], content, contentsize, target_dir_prefix, access_mode, &inode, &buffer, &buffer_size); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to pack cpio file %ls: %m", dirent->FileName); } err = pack_cpio_trailer(&buffer, &buffer_size); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to pack cpio trailer: %m"); err = tpm_log_event( tpm_pcr, POINTER_TO_PHYSICAL_ADDRESS(buffer), buffer_size, tpm_description, ret_measured); if (err != EFI_SUCCESS) return log_error_status( err, "Unable to add cpio TPM measurement for PCR %u (%ls), ignoring: %m", tpm_pcr, tpm_description); *ret_buffer = TAKE_PTR(buffer); *ret_buffer_size = buffer_size; return EFI_SUCCESS; nothing: *ret_buffer = NULL; *ret_buffer_size = 0; if (ret_measured) *ret_measured = false; return EFI_SUCCESS; } EFI_STATUS pack_cpio_literal( const void *data, size_t data_size, const char *target_dir_prefix, const char16_t *target_filename, uint32_t dir_mode, uint32_t access_mode, uint32_t tpm_pcr, const char16_t *tpm_description, void **ret_buffer, size_t *ret_buffer_size, bool *ret_measured) { uint32_t inode = 1; /* inode counter, so that each item gets a new inode */ _cleanup_free_ void *buffer = NULL; size_t buffer_size = 0; EFI_STATUS err; assert(data || data_size == 0); assert(target_dir_prefix); assert(target_filename); assert(ret_buffer); assert(ret_buffer_size); /* Generate the leading directory inodes right before adding the first files, to the * archive. Otherwise the cpio archive cannot be unpacked, since the leading dirs won't exist. */ err = pack_cpio_prefix(target_dir_prefix, dir_mode, &inode, &buffer, &buffer_size); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to pack cpio prefix: %m"); err = pack_cpio_one( target_filename, data, data_size, target_dir_prefix, access_mode, &inode, &buffer, &buffer_size); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to pack cpio file %ls: %m", target_filename); err = pack_cpio_trailer(&buffer, &buffer_size); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to pack cpio trailer: %m"); err = tpm_log_event( tpm_pcr, POINTER_TO_PHYSICAL_ADDRESS(buffer), buffer_size, tpm_description, ret_measured); if (err != EFI_SUCCESS) return log_error_status( err, "Unable to add cpio TPM measurement for PCR %u (%ls), ignoring: %m", tpm_pcr, tpm_description); *ret_buffer = TAKE_PTR(buffer); *ret_buffer_size = buffer_size; return EFI_SUCCESS; }
19,668
37.566667
114
c
null
systemd-main/src/boot/efi/cpio.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "efi.h" #include "proto/loaded-image.h" EFI_STATUS pack_cpio( EFI_LOADED_IMAGE_PROTOCOL *loaded_image, const char16_t *dropin_dir, const char16_t *match_suffix, const char *target_dir_prefix, uint32_t dir_mode, uint32_t access_mode, uint32_t tpm_pcr, const char16_t *tpm_description, void **ret_buffer, size_t *ret_buffer_size, bool *ret_measured); EFI_STATUS pack_cpio_literal( const void *data, size_t data_size, const char *target_dir_prefix, const char16_t *target_filename, uint32_t dir_mode, uint32_t access_mode, uint32_t tpm_pcr, const char16_t *tpm_description, void **ret_buffer, size_t *ret_buffer_size, bool *ret_measured);
1,062
32.21875
56
h
null
systemd-main/src/boot/efi/device-path-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "device-path-util.h" #include "util.h" EFI_STATUS make_file_device_path(EFI_HANDLE device, const char16_t *file, EFI_DEVICE_PATH **ret_dp) { EFI_STATUS err; EFI_DEVICE_PATH *dp; assert(file); assert(ret_dp); err = BS->HandleProtocol(device, MAKE_GUID_PTR(EFI_DEVICE_PATH_PROTOCOL), (void **) &dp); if (err != EFI_SUCCESS) return err; EFI_DEVICE_PATH *end_node = dp; while (!device_path_is_end(end_node)) end_node = device_path_next_node(end_node); size_t file_size = strsize16(file); size_t dp_size = (uint8_t *) end_node - (uint8_t *) dp; /* Make a copy that can also hold a file media device path. */ *ret_dp = xmalloc(dp_size + file_size + sizeof(FILEPATH_DEVICE_PATH) + sizeof(EFI_DEVICE_PATH)); dp = mempcpy(*ret_dp, dp, dp_size); FILEPATH_DEVICE_PATH *file_dp = (FILEPATH_DEVICE_PATH *) dp; file_dp->Header = (EFI_DEVICE_PATH) { .Type = MEDIA_DEVICE_PATH, .SubType = MEDIA_FILEPATH_DP, .Length = sizeof(FILEPATH_DEVICE_PATH) + file_size, }; memcpy(file_dp->PathName, file, file_size); dp = device_path_next_node(dp); *dp = DEVICE_PATH_END_NODE; return EFI_SUCCESS; } static char16_t *device_path_to_str_internal(const EFI_DEVICE_PATH *dp) { char16_t *str = NULL; for (const EFI_DEVICE_PATH *node = dp; !device_path_is_end(node); node = device_path_next_node(node)) { _cleanup_free_ char16_t *old = str; if (node->Type == END_DEVICE_PATH_TYPE && node->SubType == END_INSTANCE_DEVICE_PATH_SUBTYPE) { str = xasprintf("%ls%s,", strempty(old), old ? "\\" : ""); continue; } /* Special-case this so that FilePath-only device path string look and behave nicely. */ if (node->Type == MEDIA_DEVICE_PATH && node->SubType == MEDIA_FILEPATH_DP) { str = xasprintf("%ls%s%ls", strempty(old), old ? "\\" : "", ((FILEPATH_DEVICE_PATH *) node)->PathName); continue; } /* Instead of coding all the different types and sub-types here we just use the * generic node form. This function is a best-effort for firmware that does not * provide the EFI_DEVICE_PATH_TO_TEXT_PROTOCOL after all. */ size_t size = node->Length - sizeof(EFI_DEVICE_PATH); _cleanup_free_ char16_t *hex_data = hexdump((uint8_t *) node + sizeof(EFI_DEVICE_PATH), size); str = xasprintf("%ls%sPath(%u,%u%s%ls)", strempty(old), old ? "/" : "", node->Type, node->SubType, size == 0 ? "" : ",", hex_data); } return str; } EFI_STATUS device_path_to_str(const EFI_DEVICE_PATH *dp, char16_t **ret) { EFI_DEVICE_PATH_TO_TEXT_PROTOCOL *dp_to_text; EFI_STATUS err; _cleanup_free_ char16_t *str = NULL; assert(dp); assert(ret); err = BS->LocateProtocol(MAKE_GUID_PTR(EFI_DEVICE_PATH_TO_TEXT_PROTOCOL), NULL, (void **) &dp_to_text); if (err != EFI_SUCCESS) { *ret = device_path_to_str_internal(dp); return EFI_SUCCESS; } str = dp_to_text->ConvertDevicePathToText(dp, false, false); if (!str) return EFI_OUT_OF_RESOURCES; *ret = TAKE_PTR(str); return EFI_SUCCESS; } bool device_path_startswith(const EFI_DEVICE_PATH *dp, const EFI_DEVICE_PATH *start) { if (!start) return true; if (!dp) return false; for (;;) { if (device_path_is_end(start)) return true; if (device_path_is_end(dp)) return false; if (start->Length != dp->Length) return false; if (memcmp(dp, start, start->Length) != 0) return false; start = device_path_next_node(start); dp = device_path_next_node(dp); } } EFI_DEVICE_PATH *device_path_replace_node( const EFI_DEVICE_PATH *path, const EFI_DEVICE_PATH *node, const EFI_DEVICE_PATH *new_node) { /* Create a new device path as a copy of path, while chopping off the remainder starting at the given * node. If new_node is provided, it is appended at the end of the new path. */ assert(path); assert(node); size_t len = (uint8_t *) node - (uint8_t *) path; EFI_DEVICE_PATH *ret = xmalloc(len + (new_node ? new_node->Length : 0) + sizeof(EFI_DEVICE_PATH)); EFI_DEVICE_PATH *end = mempcpy(ret, path, len); if (new_node) end = mempcpy(end, new_node, new_node->Length); *end = DEVICE_PATH_END_NODE; return ret; }
5,339
37.417266
111
c
null
systemd-main/src/boot/efi/device-path-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "proto/device-path.h" EFI_STATUS make_file_device_path(EFI_HANDLE device, const char16_t *file, EFI_DEVICE_PATH **ret_dp); EFI_STATUS device_path_to_str(const EFI_DEVICE_PATH *dp, char16_t **ret); bool device_path_startswith(const EFI_DEVICE_PATH *dp, const EFI_DEVICE_PATH *start); EFI_DEVICE_PATH *device_path_replace_node( const EFI_DEVICE_PATH *path, const EFI_DEVICE_PATH *node, const EFI_DEVICE_PATH *new_node); static inline EFI_DEVICE_PATH *device_path_next_node(const EFI_DEVICE_PATH *dp) { assert(dp); return (EFI_DEVICE_PATH *) ((uint8_t *) dp + dp->Length); } static inline bool device_path_is_end(const EFI_DEVICE_PATH *dp) { assert(dp); return dp->Type == END_DEVICE_PATH_TYPE && dp->SubType == END_ENTIRE_DEVICE_PATH_SUBTYPE; } #define DEVICE_PATH_END_NODE \ (EFI_DEVICE_PATH) { \ .Type = END_DEVICE_PATH_TYPE, \ .SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE, \ .Length = sizeof(EFI_DEVICE_PATH) \ }
1,182
41.25
107
h
null
systemd-main/src/boot/efi/devicetree.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "devicetree.h" #include "proto/dt-fixup.h" #include "util.h" #define FDT_V1_SIZE (7*4) static EFI_STATUS devicetree_allocate(struct devicetree_state *state, size_t size) { size_t pages = DIV_ROUND_UP(size, EFI_PAGE_SIZE); EFI_STATUS err; assert(state); err = BS->AllocatePages(AllocateAnyPages, EfiACPIReclaimMemory, pages, &state->addr); if (err != EFI_SUCCESS) return err; state->pages = pages; return err; } static size_t devicetree_allocated(const struct devicetree_state *state) { assert(state); return state->pages * EFI_PAGE_SIZE; } static EFI_STATUS devicetree_fixup(struct devicetree_state *state, size_t len) { EFI_DT_FIXUP_PROTOCOL *fixup; size_t size; EFI_STATUS err; assert(state); err = BS->LocateProtocol(MAKE_GUID_PTR(EFI_DT_FIXUP_PROTOCOL), NULL, (void **) &fixup); if (err != EFI_SUCCESS) return log_error_status(EFI_SUCCESS, "Could not locate device tree fixup protocol, skipping."); size = devicetree_allocated(state); err = fixup->Fixup(fixup, PHYSICAL_ADDRESS_TO_POINTER(state->addr), &size, EFI_DT_APPLY_FIXUPS | EFI_DT_RESERVE_MEMORY); if (err == EFI_BUFFER_TOO_SMALL) { EFI_PHYSICAL_ADDRESS oldaddr = state->addr; size_t oldpages = state->pages; void *oldptr = PHYSICAL_ADDRESS_TO_POINTER(state->addr); err = devicetree_allocate(state, size); if (err != EFI_SUCCESS) return err; memcpy(PHYSICAL_ADDRESS_TO_POINTER(state->addr), oldptr, len); err = BS->FreePages(oldaddr, oldpages); if (err != EFI_SUCCESS) return err; size = devicetree_allocated(state); err = fixup->Fixup(fixup, PHYSICAL_ADDRESS_TO_POINTER(state->addr), &size, EFI_DT_APPLY_FIXUPS | EFI_DT_RESERVE_MEMORY); } return err; } EFI_STATUS devicetree_install(struct devicetree_state *state, EFI_FILE *root_dir, char16_t *name) { _cleanup_(file_closep) EFI_FILE *handle = NULL; _cleanup_free_ EFI_FILE_INFO *info = NULL; size_t len; EFI_STATUS err; assert(state); assert(root_dir); assert(name); state->orig = find_configuration_table(MAKE_GUID_PTR(EFI_DTB_TABLE)); if (!state->orig) return EFI_UNSUPPORTED; err = root_dir->Open(root_dir, &handle, name, EFI_FILE_MODE_READ, EFI_FILE_READ_ONLY); if (err != EFI_SUCCESS) return err; err = get_file_info(handle, &info, NULL); if (err != EFI_SUCCESS) return err; if (info->FileSize < FDT_V1_SIZE || info->FileSize > 32 * 1024 * 1024) /* 32MB device tree blob doesn't seem right */ return EFI_INVALID_PARAMETER; len = info->FileSize; err = devicetree_allocate(state, len); if (err != EFI_SUCCESS) return err; err = handle->Read(handle, &len, PHYSICAL_ADDRESS_TO_POINTER(state->addr)); if (err != EFI_SUCCESS) return err; err = devicetree_fixup(state, len); if (err != EFI_SUCCESS) return err; return BS->InstallConfigurationTable( MAKE_GUID_PTR(EFI_DTB_TABLE), PHYSICAL_ADDRESS_TO_POINTER(state->addr)); } EFI_STATUS devicetree_install_from_memory( struct devicetree_state *state, const void *dtb_buffer, size_t dtb_length) { EFI_STATUS err; assert(state); assert(dtb_buffer && dtb_length > 0); state->orig = find_configuration_table(MAKE_GUID_PTR(EFI_DTB_TABLE)); if (!state->orig) return EFI_UNSUPPORTED; err = devicetree_allocate(state, dtb_length); if (err != EFI_SUCCESS) return err; memcpy(PHYSICAL_ADDRESS_TO_POINTER(state->addr), dtb_buffer, dtb_length); err = devicetree_fixup(state, dtb_length); if (err != EFI_SUCCESS) return err; return BS->InstallConfigurationTable( MAKE_GUID_PTR(EFI_DTB_TABLE), PHYSICAL_ADDRESS_TO_POINTER(state->addr)); } void devicetree_cleanup(struct devicetree_state *state) { EFI_STATUS err; if (!state->pages) return; err = BS->InstallConfigurationTable(MAKE_GUID_PTR(EFI_DTB_TABLE), state->orig); /* don't free the current device tree if we can't reinstate the old one */ if (err != EFI_SUCCESS) return; BS->FreePages(state->addr, state->pages); state->pages = 0; }
4,885
32.238095
111
c
null
systemd-main/src/boot/efi/drivers.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "device-path-util.h" #include "drivers.h" #include "util.h" static EFI_STATUS load_one_driver( EFI_HANDLE parent_image, EFI_LOADED_IMAGE_PROTOCOL *loaded_image, const char16_t *fname) { _cleanup_(unload_imagep) EFI_HANDLE image = NULL; _cleanup_free_ EFI_DEVICE_PATH *path = NULL; _cleanup_free_ char16_t *spath = NULL; EFI_STATUS err; assert(parent_image); assert(loaded_image); assert(fname); spath = xasprintf("\\EFI\\systemd\\drivers\\%ls", fname); err = make_file_device_path(loaded_image->DeviceHandle, spath, &path); if (err != EFI_SUCCESS) return log_error_status(err, "Error making file device path: %m"); err = BS->LoadImage(false, parent_image, path, NULL, 0, &image); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to load image %ls: %m", fname); err = BS->HandleProtocol(image, MAKE_GUID_PTR(EFI_LOADED_IMAGE_PROTOCOL), (void **) &loaded_image); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to find protocol in driver image %ls: %m", fname); if (loaded_image->ImageCodeType != EfiBootServicesCode && loaded_image->ImageCodeType != EfiRuntimeServicesCode) return log_error("Image %ls is not a driver, refusing.", fname); err = BS->StartImage(image, NULL, NULL); if (err != EFI_SUCCESS) { /* EFI_ABORTED signals an initializing driver. It uses this error code on success * so that it is unloaded after. */ if (err != EFI_ABORTED) log_error_status(err, "Failed to start image %ls: %m", fname); return err; } TAKE_PTR(image); return EFI_SUCCESS; } EFI_STATUS reconnect_all_drivers(void) { _cleanup_free_ EFI_HANDLE *handles = NULL; size_t n_handles = 0; EFI_STATUS err; /* Reconnects all handles, so that any loaded drivers can take effect. */ err = BS->LocateHandleBuffer(AllHandles, NULL, NULL, &n_handles, &handles); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to get list of handles: %m"); for (size_t i = 0; i < n_handles; i++) /* Some firmware gives us some bogus handles (or they might become bad due to * reconnecting everything). Security policy may also prevent us from doing so too. * There is nothing we can realistically do on errors anyways, so just ignore them. */ (void) BS->ConnectController(handles[i], NULL, NULL, true); return EFI_SUCCESS; } EFI_STATUS load_drivers( EFI_HANDLE parent_image, EFI_LOADED_IMAGE_PROTOCOL *loaded_image, EFI_FILE *root_dir) { _cleanup_(file_closep) EFI_FILE *drivers_dir = NULL; _cleanup_free_ EFI_FILE_INFO *dirent = NULL; size_t dirent_size = 0, n_succeeded = 0; EFI_STATUS err; err = open_directory( root_dir, u"\\EFI\\systemd\\drivers", &drivers_dir); if (err == EFI_NOT_FOUND) return EFI_SUCCESS; if (err != EFI_SUCCESS) return log_error_status(err, "Failed to open \\EFI\\systemd\\drivers: %m"); for (;;) { err = readdir(drivers_dir, &dirent, &dirent_size); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to read extra directory of loaded image: %m"); if (!dirent) /* End of directory */ break; if (dirent->FileName[0] == '.') continue; if (FLAGS_SET(dirent->Attribute, EFI_FILE_DIRECTORY)) continue; if (!endswith_no_case(dirent->FileName, EFI_MACHINE_TYPE_NAME u".efi")) continue; err = load_one_driver(parent_image, loaded_image, dirent->FileName); if (err != EFI_SUCCESS) continue; n_succeeded++; } if (n_succeeded > 0) (void) reconnect_all_drivers(); return EFI_SUCCESS; }
4,448
37.353448
107
c
null
systemd-main/src/boot/efi/efi-string.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "efi.h" #include "macro-fundamental.h" size_t strnlen8(const char *s, size_t n); size_t strnlen16(const char16_t *s, size_t n); static inline size_t strlen8(const char *s) { return strnlen8(s, SIZE_MAX); } static inline size_t strlen16(const char16_t *s) { return strnlen16(s, SIZE_MAX); } static inline size_t strsize8(const char *s) { return s ? (strlen8(s) + 1) * sizeof(*s) : 0; } static inline size_t strsize16(const char16_t *s) { return s ? (strlen16(s) + 1) * sizeof(*s) : 0; } void strtolower8(char *s); void strtolower16(char16_t *s); int strncmp8(const char *s1, const char *s2, size_t n); int strncmp16(const char16_t *s1, const char16_t *s2, size_t n); int strncasecmp8(const char *s1, const char *s2, size_t n); int strncasecmp16(const char16_t *s1, const char16_t *s2, size_t n); static inline int strcmp8(const char *s1, const char *s2) { return strncmp8(s1, s2, SIZE_MAX); } static inline int strcmp16(const char16_t *s1, const char16_t *s2) { return strncmp16(s1, s2, SIZE_MAX); } static inline int strcasecmp8(const char *s1, const char *s2) { return strncasecmp8(s1, s2, SIZE_MAX); } static inline int strcasecmp16(const char16_t *s1, const char16_t *s2) { return strncasecmp16(s1, s2, SIZE_MAX); } static inline bool strneq8(const char *s1, const char *s2, size_t n) { return strncmp8(s1, s2, n) == 0; } static inline bool strneq16(const char16_t *s1, const char16_t *s2, size_t n) { return strncmp16(s1, s2, n) == 0; } static inline bool streq8(const char *s1, const char *s2) { return strcmp8(s1, s2) == 0; } static inline bool streq16(const char16_t *s1, const char16_t *s2) { return strcmp16(s1, s2) == 0; } static inline int strncaseeq8(const char *s1, const char *s2, size_t n) { return strncasecmp8(s1, s2, n) == 0; } static inline int strncaseeq16(const char16_t *s1, const char16_t *s2, size_t n) { return strncasecmp16(s1, s2, n) == 0; } static inline bool strcaseeq8(const char *s1, const char *s2) { return strcasecmp8(s1, s2) == 0; } static inline bool strcaseeq16(const char16_t *s1, const char16_t *s2) { return strcasecmp16(s1, s2) == 0; } char *strcpy8(char * restrict dest, const char * restrict src); char16_t *strcpy16(char16_t * restrict dest, const char16_t * restrict src); char *strchr8(const char *s, char c); char16_t *strchr16(const char16_t *s, char16_t c); char *xstrndup8(const char *s, size_t n); char16_t *xstrndup16(const char16_t *s, size_t n); static inline char *xstrdup8(const char *s) { return xstrndup8(s, SIZE_MAX); } static inline char16_t *xstrdup16(const char16_t *s) { return xstrndup16(s, SIZE_MAX); } char16_t *xstrn8_to_16(const char *str8, size_t n); static inline char16_t *xstr8_to_16(const char *str8) { return xstrn8_to_16(str8, strlen8(str8)); } char *startswith8(const char *s, const char *prefix); bool efi_fnmatch(const char16_t *pattern, const char16_t *haystack); bool parse_number8(const char *s, uint64_t *ret_u, const char **ret_tail); bool parse_number16(const char16_t *s, uint64_t *ret_u, const char16_t **ret_tail); char16_t *hexdump(const void *data, size_t size); #ifdef __clang__ # define _gnu_printf_(a, b) _printf_(a, b) #else # define _gnu_printf_(a, b) __attribute__((format(gnu_printf, a, b))) #endif _gnu_printf_(2, 3) void printf_status(EFI_STATUS status, const char *format, ...); _gnu_printf_(2, 0) void vprintf_status(EFI_STATUS status, const char *format, va_list ap); _gnu_printf_(2, 3) _warn_unused_result_ char16_t *xasprintf_status(EFI_STATUS status, const char *format, ...); _gnu_printf_(2, 0) _warn_unused_result_ char16_t *xvasprintf_status(EFI_STATUS status, const char *format, va_list ap); #if SD_BOOT # define printf(...) printf_status(EFI_SUCCESS, __VA_ARGS__) # define xasprintf(...) xasprintf_status(EFI_SUCCESS, __VA_ARGS__) /* inttypes.h is provided by libc instead of the compiler and is not supposed to be used in freestanding * environments. We could use clang __*_FMT*__ constants for this, bug gcc does not have them. :( */ # if defined(__ILP32__) || defined(__arm__) || defined(__i386__) # define PRI64_PREFIX "ll" # elif defined(__LP64__) # define PRI64_PREFIX "l" # elif defined(__LLP64__) || (__SIZEOF_LONG__ == 4 && __SIZEOF_POINTER__ == 8) # define PRI64_PREFIX "ll" # else # error Unknown 64-bit data model # endif # define PRIi32 "i" # define PRIu32 "u" # define PRIx32 "x" # define PRIX32 "X" # define PRIiPTR "zi" # define PRIuPTR "zu" # define PRIxPTR "zx" # define PRIXPTR "zX" # define PRIi64 PRI64_PREFIX "i" # define PRIu64 PRI64_PREFIX "u" # define PRIx64 PRI64_PREFIX "x" # define PRIX64 PRI64_PREFIX "X" /* The compiler normally has knowledge about standard functions such as memcmp, but this is not the case when * compiling with -ffreestanding. By referring to builtins, the compiler can check arguments and do * optimizations again. Note that we still need to provide implementations as the compiler is free to not * inline its own implementation and instead issue a library call. */ # define memchr __builtin_memchr # define memcmp __builtin_memcmp # define memcpy __builtin_memcpy # define memset __builtin_memset static inline void *mempcpy(void * restrict dest, const void * restrict src, size_t n) { if (!dest || !src || n == 0) return dest; memcpy(dest, src, n); return (uint8_t *) dest + n; } #else /* For unit testing. */ void *efi_memchr(const void *p, int c, size_t n); int efi_memcmp(const void *p1, const void *p2, size_t n); void *efi_memcpy(void * restrict dest, const void * restrict src, size_t n); void *efi_memset(void *p, int c, size_t n); #endif
5,852
32.067797
119
h
null
systemd-main/src/boot/efi/efi.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdarg.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #include "macro-fundamental.h" #if SD_BOOT /* uchar.h/wchar.h are not suitable for freestanding environments. */ typedef __WCHAR_TYPE__ wchar_t; typedef __CHAR16_TYPE__ char16_t; typedef __CHAR32_TYPE__ char32_t; /* Let's be paranoid and do some sanity checks. */ assert_cc(__STDC_HOSTED__ == 0); assert_cc(sizeof(bool) == 1); assert_cc(sizeof(uint8_t) == 1); assert_cc(sizeof(uint16_t) == 2); assert_cc(sizeof(uint32_t) == 4); assert_cc(sizeof(uint64_t) == 8); assert_cc(sizeof(wchar_t) == 2); assert_cc(sizeof(char16_t) == 2); assert_cc(sizeof(char32_t) == 4); assert_cc(sizeof(size_t) == sizeof(void *)); assert_cc(sizeof(size_t) == sizeof(uintptr_t)); # if defined(__x86_64__) && defined(__ILP32__) # error Building for x64 requires -m64 on x32 ABI. # endif #else # include <uchar.h> # include <wchar.h> #endif /* We use size_t/ssize_t to represent UEFI UINTN/INTN. */ typedef size_t EFI_STATUS; typedef intptr_t ssize_t; typedef void* EFI_HANDLE; typedef void* EFI_EVENT; typedef size_t EFI_TPL; typedef uint64_t EFI_LBA; typedef uint64_t EFI_PHYSICAL_ADDRESS; #if defined(__x86_64__) && !defined(__ILP32__) # define EFIAPI __attribute__((ms_abi)) #else # define EFIAPI #endif #if __SIZEOF_POINTER__ == 8 # define EFI_ERROR_MASK 0x8000000000000000ULL #elif __SIZEOF_POINTER__ == 4 # define EFI_ERROR_MASK 0x80000000ULL #else # error Unsupported pointer size #endif #define EFIWARN(s) ((EFI_STATUS) s) #define EFIERR(s) ((EFI_STATUS) (s | EFI_ERROR_MASK)) #define EFI_SUCCESS EFIWARN(0) #define EFI_WARN_UNKNOWN_GLYPH EFIWARN(1) #define EFI_WARN_DELETE_FAILURE EFIWARN(2) #define EFI_WARN_WRITE_FAILURE EFIWARN(3) #define EFI_WARN_BUFFER_TOO_SMALL EFIWARN(4) #define EFI_WARN_STALE_DATA EFIWARN(5) #define EFI_WARN_FILE_SYSTEM EFIWARN(6) #define EFI_WARN_RESET_REQUIRED EFIWARN(7) #define EFI_LOAD_ERROR EFIERR(1) #define EFI_INVALID_PARAMETER EFIERR(2) #define EFI_UNSUPPORTED EFIERR(3) #define EFI_BAD_BUFFER_SIZE EFIERR(4) #define EFI_BUFFER_TOO_SMALL EFIERR(5) #define EFI_NOT_READY EFIERR(6) #define EFI_DEVICE_ERROR EFIERR(7) #define EFI_WRITE_PROTECTED EFIERR(8) #define EFI_OUT_OF_RESOURCES EFIERR(9) #define EFI_VOLUME_CORRUPTED EFIERR(10) #define EFI_VOLUME_FULL EFIERR(11) #define EFI_NO_MEDIA EFIERR(12) #define EFI_MEDIA_CHANGED EFIERR(13) #define EFI_NOT_FOUND EFIERR(14) #define EFI_ACCESS_DENIED EFIERR(15) #define EFI_NO_RESPONSE EFIERR(16) #define EFI_NO_MAPPING EFIERR(17) #define EFI_TIMEOUT EFIERR(18) #define EFI_NOT_STARTED EFIERR(19) #define EFI_ALREADY_STARTED EFIERR(20) #define EFI_ABORTED EFIERR(21) #define EFI_ICMP_ERROR EFIERR(22) #define EFI_TFTP_ERROR EFIERR(23) #define EFI_PROTOCOL_ERROR EFIERR(24) #define EFI_INCOMPATIBLE_VERSION EFIERR(25) #define EFI_SECURITY_VIOLATION EFIERR(26) #define EFI_CRC_ERROR EFIERR(27) #define EFI_END_OF_MEDIA EFIERR(28) #define EFI_ERROR_RESERVED_29 EFIERR(29) #define EFI_ERROR_RESERVED_30 EFIERR(30) #define EFI_END_OF_FILE EFIERR(31) #define EFI_INVALID_LANGUAGE EFIERR(32) #define EFI_COMPROMISED_DATA EFIERR(33) #define EFI_IP_ADDRESS_CONFLICT EFIERR(34) #define EFI_HTTP_ERROR EFIERR(35) typedef struct { uint32_t Data1; uint16_t Data2; uint16_t Data3; uint8_t Data4[8]; } EFI_GUID; #define GUID_DEF(d1, d2, d3, d4_1, d4_2, d4_3, d4_4, d4_5, d4_6, d4_7, d4_8) \ { d1, d2, d3, { d4_1, d4_2, d4_3, d4_4, d4_5, d4_6, d4_7, d4_8 } } /* Creates a EFI_GUID pointer suitable for EFI APIs. Use of const allows the compiler to merge multiple * uses (although, currently compilers do that regardless). Most EFI APIs declare their EFI_GUID input * as non-const, but almost all of them are in fact const. */ #define MAKE_GUID_PTR(name) ((EFI_GUID *) &(const EFI_GUID) name##_GUID) /* These allow MAKE_GUID_PTR() to work without requiring an extra _GUID in the passed name. We want to * keep the GUID definitions in line with the UEFI spec. */ #define EFI_GLOBAL_VARIABLE_GUID EFI_GLOBAL_VARIABLE #define EFI_FILE_INFO_GUID EFI_FILE_INFO_ID #define EFI_GLOBAL_VARIABLE \ GUID_DEF(0x8be4df61, 0x93ca, 0x11d2, 0xaa, 0x0d, 0x00, 0xe0, 0x98, 0x03, 0x2b, 0x8c) #define EFI_IMAGE_SECURITY_DATABASE_GUID \ GUID_DEF(0xd719b2cb, 0x3d3a, 0x4596, 0xa3, 0xbc, 0xda, 0xd0, 0x0e, 0x67, 0x65, 0x6f) #define EVT_TIMER 0x80000000U #define EVT_RUNTIME 0x40000000U #define EVT_NOTIFY_WAIT 0x00000100U #define EVT_NOTIFY_SIGNAL 0x00000200U #define EVT_SIGNAL_EXIT_BOOT_SERVICES 0x00000201U #define EVT_SIGNAL_VIRTUAL_ADDRESS_CHANGE 0x60000202U #define EFI_OPEN_PROTOCOL_BY_HANDLE_PROTOCOL 0x01U #define EFI_OPEN_PROTOCOL_GET_PROTOCOL 0x02U #define EFI_OPEN_PROTOCOL_TEST_PROTOCOL 0x04U #define EFI_OPEN_PROTOCOL_BY_CHILD_CONTROLLER 0x08U #define EFI_OPEN_PROTOCOL_BY_DRIVER 0x10U #define EFI_OPEN_PROTOCOL_EXCLUSIVE 0x20U #define EFI_VARIABLE_NON_VOLATILE 0x01U #define EFI_VARIABLE_BOOTSERVICE_ACCESS 0x02U #define EFI_VARIABLE_RUNTIME_ACCESS 0x04U #define EFI_VARIABLE_HARDWARE_ERROR_RECORD 0x08U #define EFI_VARIABLE_AUTHENTICATED_WRITE_ACCESS 0x10U #define EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS 0x20U #define EFI_VARIABLE_APPEND_WRITE 0x40U #define EFI_VARIABLE_ENHANCED_AUTHENTICATED_ACCESS 0x80U #define EFI_TIME_ADJUST_DAYLIGHT 0x001U #define EFI_TIME_IN_DAYLIGHT 0x002U #define EFI_UNSPECIFIED_TIMEZONE 0x7FFU #define EFI_OS_INDICATIONS_BOOT_TO_FW_UI 0x01U #define EFI_OS_INDICATIONS_TIMESTAMP_REVOCATION 0x02U #define EFI_OS_INDICATIONS_FILE_CAPSULE_DELIVERY_SUPPORTED 0x04U #define EFI_OS_INDICATIONS_FMP_CAPSULE_SUPPORTED 0x08U #define EFI_OS_INDICATIONS_CAPSULE_RESULT_VAR_SUPPORTED 0x10U #define EFI_OS_INDICATIONS_START_OS_RECOVERY 0x20U #define EFI_OS_INDICATIONS_START_PLATFORM_RECOVERY 0x40U #define EFI_OS_INDICATIONS_JSON_CONFIG_DATA_REFRESH 0x80U #define EFI_PAGE_SIZE 4096U #define EFI_SIZE_TO_PAGES(s) (((s) + 0xFFFU) >> 12U) /* These are common enough to warrant forward declaration. We also give them a * shorter name for convenience. */ typedef struct EFI_FILE_PROTOCOL EFI_FILE; typedef struct EFI_DEVICE_PATH_PROTOCOL EFI_DEVICE_PATH; typedef struct EFI_SIMPLE_TEXT_INPUT_PROTOCOL EFI_SIMPLE_TEXT_INPUT_PROTOCOL; typedef struct EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL; typedef enum { TimerCancel, TimerPeriodic, TimerRelative, } EFI_TIMER_DELAY; typedef enum { AllocateAnyPages, AllocateMaxAddress, AllocateAddress, MaxAllocateType, } EFI_ALLOCATE_TYPE; typedef enum { EfiReservedMemoryType, EfiLoaderCode, EfiLoaderData, EfiBootServicesCode, EfiBootServicesData, EfiRuntimeServicesCode, EfiRuntimeServicesData, EfiConventionalMemory, EfiUnusableMemory, EfiACPIReclaimMemory, EfiACPIMemoryNVS, EfiMemoryMappedIO, EfiMemoryMappedIOPortSpace, EfiPalCode, EfiPersistentMemory, EfiUnacceptedMemoryType, EfiMaxMemoryType, } EFI_MEMORY_TYPE; typedef enum { AllHandles, ByRegisterNotify, ByProtocol, } EFI_LOCATE_SEARCH_TYPE; typedef enum { EfiResetCold, EfiResetWarm, EfiResetShutdown, EfiResetPlatformSpecific, } EFI_RESET_TYPE; typedef struct { uint16_t Year; uint8_t Month; uint8_t Day; uint8_t Hour; uint8_t Minute; uint8_t Second; uint8_t Pad1; uint32_t Nanosecond; int16_t TimeZone; uint8_t Daylight; uint8_t Pad2; } EFI_TIME; typedef struct { uint32_t Resolution; uint32_t Accuracy; bool SetsToZero; } EFI_TIME_CAPABILITIES; typedef struct { uint64_t Signature; uint32_t Revision; uint32_t HeaderSize; uint32_t CRC32; uint32_t Reserved; } EFI_TABLE_HEADER; typedef struct { EFI_TABLE_HEADER Hdr; void *RaiseTPL; void *RestoreTPL; EFI_STATUS (EFIAPI *AllocatePages)( EFI_ALLOCATE_TYPE Type, EFI_MEMORY_TYPE MemoryType, size_t Pages, EFI_PHYSICAL_ADDRESS *Memory); EFI_STATUS (EFIAPI *FreePages)( EFI_PHYSICAL_ADDRESS Memory, size_t Pages); void *GetMemoryMap; EFI_STATUS (EFIAPI *AllocatePool)( EFI_MEMORY_TYPE PoolType, size_t Size, void **Buffer); EFI_STATUS (EFIAPI *FreePool)(void *Buffer); EFI_STATUS (EFIAPI *CreateEvent)( uint32_t Type, EFI_TPL NotifyTpl, void *NotifyFunction, void *NotifyContext, EFI_EVENT *Event); EFI_STATUS (EFIAPI *SetTimer)( EFI_EVENT Event, EFI_TIMER_DELAY Type, uint64_t TriggerTime); EFI_STATUS (EFIAPI *WaitForEvent)( size_t NumberOfEvents, EFI_EVENT *Event, size_t *Index); void *SignalEvent; EFI_STATUS (EFIAPI *CloseEvent)(EFI_EVENT Event); EFI_STATUS (EFIAPI *CheckEvent)(EFI_EVENT Event); void *InstallProtocolInterface; EFI_STATUS (EFIAPI *ReinstallProtocolInterface)( EFI_HANDLE Handle, EFI_GUID *Protocol, void *OldInterface, void *NewInterface); void *UninstallProtocolInterface; EFI_STATUS (EFIAPI *HandleProtocol)( EFI_HANDLE Handle, EFI_GUID *Protocol, void **Interface); void *Reserved; void *RegisterProtocolNotify; EFI_STATUS (EFIAPI *LocateHandle)( EFI_LOCATE_SEARCH_TYPE SearchType, EFI_GUID *Protocol, void *SearchKey, size_t *BufferSize, EFI_HANDLE *Buffer); EFI_STATUS (EFIAPI *LocateDevicePath)( EFI_GUID *Protocol, EFI_DEVICE_PATH **DevicePath, EFI_HANDLE *Device); EFI_STATUS (EFIAPI *InstallConfigurationTable)( EFI_GUID *Guid, void *Table); EFI_STATUS (EFIAPI *LoadImage)( bool BootPolicy, EFI_HANDLE ParentImageHandle, EFI_DEVICE_PATH *DevicePath, void *SourceBuffer, size_t SourceSize, EFI_HANDLE *ImageHandle); EFI_STATUS (EFIAPI *StartImage)( EFI_HANDLE ImageHandle, size_t *ExitDataSize, char16_t **ExitData); EFI_STATUS (EFIAPI *Exit)( EFI_HANDLE ImageHandle, EFI_STATUS ExitStatus, size_t ExitDataSize, char16_t *ExitData); EFI_STATUS (EFIAPI *UnloadImage)(EFI_HANDLE ImageHandle); void *ExitBootServices; EFI_STATUS (EFIAPI *GetNextMonotonicCount)(uint64_t *Count); EFI_STATUS (EFIAPI *Stall)(size_t Microseconds); EFI_STATUS (EFIAPI *SetWatchdogTimer)( size_t Timeout, uint64_t WatchdogCode, size_t DataSize, char16_t *WatchdogData); EFI_STATUS (EFIAPI *ConnectController)( EFI_HANDLE ControllerHandle, EFI_HANDLE *DriverImageHandle, EFI_DEVICE_PATH *RemainingDevicePath, bool Recursive); EFI_STATUS (EFIAPI *DisconnectController)( EFI_HANDLE ControllerHandle, EFI_HANDLE DriverImageHandle, EFI_HANDLE ChildHandle); EFI_STATUS (EFIAPI *OpenProtocol)( EFI_HANDLE Handle, EFI_GUID *Protocol, void **Interface, EFI_HANDLE AgentHandle, EFI_HANDLE ControllerHandle, uint32_t Attributes); EFI_STATUS (EFIAPI *CloseProtocol)( EFI_HANDLE Handle, EFI_GUID *Protocol, EFI_HANDLE AgentHandle, EFI_HANDLE ControllerHandle); void *OpenProtocolInformation; EFI_STATUS (EFIAPI *ProtocolsPerHandle)( EFI_HANDLE Handle, EFI_GUID ***ProtocolBuffer, size_t *ProtocolBufferCount); EFI_STATUS (EFIAPI *LocateHandleBuffer)( EFI_LOCATE_SEARCH_TYPE SearchType, EFI_GUID *Protocol, void *SearchKey, size_t *NoHandles, EFI_HANDLE **Buffer); EFI_STATUS (EFIAPI *LocateProtocol)( EFI_GUID *Protocol, void *Registration, void **Interface); EFI_STATUS (EFIAPI *InstallMultipleProtocolInterfaces)(EFI_HANDLE *Handle, ...); EFI_STATUS (EFIAPI *UninstallMultipleProtocolInterfaces)(EFI_HANDLE Handle, ...); EFI_STATUS (EFIAPI *CalculateCrc32)( void *Data, size_t DataSize, uint32_t *Crc32); void (EFIAPI *CopyMem)( void *Destination, void *Source, size_t Length); void (EFIAPI *SetMem)( void *Buffer, size_t Size, uint8_t Value); void *CreateEventEx; } EFI_BOOT_SERVICES; typedef struct { EFI_TABLE_HEADER Hdr; EFI_STATUS (EFIAPI *GetTime)( EFI_TIME *Time, EFI_TIME_CAPABILITIES *Capabilities); EFI_STATUS (EFIAPI *SetTime)(EFI_TIME *Time); void *GetWakeupTime; void *SetWakeupTime; void *SetVirtualAddressMap; void *ConvertPointer; EFI_STATUS (EFIAPI *GetVariable)( char16_t *VariableName, EFI_GUID *VendorGuid, uint32_t *Attributes, size_t *DataSize, void *Data); void *GetNextVariableName; EFI_STATUS (EFIAPI *SetVariable)( char16_t *VariableName, EFI_GUID *VendorGuid, uint32_t Attributes, size_t DataSize, void *Data); EFI_STATUS (EFIAPI *GetNextHighMonotonicCount)(uint32_t *HighCount); void (EFIAPI *ResetSystem)( EFI_RESET_TYPE ResetType, EFI_STATUS ResetStatus, size_t DataSize, void *ResetData); void *UpdateCapsule; void *QueryCapsuleCapabilities; void *QueryVariableInfo; } EFI_RUNTIME_SERVICES; typedef struct { EFI_TABLE_HEADER Hdr; char16_t *FirmwareVendor; uint32_t FirmwareRevision; EFI_HANDLE ConsoleInHandle; EFI_SIMPLE_TEXT_INPUT_PROTOCOL *ConIn; EFI_HANDLE ConsoleOutHandle; EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *ConOut; EFI_HANDLE StandardErrorHandle; EFI_SIMPLE_TEXT_OUTPUT_PROTOCOL *StdErr; EFI_RUNTIME_SERVICES *RuntimeServices; EFI_BOOT_SERVICES *BootServices; size_t NumberOfTableEntries; struct { EFI_GUID VendorGuid; void *VendorTable; } *ConfigurationTable; } EFI_SYSTEM_TABLE; extern EFI_SYSTEM_TABLE *ST; extern EFI_BOOT_SERVICES *BS; extern EFI_RUNTIME_SERVICES *RT;
16,786
36.221729
103
h
null
systemd-main/src/boot/efi/fuzz-bcd.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "bcd.h" #include "fuzz.h" #include "utf8.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_free_ void *p = NULL; /* This limit was borrowed from src/boot/efi/boot.c */ if (outside_size_range(size, 0, 100*1024)) return 0; p = memdup(data, size); assert_se(p); char16_t *title = get_bcd_title(p, size); /* If we get something, it must be NUL-terminated, but an empty string is still valid! */ DO_NOT_OPTIMIZE(title && char16_strlen(title)); return 0; }
651
27.347826
97
c
null
systemd-main/src/boot/efi/fuzz-efi-printf.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "efi-string.h" #include "fuzz.h" #include "utf8.h" typedef struct { EFI_STATUS status; int16_t field_width; int16_t precision; const void *ptr; char c; unsigned char uchar; signed char schar; unsigned short ushort; signed short sshort; unsigned int uint; signed int sint; unsigned long ulong; signed long slong; unsigned long long ulonglong; signed long long slonglong; size_t size; ssize_t ssize; intmax_t intmax; uintmax_t uintmax; ptrdiff_t ptrdiff; char str[]; } Input; #define PRINTF_ONE(...) \ ({ \ _cleanup_free_ char16_t *_ret = xasprintf_status(__VA_ARGS__); \ DO_NOT_OPTIMIZE(_ret); \ }) int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { if (outside_size_range(size, sizeof(Input), 1024 * 1024)) return 0; const Input *i = (const Input *) data; size_t len = size - offsetof(Input, str); PRINTF_ONE(i->status, "%*.*s", i->field_width, (int) len, i->str); PRINTF_ONE(i->status, "%*.*ls", i->field_width, (int) (len / sizeof(wchar_t)), (const wchar_t *) i->str); PRINTF_ONE(i->status, "%% %*.*m", i->field_width, i->precision); PRINTF_ONE(i->status, "%*p", i->field_width, i->ptr); PRINTF_ONE(i->status, "%*c %12340c %56789c", i->field_width, i->c, i->c, i->c); PRINTF_ONE(i->status, "%*.*hhu", i->field_width, i->precision, i->uchar); PRINTF_ONE(i->status, "%*.*hhi", i->field_width, i->precision, i->schar); PRINTF_ONE(i->status, "%*.*hu", i->field_width, i->precision, i->ushort); PRINTF_ONE(i->status, "%*.*hi", i->field_width, i->precision, i->sshort); PRINTF_ONE(i->status, "%*.*u", i->field_width, i->precision, i->uint); PRINTF_ONE(i->status, "%*.*i", i->field_width, i->precision, i->sint); PRINTF_ONE(i->status, "%*.*lu", i->field_width, i->precision, i->ulong); PRINTF_ONE(i->status, "%*.*li", i->field_width, i->precision, i->slong); PRINTF_ONE(i->status, "%*.*llu", i->field_width, i->precision, i->ulonglong); PRINTF_ONE(i->status, "%*.*lli", i->field_width, i->precision, i->slonglong); PRINTF_ONE(i->status, "%+*.*hhi", i->field_width, i->precision, i->schar); PRINTF_ONE(i->status, "%-*.*hi", i->field_width, i->precision, i->sshort); PRINTF_ONE(i->status, "% *.*i", i->field_width, i->precision, i->sint); PRINTF_ONE(i->status, "%0*li", i->field_width, i->slong); PRINTF_ONE(i->status, "%#*.*llx", i->field_width, i->precision, i->ulonglong); PRINTF_ONE(i->status, "%-*.*zx", i->field_width, i->precision, i->size); PRINTF_ONE(i->status, "% *.*zi", i->field_width, i->precision, i->ssize); PRINTF_ONE(i->status, "%0*ji", i->field_width, i->intmax); PRINTF_ONE(i->status, "%#0*jX", i->field_width, i->uintmax); PRINTF_ONE(i->status, "%*.*ti", i->field_width, i->precision, i->ptrdiff); return 0; }
3,355
42.584416
113
c
null
systemd-main/src/boot/efi/fuzz-efi-string.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "efi-string.h" #include "fuzz.h" #include "utf8.h" static char16_t *memdup_str16(const uint8_t *data, size_t size) { char16_t *ret = memdup(data, size); assert_se(ret); ret[size / sizeof(char16_t) - 1] = '\0'; return ret; } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { if (outside_size_range(size, sizeof(size_t), 64 * 1024)) return 0; size_t len, len2; memcpy(&len, data, sizeof(len)); data += sizeof(len); size -= sizeof(len); len2 = size - len; if (len > size || len < sizeof(char16_t) || len2 < sizeof(char16_t)) return 0; const char *tail8 = NULL; _cleanup_free_ char *str8 = ASSERT_SE_PTR(memdup_suffix0(data, size)); DO_NOT_OPTIMIZE(parse_number8(str8, &(uint64_t){ 0 }, size % 2 == 0 ? NULL : &tail8)); const char16_t *tail16 = NULL; _cleanup_free_ char16_t *str16 = memdup_str16(data, size); DO_NOT_OPTIMIZE(parse_number16(str16, &(uint64_t){ 0 }, size % 2 == 0 ? NULL : &tail16)); _cleanup_free_ char16_t *pattern = memdup_str16(data, len), *haystack = memdup_str16(data + len, len2); DO_NOT_OPTIMIZE(efi_fnmatch(pattern, haystack)); return 0; }
1,357
32.121951
111
c
null
systemd-main/src/boot/efi/graphics.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Copyright © 2013 Intel Corporation * Authored by Joonas Lahtinen <[email protected]> */ #include "graphics.h" #include "proto/console-control.h" #include "proto/simple-text-io.h" #include "util.h" EFI_STATUS graphics_mode(bool on) { EFI_CONSOLE_CONTROL_PROTOCOL *ConsoleControl = NULL; EFI_CONSOLE_CONTROL_SCREEN_MODE new; EFI_CONSOLE_CONTROL_SCREEN_MODE current; bool uga_exists, stdin_locked; EFI_STATUS err; err = BS->LocateProtocol(MAKE_GUID_PTR(EFI_CONSOLE_CONTROL_PROTOCOL), NULL, (void **) &ConsoleControl); if (err != EFI_SUCCESS) /* console control protocol is nonstandard and might not exist. */ return err == EFI_NOT_FOUND ? EFI_SUCCESS : err; /* check current mode */ err = ConsoleControl->GetMode(ConsoleControl, &current, &uga_exists, &stdin_locked); if (err != EFI_SUCCESS) return err; /* do not touch the mode */ new = on ? EfiConsoleControlScreenGraphics : EfiConsoleControlScreenText; if (new == current) return EFI_SUCCESS; log_wait(); err = ConsoleControl->SetMode(ConsoleControl, new); /* some firmware enables the cursor when switching modes */ ST->ConOut->EnableCursor(ST->ConOut, false); return err; }
1,415
32.714286
111
c
null
systemd-main/src/boot/efi/initrd.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "initrd.h" #include "macro-fundamental.h" #include "proto/device-path.h" #include "proto/load-file.h" #include "util.h" #define LINUX_INITRD_MEDIA_GUID \ GUID_DEF(0x5568e427, 0x68fc, 0x4f3d, 0xac, 0x74, 0xca, 0x55, 0x52, 0x31, 0xcc, 0x68) /* extend LoadFileProtocol */ struct initrd_loader { EFI_LOAD_FILE_PROTOCOL load_file; const void *address; size_t length; }; /* static structure for LINUX_INITRD_MEDIA device path see https://github.com/torvalds/linux/blob/v5.13/drivers/firmware/efi/libstub/efi-stub-helper.c */ static const struct { VENDOR_DEVICE_PATH vendor; EFI_DEVICE_PATH end; } _packed_ efi_initrd_device_path = { .vendor = { .Header = { .Type = MEDIA_DEVICE_PATH, .SubType = MEDIA_VENDOR_DP, .Length = sizeof(efi_initrd_device_path.vendor), }, .Guid = LINUX_INITRD_MEDIA_GUID }, .end = { .Type = END_DEVICE_PATH_TYPE, .SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE, .Length = sizeof(efi_initrd_device_path.end), } }; static EFIAPI EFI_STATUS initrd_load_file( EFI_LOAD_FILE_PROTOCOL *this, EFI_DEVICE_PATH *file_path, bool boot_policy, size_t *buffer_size, void *buffer) { struct initrd_loader *loader; if (!this || !buffer_size || !file_path) return EFI_INVALID_PARAMETER; if (boot_policy) return EFI_UNSUPPORTED; loader = (struct initrd_loader *) this; if (loader->length == 0 || !loader->address) return EFI_NOT_FOUND; if (!buffer || *buffer_size < loader->length) { *buffer_size = loader->length; return EFI_BUFFER_TOO_SMALL; } memcpy(buffer, loader->address, loader->length); *buffer_size = loader->length; return EFI_SUCCESS; } EFI_STATUS initrd_register( const void *initrd_address, size_t initrd_length, EFI_HANDLE *ret_initrd_handle) { EFI_STATUS err; EFI_DEVICE_PATH *dp = (EFI_DEVICE_PATH *) &efi_initrd_device_path; EFI_HANDLE handle; struct initrd_loader *loader; assert(ret_initrd_handle); if (!initrd_address || initrd_length == 0) return EFI_SUCCESS; /* check if a LINUX_INITRD_MEDIA_GUID DevicePath is already registered. LocateDevicePath checks for the "closest DevicePath" and returns its handle, where as InstallMultipleProtocolInterfaces only matches identical DevicePaths. */ err = BS->LocateDevicePath(MAKE_GUID_PTR(EFI_LOAD_FILE2_PROTOCOL), &dp, &handle); if (err != EFI_NOT_FOUND) /* InitrdMedia is already registered */ return EFI_ALREADY_STARTED; loader = xnew(struct initrd_loader, 1); *loader = (struct initrd_loader) { .load_file.LoadFile = initrd_load_file, .address = initrd_address, .length = initrd_length }; /* create a new handle and register the LoadFile2 protocol with the InitrdMediaPath on it */ err = BS->InstallMultipleProtocolInterfaces( ret_initrd_handle, MAKE_GUID_PTR(EFI_DEVICE_PATH_PROTOCOL), &efi_initrd_device_path, MAKE_GUID_PTR(EFI_LOAD_FILE2_PROTOCOL), loader, NULL); if (err != EFI_SUCCESS) free(loader); return err; } EFI_STATUS initrd_unregister(EFI_HANDLE initrd_handle) { EFI_STATUS err; struct initrd_loader *loader; if (!initrd_handle) return EFI_SUCCESS; /* get the LoadFile2 protocol that we allocated earlier */ err = BS->HandleProtocol(initrd_handle, MAKE_GUID_PTR(EFI_LOAD_FILE2_PROTOCOL), (void **) &loader); if (err != EFI_SUCCESS) return err; /* uninstall all protocols thus destroying the handle */ err = BS->UninstallMultipleProtocolInterfaces( initrd_handle, MAKE_GUID_PTR(EFI_DEVICE_PATH_PROTOCOL), &efi_initrd_device_path, MAKE_GUID_PTR(EFI_LOAD_FILE2_PROTOCOL), loader, NULL); if (err != EFI_SUCCESS) return err; initrd_handle = NULL; free(loader); return EFI_SUCCESS; }
4,667
33.072993
107
c
null
systemd-main/src/boot/efi/linux.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * Generic Linux boot protocol using the EFI/PE entry point of the kernel. Passes * initrd with the LINUX_INITRD_MEDIA_GUID DevicePath and cmdline with * EFI LoadedImageProtocol. * * This method works for Linux 5.8 and newer on ARM/Aarch64, x86/x68_64 and RISC-V. */ #include "initrd.h" #include "linux.h" #include "pe.h" #include "proto/device-path.h" #include "proto/loaded-image.h" #include "secure-boot.h" #include "util.h" #define STUB_PAYLOAD_GUID \ { 0x55c5d1f8, 0x04cd, 0x46b5, { 0x8a, 0x20, 0xe5, 0x6c, 0xbb, 0x30, 0x52, 0xd0 } } typedef struct { const void *addr; size_t len; const EFI_DEVICE_PATH *device_path; } ValidationContext; static bool validate_payload( const void *ctx, const EFI_DEVICE_PATH *device_path, const void *file_buffer, size_t file_size) { const ValidationContext *payload = ASSERT_PTR(ctx); if (device_path != payload->device_path) return false; /* Security arch (1) protocol does not provide a file buffer. Instead we are supposed to fetch the payload * ourselves, which is not needed as we already have everything in memory and the device paths match. */ if (file_buffer && (file_buffer != payload->addr || file_size != payload->len)) return false; return true; } static EFI_STATUS load_image(EFI_HANDLE parent, const void *source, size_t len, EFI_HANDLE *ret_image) { assert(parent); assert(source); assert(ret_image); /* We could pass a NULL device path, but it's nicer to provide something and it allows us to identify * the loaded image from within the security hooks. */ struct { VENDOR_DEVICE_PATH payload; EFI_DEVICE_PATH end; } _packed_ payload_device_path = { .payload = { .Header = { .Type = MEDIA_DEVICE_PATH, .SubType = MEDIA_VENDOR_DP, .Length = sizeof(payload_device_path.payload), }, .Guid = STUB_PAYLOAD_GUID, }, .end = { .Type = END_DEVICE_PATH_TYPE, .SubType = END_ENTIRE_DEVICE_PATH_SUBTYPE, .Length = sizeof(payload_device_path.end), }, }; /* We want to support unsigned kernel images as payload, which is safe to do under secure boot * because it is embedded in this stub loader (and since it is already running it must be trusted). */ install_security_override( validate_payload, &(ValidationContext) { .addr = source, .len = len, .device_path = &payload_device_path.payload.Header, }); EFI_STATUS ret = BS->LoadImage( /*BootPolicy=*/false, parent, &payload_device_path.payload.Header, (void *) source, len, ret_image); uninstall_security_override(); return ret; } EFI_STATUS linux_exec( EFI_HANDLE parent, const char16_t *cmdline, const void *linux_buffer, size_t linux_length, const void *initrd_buffer, size_t initrd_length) { uint32_t compat_address; EFI_STATUS err; assert(parent); assert(linux_buffer && linux_length > 0); assert(initrd_buffer || initrd_length == 0); err = pe_kernel_info(linux_buffer, &compat_address); #if defined(__i386__) || defined(__x86_64__) if (err == EFI_UNSUPPORTED) /* Kernel is too old to support LINUX_INITRD_MEDIA_GUID, try the deprecated EFI handover * protocol. */ return linux_exec_efi_handover( parent, cmdline, linux_buffer, linux_length, initrd_buffer, initrd_length); #endif if (err != EFI_SUCCESS) return log_error_status(err, "Bad kernel image: %m"); _cleanup_(unload_imagep) EFI_HANDLE kernel_image = NULL; err = load_image(parent, linux_buffer, linux_length, &kernel_image); if (err != EFI_SUCCESS) return log_error_status(err, "Error loading kernel image: %m"); EFI_LOADED_IMAGE_PROTOCOL *loaded_image; err = BS->HandleProtocol( kernel_image, MAKE_GUID_PTR(EFI_LOADED_IMAGE_PROTOCOL), (void **) &loaded_image); if (err != EFI_SUCCESS) return log_error_status(err, "Error getting kernel loaded image protocol: %m"); if (cmdline) { loaded_image->LoadOptions = (void *) cmdline; loaded_image->LoadOptionsSize = strsize16(loaded_image->LoadOptions); } _cleanup_(cleanup_initrd) EFI_HANDLE initrd_handle = NULL; err = initrd_register(initrd_buffer, initrd_length, &initrd_handle); if (err != EFI_SUCCESS) return log_error_status(err, "Error registering initrd: %m"); log_wait(); err = BS->StartImage(kernel_image, NULL, NULL); /* Try calling the kernel compat entry point if one exists. */ if (err == EFI_UNSUPPORTED && compat_address > 0) { EFI_IMAGE_ENTRY_POINT compat_entry = (EFI_IMAGE_ENTRY_POINT) ((uint8_t *) loaded_image->ImageBase + compat_address); err = compat_entry(kernel_image, ST); } return log_error_status(err, "Error starting kernel image: %m"); }
6,061
37.611465
114
c
null
systemd-main/src/boot/efi/linux.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "efi.h" EFI_STATUS linux_exec( EFI_HANDLE parent, const char16_t *cmdline, const void *linux_buffer, size_t linux_length, const void *initrd_buffer, size_t initrd_length); EFI_STATUS linux_exec_efi_handover( EFI_HANDLE parent, const char16_t *cmdline, const void *linux_buffer, size_t linux_length, const void *initrd_buffer, size_t initrd_length);
614
29.75
48
h
null
systemd-main/src/boot/efi/linux_x86.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* * x86 specific code to for EFI handover boot protocol * Linux kernels version 5.8 and newer support providing the initrd by * LINUX_INITRD_MEDIA_GUID DevicePath. In order to support older kernels too, * this x86 specific linux_exec function passes the initrd by setting the * corresponding fields in the setup_header struct. * * see https://docs.kernel.org/x86/boot.html */ #include "initrd.h" #include "linux.h" #include "macro-fundamental.h" #include "util.h" #define KERNEL_SECTOR_SIZE 512u #define BOOT_FLAG_MAGIC 0xAA55u #define SETUP_MAGIC 0x53726448u /* "HdrS" */ #define SETUP_VERSION_2_11 0x20bu #define SETUP_VERSION_2_12 0x20cu #define SETUP_VERSION_2_15 0x20fu #define CMDLINE_PTR_MAX 0xA0000u enum { XLF_KERNEL_64 = 1 << 0, XLF_CAN_BE_LOADED_ABOVE_4G = 1 << 1, XLF_EFI_HANDOVER_32 = 1 << 2, XLF_EFI_HANDOVER_64 = 1 << 3, #ifdef __x86_64__ XLF_EFI_HANDOVER = XLF_EFI_HANDOVER_64, #else XLF_EFI_HANDOVER = XLF_EFI_HANDOVER_32, #endif }; typedef struct { uint8_t setup_sects; uint16_t root_flags; uint32_t syssize; uint16_t ram_size; uint16_t vid_mode; uint16_t root_dev; uint16_t boot_flag; uint8_t jump; /* We split the 2-byte jump field from the spec in two for convenience. */ uint8_t setup_size; uint32_t header; uint16_t version; uint32_t realmode_swtch; uint16_t start_sys_seg; uint16_t kernel_version; uint8_t type_of_loader; uint8_t loadflags; uint16_t setup_move_size; uint32_t code32_start; uint32_t ramdisk_image; uint32_t ramdisk_size; uint32_t bootsect_kludge; uint16_t heap_end_ptr; uint8_t ext_loader_ver; uint8_t ext_loader_type; uint32_t cmd_line_ptr; uint32_t initrd_addr_max; uint32_t kernel_alignment; uint8_t relocatable_kernel; uint8_t min_alignment; uint16_t xloadflags; uint32_t cmdline_size; uint32_t hardware_subarch; uint64_t hardware_subarch_data; uint32_t payload_offset; uint32_t payload_length; uint64_t setup_data; uint64_t pref_address; uint32_t init_size; uint32_t handover_offset; } _packed_ SetupHeader; /* We really only care about a few fields, but we still have to provide a full page otherwise. */ typedef struct { uint8_t pad[192]; uint32_t ext_ramdisk_image; uint32_t ext_ramdisk_size; uint32_t ext_cmd_line_ptr; uint8_t pad2[293]; SetupHeader hdr; uint8_t pad3[3480]; } _packed_ BootParams; assert_cc(offsetof(BootParams, ext_ramdisk_image) == 0x0C0); assert_cc(sizeof(BootParams) == 4096); #ifdef __i386__ # define __regparm0__ __attribute__((regparm(0))) #else # define __regparm0__ #endif typedef void (*handover_f)(void *parent, EFI_SYSTEM_TABLE *table, BootParams *params) __regparm0__ __attribute__((sysv_abi)); static void linux_efi_handover(EFI_HANDLE parent, uintptr_t kernel, BootParams *params) { assert(params); kernel += (params->hdr.setup_sects + 1) * KERNEL_SECTOR_SIZE; /* 32-bit entry address. */ /* Old kernels needs this set, while newer ones seem to ignore this. */ params->hdr.code32_start = kernel; #ifdef __x86_64__ kernel += KERNEL_SECTOR_SIZE; /* 64-bit entry address. */ #endif kernel += params->hdr.handover_offset; /* 32/64-bit EFI handover address. */ /* Note in EFI mixed mode this now points to the correct 32-bit handover entry point, allowing a 64-bit * kernel to be booted from a 32-bit sd-stub. */ handover_f handover = (handover_f) kernel; handover(parent, ST, params); } EFI_STATUS linux_exec_efi_handover( EFI_HANDLE parent, const char16_t *cmdline, const void *linux_buffer, size_t linux_length, const void *initrd_buffer, size_t initrd_length) { assert(parent); assert(linux_buffer); assert(initrd_buffer || initrd_length == 0); if (linux_length < sizeof(BootParams)) return EFI_LOAD_ERROR; const BootParams *image_params = (const BootParams *) linux_buffer; if (image_params->hdr.header != SETUP_MAGIC || image_params->hdr.boot_flag != BOOT_FLAG_MAGIC) return log_error_status(EFI_UNSUPPORTED, "Unsupported kernel image."); if (image_params->hdr.version < SETUP_VERSION_2_11) return log_error_status(EFI_UNSUPPORTED, "Kernel too old."); if (!image_params->hdr.relocatable_kernel) return log_error_status(EFI_UNSUPPORTED, "Kernel is not relocatable."); /* The xloadflags were added in version 2.12+ of the boot protocol but the handover support predates * that, so we cannot safety-check this for 2.11. */ if (image_params->hdr.version >= SETUP_VERSION_2_12 && !FLAGS_SET(image_params->hdr.xloadflags, XLF_EFI_HANDOVER)) return log_error_status(EFI_UNSUPPORTED, "Kernel does not support EFI handover protocol."); bool can_4g = image_params->hdr.version >= SETUP_VERSION_2_12 && FLAGS_SET(image_params->hdr.xloadflags, XLF_CAN_BE_LOADED_ABOVE_4G); /* There is no way to pass the high bits of code32_start. Newer kernels seems to handle this * just fine, but older kernels will fail even if they otherwise have above 4G boot support. */ _cleanup_pages_ Pages linux_relocated = {}; if (POINTER_TO_PHYSICAL_ADDRESS(linux_buffer) + linux_length > UINT32_MAX) { linux_relocated = xmalloc_pages( AllocateMaxAddress, EfiLoaderCode, EFI_SIZE_TO_PAGES(linux_length), UINT32_MAX); linux_buffer = memcpy( PHYSICAL_ADDRESS_TO_POINTER(linux_relocated.addr), linux_buffer, linux_length); } _cleanup_pages_ Pages initrd_relocated = {}; if (!can_4g && POINTER_TO_PHYSICAL_ADDRESS(initrd_buffer) + initrd_length > UINT32_MAX) { initrd_relocated = xmalloc_pages( AllocateMaxAddress, EfiLoaderData, EFI_SIZE_TO_PAGES(initrd_length), UINT32_MAX); initrd_buffer = memcpy( PHYSICAL_ADDRESS_TO_POINTER(initrd_relocated.addr), initrd_buffer, initrd_length); } _cleanup_pages_ Pages boot_params_page = xmalloc_pages( can_4g ? AllocateAnyPages : AllocateMaxAddress, EfiLoaderData, EFI_SIZE_TO_PAGES(sizeof(BootParams)), UINT32_MAX /* Below the 4G boundary */); BootParams *boot_params = PHYSICAL_ADDRESS_TO_POINTER(boot_params_page.addr); *boot_params = (BootParams){}; /* Setup size is determined by offset 0x0202 + byte value at offset 0x0201, which is the same as * offset of the header field and the target from the jump field (which we split for this reason). */ memcpy(&boot_params->hdr, &image_params->hdr, offsetof(SetupHeader, header) + image_params->hdr.setup_size); boot_params->hdr.type_of_loader = 0xff; /* Spec says: For backwards compatibility, if the setup_sects field contains 0, the real value is 4. */ if (boot_params->hdr.setup_sects == 0) boot_params->hdr.setup_sects = 4; _cleanup_pages_ Pages cmdline_pages = {}; if (cmdline) { size_t len = MIN(strlen16(cmdline), image_params->hdr.cmdline_size); cmdline_pages = xmalloc_pages( can_4g ? AllocateAnyPages : AllocateMaxAddress, EfiLoaderData, EFI_SIZE_TO_PAGES(len + 1), CMDLINE_PTR_MAX); /* Convert cmdline to ASCII. */ char *cmdline8 = PHYSICAL_ADDRESS_TO_POINTER(cmdline_pages.addr); for (size_t i = 0; i < len; i++) cmdline8[i] = cmdline[i] <= 0x7E ? cmdline[i] : ' '; cmdline8[len] = '\0'; boot_params->hdr.cmd_line_ptr = (uint32_t) cmdline_pages.addr; boot_params->ext_cmd_line_ptr = cmdline_pages.addr >> 32; assert(can_4g || cmdline_pages.addr <= CMDLINE_PTR_MAX); } boot_params->hdr.ramdisk_image = (uintptr_t) initrd_buffer; boot_params->ext_ramdisk_image = POINTER_TO_PHYSICAL_ADDRESS(initrd_buffer) >> 32; boot_params->hdr.ramdisk_size = initrd_length; boot_params->ext_ramdisk_size = ((uint64_t) initrd_length) >> 32; log_wait(); linux_efi_handover(parent, (uintptr_t) linux_buffer, boot_params); return EFI_LOAD_ERROR; }
9,171
39.764444
113
c
null
systemd-main/src/boot/efi/log.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "log.h" #include "proto/rng.h" #include "proto/simple-text-io.h" #include "util.h" static unsigned log_count = 0; void freeze(void) { for (;;) BS->Stall(60 * 1000 * 1000); } _noreturn_ static void panic(const char16_t *message) { if (ST->ConOut->Mode->CursorColumn > 0) ST->ConOut->OutputString(ST->ConOut, (char16_t *) u"\r\n"); ST->ConOut->SetAttribute(ST->ConOut, EFI_TEXT_ATTR(EFI_LIGHTRED, EFI_BLACK)); ST->ConOut->OutputString(ST->ConOut, (char16_t *) message); freeze(); } void efi_assert(const char *expr, const char *file, unsigned line, const char *function) { static bool asserting = false; /* Let's be paranoid. */ if (asserting) panic(u"systemd-boot: Nested assertion failure, halting."); asserting = true; log_error("systemd-boot: Assertion '%s' failed at %s:%u@%s, halting.", expr, file, line, function); freeze(); } EFI_STATUS log_internal(EFI_STATUS status, const char *format, ...) { assert(format); int32_t attr = ST->ConOut->Mode->Attribute; if (ST->ConOut->Mode->CursorColumn > 0) ST->ConOut->OutputString(ST->ConOut, (char16_t *) u"\r\n"); ST->ConOut->SetAttribute(ST->ConOut, EFI_TEXT_ATTR(EFI_LIGHTRED, EFI_BLACK)); va_list ap; va_start(ap, format); vprintf_status(status, format, ap); va_end(ap); ST->ConOut->OutputString(ST->ConOut, (char16_t *) u"\r\n"); ST->ConOut->SetAttribute(ST->ConOut, attr); log_count++; return status; } #ifdef EFI_DEBUG void log_hexdump(const char16_t *prefix, const void *data, size_t size) { /* Debugging helper — please keep this around, even if not used */ _cleanup_free_ char16_t *hex = hexdump(data, size); log_internal(EFI_SUCCESS, "%ls[%zu]: %ls", prefix, size, hex); } #endif void log_wait(void) { if (log_count == 0) return; BS->Stall(MIN(4u, log_count) * 2500 * 1000); log_count = 0; } _used_ intptr_t __stack_chk_guard = (intptr_t) 0x70f6967de78acae3; /* We can only set a random stack canary if this function attribute is available, * otherwise this may create a stack check fail. */ #if STACK_PROTECTOR_RANDOM void __stack_chk_guard_init(void) { EFI_RNG_PROTOCOL *rng; if (BS->LocateProtocol(MAKE_GUID_PTR(EFI_RNG_PROTOCOL), NULL, (void **) &rng) == EFI_SUCCESS) (void) rng->GetRNG(rng, NULL, sizeof(__stack_chk_guard), (void *) &__stack_chk_guard); } #endif _used_ _noreturn_ void __stack_chk_fail(void); _used_ _noreturn_ void __stack_chk_fail_local(void); void __stack_chk_fail(void) { panic(u"systemd-boot: Stack check failed, halting."); } void __stack_chk_fail_local(void) { __stack_chk_fail(); } /* Called by libgcc for some fatal errors like integer overflow with -ftrapv. */ _used_ _noreturn_ void abort(void); void abort(void) { panic(u"systemd-boot: Unknown error, halting."); } #if defined(__ARM_EABI__) /* These override the (weak) div0 handlers from libgcc as they would otherwise call raise() instead. */ _used_ _noreturn_ int __aeabi_idiv0(int return_value); _used_ _noreturn_ long long __aeabi_ldiv0(long long return_value); int __aeabi_idiv0(int return_value) { panic(u"systemd-boot: Division by zero, halting."); } long long __aeabi_ldiv0(long long return_value) { panic(u"systemd-boot: Division by zero, halting."); } #endif
3,579
30.681416
107
c
null
systemd-main/src/boot/efi/log.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "efi-string.h" #if defined __has_attribute # if __has_attribute(no_stack_protector) # define HAVE_NO_STACK_PROTECTOR_ATTRIBUTE # endif #endif #if defined(HAVE_NO_STACK_PROTECTOR_ATTRIBUTE) && \ (defined(__SSP__) || defined(__SSP_ALL__) || \ defined(__SSP_STRONG__) || defined(__SSP_EXPLICIT__)) # define STACK_PROTECTOR_RANDOM 1 __attribute__((no_stack_protector, noinline)) void __stack_chk_guard_init(void); #else # define STACK_PROTECTOR_RANDOM 0 # define __stack_chk_guard_init() #endif _noreturn_ void freeze(void); void log_wait(void); _gnu_printf_(2, 3) EFI_STATUS log_internal(EFI_STATUS status, const char *format, ...); #define log_error_status(status, ...) log_internal(status, __VA_ARGS__) #define log_error(...) log_internal(EFI_INVALID_PARAMETER, __VA_ARGS__) #define log_oom() log_internal(EFI_OUT_OF_RESOURCES, "Out of memory.") #define log_trace() log_internal(EFI_SUCCESS, "%s:%i@%s", __FILE__, __LINE__, __func__) #ifdef EFI_DEBUG void log_hexdump(const char16_t *prefix, const void *data, size_t size); #endif
1,122
33.030303
87
h
null
systemd-main/src/boot/efi/part-discovery.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "device-path-util.h" #include "part-discovery.h" #include "proto/block-io.h" #include "proto/device-path.h" #include "util.h" typedef struct { EFI_GUID PartitionTypeGUID; EFI_GUID UniquePartitionGUID; EFI_LBA StartingLBA; EFI_LBA EndingLBA; uint64_t Attributes; char16_t PartitionName[36]; } EFI_PARTITION_ENTRY; typedef struct { EFI_TABLE_HEADER Header; EFI_LBA MyLBA; EFI_LBA AlternateLBA; EFI_LBA FirstUsableLBA; EFI_LBA LastUsableLBA; EFI_GUID DiskGUID; EFI_LBA PartitionEntryLBA; uint32_t NumberOfPartitionEntries; uint32_t SizeOfPartitionEntry; uint32_t PartitionEntryArrayCRC32; uint8_t _pad[420]; } _packed_ GptHeader; assert_cc(sizeof(GptHeader) == 512); static bool verify_gpt(/*const*/ GptHeader *h, EFI_LBA lba_expected) { uint32_t crc32, crc32_saved; EFI_STATUS err; assert(h); /* Some superficial validation of the GPT header */ if (memcmp(&h->Header.Signature, "EFI PART", sizeof(h->Header.Signature)) != 0) return false; if (h->Header.HeaderSize < 92 || h->Header.HeaderSize > 512) return false; if (h->Header.Revision != 0x00010000U) return false; /* Calculate CRC check */ crc32_saved = h->Header.CRC32; h->Header.CRC32 = 0; err = BS->CalculateCrc32(h, h->Header.HeaderSize, &crc32); h->Header.CRC32 = crc32_saved; if (err != EFI_SUCCESS || crc32 != crc32_saved) return false; if (h->MyLBA != lba_expected) return false; if ((h->SizeOfPartitionEntry % sizeof(EFI_PARTITION_ENTRY)) != 0) return false; if (h->NumberOfPartitionEntries <= 0 || h->NumberOfPartitionEntries > 1024) return false; /* overflow check */ if (h->SizeOfPartitionEntry > SIZE_MAX / h->NumberOfPartitionEntries) return false; return true; } static EFI_STATUS try_gpt( const EFI_GUID *type, EFI_BLOCK_IO_PROTOCOL *block_io, EFI_LBA lba, EFI_LBA *ret_backup_lba, /* May be changed even on error! */ HARDDRIVE_DEVICE_PATH *ret_hd) { _cleanup_free_ EFI_PARTITION_ENTRY *entries = NULL; GptHeader gpt; EFI_STATUS err; uint32_t crc32; size_t size; assert(block_io); assert(ret_hd); /* Read the GPT header */ err = block_io->ReadBlocks( block_io, block_io->Media->MediaId, lba, sizeof(gpt), &gpt); if (err != EFI_SUCCESS) return err; /* Indicate the location of backup LBA even if the rest of the header is corrupt. */ if (ret_backup_lba) *ret_backup_lba = gpt.AlternateLBA; if (!verify_gpt(&gpt, lba)) return EFI_NOT_FOUND; /* Now load the GPT entry table */ size = ALIGN_TO((size_t) gpt.SizeOfPartitionEntry * (size_t) gpt.NumberOfPartitionEntries, 512); entries = xmalloc(size); err = block_io->ReadBlocks( block_io, block_io->Media->MediaId, gpt.PartitionEntryLBA, size, entries); if (err != EFI_SUCCESS) return err; /* Calculate CRC of entries array, too */ err = BS->CalculateCrc32(entries, size, &crc32); if (err != EFI_SUCCESS || crc32 != gpt.PartitionEntryArrayCRC32) return EFI_CRC_ERROR; /* Now we can finally look for xbootloader partitions. */ for (size_t i = 0; i < gpt.NumberOfPartitionEntries; i++) { EFI_PARTITION_ENTRY *entry = (EFI_PARTITION_ENTRY *) ((uint8_t *) entries + gpt.SizeOfPartitionEntry * i); if (!efi_guid_equal(&entry->PartitionTypeGUID, type)) continue; if (entry->EndingLBA < entry->StartingLBA) /* Bogus? */ continue; *ret_hd = (HARDDRIVE_DEVICE_PATH) { .Header = { .Type = MEDIA_DEVICE_PATH, .SubType = MEDIA_HARDDRIVE_DP, .Length = sizeof(HARDDRIVE_DEVICE_PATH), }, .PartitionNumber = i + 1, .PartitionStart = entry->StartingLBA, .PartitionSize = entry->EndingLBA - entry->StartingLBA + 1, .MBRType = MBR_TYPE_EFI_PARTITION_TABLE_HEADER, .SignatureType = SIGNATURE_TYPE_GUID, }; memcpy(ret_hd->Signature, &entry->UniquePartitionGUID, sizeof(ret_hd->Signature)); return EFI_SUCCESS; } /* This GPT was fully valid, but we didn't find what we are looking for. This * means there's no reason to check the second copy of the GPT header */ return EFI_NOT_FOUND; } static EFI_STATUS find_device(const EFI_GUID *type, EFI_HANDLE *device, EFI_DEVICE_PATH **ret_device_path) { EFI_STATUS err; assert(device); assert(ret_device_path); EFI_DEVICE_PATH *partition_path; err = BS->HandleProtocol(device, MAKE_GUID_PTR(EFI_DEVICE_PATH_PROTOCOL), (void **) &partition_path); if (err != EFI_SUCCESS) return err; /* Find the (last) partition node itself. */ EFI_DEVICE_PATH *part_node = NULL; for (EFI_DEVICE_PATH *node = partition_path; !device_path_is_end(node); node = device_path_next_node(node)) { if (node->Type != MEDIA_DEVICE_PATH || node->SubType != MEDIA_HARDDRIVE_DP) continue; part_node = node; } if (!part_node) return EFI_NOT_FOUND; /* Chop off the partition part, leaving us with the full path to the disk itself. */ _cleanup_free_ EFI_DEVICE_PATH *disk_path = NULL; EFI_DEVICE_PATH *p = disk_path = device_path_replace_node(partition_path, part_node, NULL); EFI_HANDLE disk_handle; EFI_BLOCK_IO_PROTOCOL *block_io; err = BS->LocateDevicePath(MAKE_GUID_PTR(EFI_BLOCK_IO_PROTOCOL), &p, &disk_handle); if (err != EFI_SUCCESS) return err; /* The drivers for other partitions on this drive may not be initialized on fastboot firmware, so we * have to ask the firmware to do just that. */ (void) BS->ConnectController(disk_handle, NULL, NULL, true); err = BS->HandleProtocol(disk_handle, MAKE_GUID_PTR(EFI_BLOCK_IO_PROTOCOL), (void **) &block_io); if (err != EFI_SUCCESS) return err; /* Filter out some block devices early. (We only care about block devices that aren't * partitions themselves — we look for GPT partition tables to parse after all —, and only * those which contain a medium and have at least 2 blocks.) */ if (block_io->Media->LogicalPartition || !block_io->Media->MediaPresent || block_io->Media->LastBlock <= 1) return EFI_NOT_FOUND; /* Try several copies of the GPT header, in case one is corrupted */ EFI_LBA backup_lba = 0; for (size_t nr = 0; nr < 3; nr++) { EFI_LBA lba; /* Read the first copy at LBA 1 and then try the backup GPT header pointed * to by the first header if that one was corrupted. As a last resort, * try the very last LBA of this block device. */ if (nr == 0) lba = 1; else if (nr == 1 && backup_lba != 0) lba = backup_lba; else if (nr == 2 && backup_lba != block_io->Media->LastBlock) lba = block_io->Media->LastBlock; else continue; HARDDRIVE_DEVICE_PATH hd; err = try_gpt(type, block_io, lba, nr == 0 ? &backup_lba : NULL, /* Only get backup LBA location from first GPT header. */ &hd); if (err != EFI_SUCCESS) { /* GPT was valid but no XBOOT loader partition found. */ if (err == EFI_NOT_FOUND) break; /* Bad GPT, try next one. */ continue; } /* Patch in the data we found */ *ret_device_path = device_path_replace_node(partition_path, part_node, (EFI_DEVICE_PATH *) &hd); return EFI_SUCCESS; } /* No xbootloader partition found */ return EFI_NOT_FOUND; } EFI_STATUS partition_open(const EFI_GUID *type, EFI_HANDLE *device, EFI_HANDLE *ret_device, EFI_FILE **ret_root_dir) { _cleanup_free_ EFI_DEVICE_PATH *partition_path = NULL; EFI_HANDLE new_device; EFI_FILE *root_dir; EFI_STATUS err; assert(type); assert(device); assert(ret_root_dir); err = find_device(type, device, &partition_path); if (err != EFI_SUCCESS) return err; EFI_DEVICE_PATH *dp = partition_path; err = BS->LocateDevicePath(MAKE_GUID_PTR(EFI_BLOCK_IO_PROTOCOL), &dp, &new_device); if (err != EFI_SUCCESS) return err; err = open_volume(new_device, &root_dir); if (err != EFI_SUCCESS) return err; if (ret_device) *ret_device = new_device; *ret_root_dir = root_dir; return EFI_SUCCESS; } char16_t *disk_get_part_uuid(EFI_HANDLE *handle) { EFI_STATUS err; EFI_DEVICE_PATH *dp; /* export the device path this image is started from */ if (!handle) return NULL; err = BS->HandleProtocol(handle, MAKE_GUID_PTR(EFI_DEVICE_PATH_PROTOCOL), (void **) &dp); if (err != EFI_SUCCESS) return NULL; for (; !device_path_is_end(dp); dp = device_path_next_node(dp)) { if (dp->Type != MEDIA_DEVICE_PATH || dp->SubType != MEDIA_HARDDRIVE_DP) continue; HARDDRIVE_DEVICE_PATH *hd = (HARDDRIVE_DEVICE_PATH *) dp; if (hd->SignatureType != SIGNATURE_TYPE_GUID) continue; return xasprintf(GUID_FORMAT_STR, GUID_FORMAT_VAL(hd->SignatureGuid)); } return NULL; }
10,911
35.494983
112
c
null
systemd-main/src/boot/efi/pe.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "pe.h" #include "util.h" #define DOS_FILE_MAGIC "MZ" #define PE_FILE_MAGIC "PE\0\0" #define MAX_SECTIONS 96 #if defined(__i386__) # define TARGET_MACHINE_TYPE 0x014CU # define TARGET_MACHINE_TYPE_COMPATIBILITY 0x8664U #elif defined(__x86_64__) # define TARGET_MACHINE_TYPE 0x8664U #elif defined(__aarch64__) # define TARGET_MACHINE_TYPE 0xAA64U #elif defined(__arm__) # define TARGET_MACHINE_TYPE 0x01C2U #elif defined(__riscv) && __riscv_xlen == 32 # define TARGET_MACHINE_TYPE 0x5032U #elif defined(__riscv) && __riscv_xlen == 64 # define TARGET_MACHINE_TYPE 0x5064U #elif defined(__loongarch__) && __loongarch_grlen == 32 # define TARGET_MACHINE_TYPE 0x6232U #elif defined(__loongarch__) && __loongarch_grlen == 64 # define TARGET_MACHINE_TYPE 0x6264U #else # error Unknown EFI arch #endif #ifndef TARGET_MACHINE_TYPE_COMPATIBILITY # define TARGET_MACHINE_TYPE_COMPATIBILITY 0 #endif typedef struct DosFileHeader { uint8_t Magic[2]; uint16_t LastSize; uint16_t nBlocks; uint16_t nReloc; uint16_t HdrSize; uint16_t MinAlloc; uint16_t MaxAlloc; uint16_t ss; uint16_t sp; uint16_t Checksum; uint16_t ip; uint16_t cs; uint16_t RelocPos; uint16_t nOverlay; uint16_t reserved[4]; uint16_t OEMId; uint16_t OEMInfo; uint16_t reserved2[10]; uint32_t ExeHeader; } _packed_ DosFileHeader; typedef struct CoffFileHeader { uint16_t Machine; uint16_t NumberOfSections; uint32_t TimeDateStamp; uint32_t PointerToSymbolTable; uint32_t NumberOfSymbols; uint16_t SizeOfOptionalHeader; uint16_t Characteristics; } _packed_ CoffFileHeader; #define OPTHDR32_MAGIC 0x10B /* PE32 OptionalHeader */ #define OPTHDR64_MAGIC 0x20B /* PE32+ OptionalHeader */ typedef struct PeOptionalHeader { uint16_t Magic; uint8_t LinkerMajor; uint8_t LinkerMinor; uint32_t SizeOfCode; uint32_t SizeOfInitializedData; uint32_t SizeOfUninitializeData; uint32_t AddressOfEntryPoint; uint32_t BaseOfCode; union { struct { /* PE32 */ uint32_t BaseOfData; uint32_t ImageBase32; }; uint64_t ImageBase64; /* PE32+ */ }; uint32_t SectionAlignment; uint32_t FileAlignment; uint16_t MajorOperatingSystemVersion; uint16_t MinorOperatingSystemVersion; uint16_t MajorImageVersion; uint16_t MinorImageVersion; uint16_t MajorSubsystemVersion; uint16_t MinorSubsystemVersion; uint32_t Win32VersionValue; uint32_t SizeOfImage; uint32_t SizeOfHeaders; uint32_t CheckSum; uint16_t Subsystem; uint16_t DllCharacteristics; /* fields with different sizes for 32/64 omitted */ } _packed_ PeOptionalHeader; typedef struct PeFileHeader { uint8_t Magic[4]; CoffFileHeader FileHeader; PeOptionalHeader OptionalHeader; } _packed_ PeFileHeader; typedef struct PeSectionHeader { uint8_t Name[8]; uint32_t VirtualSize; uint32_t VirtualAddress; uint32_t SizeOfRawData; uint32_t PointerToRawData; uint32_t PointerToRelocations; uint32_t PointerToLinenumbers; uint16_t NumberOfRelocations; uint16_t NumberOfLinenumbers; uint32_t Characteristics; } _packed_ PeSectionHeader; static inline bool verify_dos(const DosFileHeader *dos) { assert(dos); return memcmp(dos->Magic, DOS_FILE_MAGIC, STRLEN(DOS_FILE_MAGIC)) == 0; } static inline bool verify_pe(const PeFileHeader *pe, bool allow_compatibility) { assert(pe); return memcmp(pe->Magic, PE_FILE_MAGIC, STRLEN(PE_FILE_MAGIC)) == 0 && (pe->FileHeader.Machine == TARGET_MACHINE_TYPE || (allow_compatibility && pe->FileHeader.Machine == TARGET_MACHINE_TYPE_COMPATIBILITY)) && pe->FileHeader.NumberOfSections > 0 && pe->FileHeader.NumberOfSections <= MAX_SECTIONS && IN_SET(pe->OptionalHeader.Magic, OPTHDR32_MAGIC, OPTHDR64_MAGIC); } static inline size_t section_table_offset(const DosFileHeader *dos, const PeFileHeader *pe) { assert(dos); assert(pe); return dos->ExeHeader + offsetof(PeFileHeader, OptionalHeader) + pe->FileHeader.SizeOfOptionalHeader; } static void locate_sections( const PeSectionHeader section_table[], size_t n_table, const char * const sections[], size_t *offsets, size_t *sizes, bool in_memory) { assert(section_table); assert(sections); assert(offsets); assert(sizes); for (size_t i = 0; i < n_table; i++) { const PeSectionHeader *sect = section_table + i; for (size_t j = 0; sections[j]; j++) { if (memcmp(sect->Name, sections[j], strlen8(sections[j])) != 0) continue; offsets[j] = in_memory ? sect->VirtualAddress : sect->PointerToRawData; sizes[j] = sect->VirtualSize; } } } static uint32_t get_compatibility_entry_address(const DosFileHeader *dos, const PeFileHeader *pe) { size_t addr = 0, size = 0; static const char *sections[] = { ".compat", NULL }; /* The kernel may provide alternative PE entry points for different PE architectures. This allows * booting a 64-bit kernel on 32-bit EFI that is otherwise running on a 64-bit CPU. The locations of any * such compat entry points are located in a special PE section. */ locate_sections((const PeSectionHeader *) ((const uint8_t *) dos + section_table_offset(dos, pe)), pe->FileHeader.NumberOfSections, sections, &addr, &size, /*in_memory=*/true); if (size == 0) return 0; typedef struct { uint8_t type; uint8_t size; uint16_t machine_type; uint32_t entry_point; } _packed_ LinuxPeCompat1; while (size >= sizeof(LinuxPeCompat1) && addr % alignof(LinuxPeCompat1) == 0) { LinuxPeCompat1 *compat = (LinuxPeCompat1 *) ((uint8_t *) dos + addr); if (compat->type == 0 || compat->size == 0 || compat->size > size) break; if (compat->type == 1 && compat->size >= sizeof(LinuxPeCompat1) && compat->machine_type == TARGET_MACHINE_TYPE) return compat->entry_point; addr += compat->size; size -= compat->size; } return 0; } EFI_STATUS pe_kernel_info(const void *base, uint32_t *ret_compat_address) { assert(base); assert(ret_compat_address); const DosFileHeader *dos = (const DosFileHeader *) base; if (!verify_dos(dos)) return EFI_LOAD_ERROR; const PeFileHeader *pe = (const PeFileHeader *) ((const uint8_t *) base + dos->ExeHeader); if (!verify_pe(pe, /* allow_compatibility= */ true)) return EFI_LOAD_ERROR; /* Support for LINUX_INITRD_MEDIA_GUID was added in kernel stub 1.0. */ if (pe->OptionalHeader.MajorImageVersion < 1) return EFI_UNSUPPORTED; if (pe->FileHeader.Machine == TARGET_MACHINE_TYPE) { *ret_compat_address = 0; return EFI_SUCCESS; } uint32_t compat_address = get_compatibility_entry_address(dos, pe); if (compat_address == 0) /* Image type not supported and no compat entry found. */ return EFI_UNSUPPORTED; *ret_compat_address = compat_address; return EFI_SUCCESS; } EFI_STATUS pe_memory_locate_sections(const void *base, const char * const sections[], size_t *addrs, size_t *sizes) { const DosFileHeader *dos; const PeFileHeader *pe; size_t offset; assert(base); assert(sections); assert(addrs); assert(sizes); dos = (const DosFileHeader *) base; if (!verify_dos(dos)) return EFI_LOAD_ERROR; pe = (const PeFileHeader *) ((uint8_t *) base + dos->ExeHeader); if (!verify_pe(pe, /* allow_compatibility= */ false)) return EFI_LOAD_ERROR; offset = section_table_offset(dos, pe); locate_sections((PeSectionHeader *) ((uint8_t *) base + offset), pe->FileHeader.NumberOfSections, sections, addrs, sizes, /*in_memory=*/true); return EFI_SUCCESS; } EFI_STATUS pe_file_locate_sections( EFI_FILE *dir, const char16_t *path, const char * const sections[], size_t *offsets, size_t *sizes) { _cleanup_free_ PeSectionHeader *section_table = NULL; _cleanup_(file_closep) EFI_FILE *handle = NULL; DosFileHeader dos; PeFileHeader pe; size_t len, section_table_len; EFI_STATUS err; assert(dir); assert(path); assert(sections); assert(offsets); assert(sizes); err = dir->Open(dir, &handle, (char16_t *) path, EFI_FILE_MODE_READ, 0ULL); if (err != EFI_SUCCESS) return err; len = sizeof(dos); err = handle->Read(handle, &len, &dos); if (err != EFI_SUCCESS) return err; if (len != sizeof(dos) || !verify_dos(&dos)) return EFI_LOAD_ERROR; err = handle->SetPosition(handle, dos.ExeHeader); if (err != EFI_SUCCESS) return err; len = sizeof(pe); err = handle->Read(handle, &len, &pe); if (err != EFI_SUCCESS) return err; if (len != sizeof(pe) || !verify_pe(&pe, /* allow_compatibility= */ false)) return EFI_LOAD_ERROR; section_table_len = pe.FileHeader.NumberOfSections * sizeof(PeSectionHeader); section_table = xmalloc(section_table_len); if (!section_table) return EFI_OUT_OF_RESOURCES; err = handle->SetPosition(handle, section_table_offset(&dos, &pe)); if (err != EFI_SUCCESS) return err; len = section_table_len; err = handle->Read(handle, &len, section_table); if (err != EFI_SUCCESS) return err; if (len != section_table_len) return EFI_LOAD_ERROR; locate_sections(section_table, pe.FileHeader.NumberOfSections, sections, offsets, sizes, /*in_memory=*/false); return EFI_SUCCESS; }
11,183
32.585586
117
c
null
systemd-main/src/boot/efi/pe.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "efi.h" EFI_STATUS pe_memory_locate_sections( const void *base, const char * const sections[], size_t *addrs, size_t *sizes); EFI_STATUS pe_file_locate_sections( EFI_FILE *dir, const char16_t *path, const char * const sections[], size_t *offsets, size_t *sizes); EFI_STATUS pe_kernel_info(const void *base, uint32_t *ret_compat_address);
557
26.9
74
h
null
systemd-main/src/boot/efi/random-seed.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "memory-util-fundamental.h" #include "proto/rng.h" #include "random-seed.h" #include "secure-boot.h" #include "sha256.h" #include "util.h" #define RANDOM_MAX_SIZE_MIN (32U) #define RANDOM_MAX_SIZE_MAX (32U*1024U) struct linux_efi_random_seed { uint32_t size; uint8_t seed[]; }; #define LINUX_EFI_RANDOM_SEED_TABLE_GUID \ { 0x1ce1e5bc, 0x7ceb, 0x42f2, { 0x81, 0xe5, 0x8a, 0xad, 0xf1, 0x80, 0xf5, 0x7b } } /* SHA256 gives us 256/8=32 bytes */ #define HASH_VALUE_SIZE 32 /* Linux's RNG is 256 bits, so let's provide this much */ #define DESIRED_SEED_SIZE 32 /* Some basic domain separation in case somebody uses this data elsewhere */ #define HASH_LABEL "systemd-boot random seed label v1" static EFI_STATUS acquire_rng(void *ret, size_t size) { EFI_RNG_PROTOCOL *rng; EFI_STATUS err; assert(ret); /* Try to acquire the specified number of bytes from the UEFI RNG */ err = BS->LocateProtocol(MAKE_GUID_PTR(EFI_RNG_PROTOCOL), NULL, (void **) &rng); if (err != EFI_SUCCESS) return err; if (!rng) return EFI_UNSUPPORTED; err = rng->GetRNG(rng, NULL, size, ret); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to acquire RNG data: %m"); return EFI_SUCCESS; } static EFI_STATUS acquire_system_token(void **ret, size_t *ret_size) { _cleanup_free_ char *data = NULL; EFI_STATUS err; size_t size; assert(ret); assert(ret_size); err = efivar_get_raw(MAKE_GUID_PTR(LOADER), u"LoaderSystemToken", &data, &size); if (err != EFI_SUCCESS) { if (err != EFI_NOT_FOUND) log_error_status(err, "Failed to read LoaderSystemToken EFI variable: %m"); return err; } if (size <= 0) return log_error_status(EFI_NOT_FOUND, "System token too short, ignoring."); *ret = TAKE_PTR(data); *ret_size = size; return EFI_SUCCESS; } static void validate_sha256(void) { #ifdef EFI_DEBUG /* Let's validate our SHA256 implementation. We stole it from glibc, and converted it to UEFI * style. We better check whether it does the right stuff. We use the simpler test vectors from the * SHA spec. Note that we strip this out in optimization builds. */ static const struct { const char *string; uint8_t hash[HASH_VALUE_SIZE]; } array[] = { { "abc", { 0xba, 0x78, 0x16, 0xbf, 0x8f, 0x01, 0xcf, 0xea, 0x41, 0x41, 0x40, 0xde, 0x5d, 0xae, 0x22, 0x23, 0xb0, 0x03, 0x61, 0xa3, 0x96, 0x17, 0x7a, 0x9c, 0xb4, 0x10, 0xff, 0x61, 0xf2, 0x00, 0x15, 0xad }}, { "", { 0xe3, 0xb0, 0xc4, 0x42, 0x98, 0xfc, 0x1c, 0x14, 0x9a, 0xfb, 0xf4, 0xc8, 0x99, 0x6f, 0xb9, 0x24, 0x27, 0xae, 0x41, 0xe4, 0x64, 0x9b, 0x93, 0x4c, 0xa4, 0x95, 0x99, 0x1b, 0x78, 0x52, 0xb8, 0x55 }}, { "abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq", { 0x24, 0x8d, 0x6a, 0x61, 0xd2, 0x06, 0x38, 0xb8, 0xe5, 0xc0, 0x26, 0x93, 0x0c, 0x3e, 0x60, 0x39, 0xa3, 0x3c, 0xe4, 0x59, 0x64, 0xff, 0x21, 0x67, 0xf6, 0xec, 0xed, 0xd4, 0x19, 0xdb, 0x06, 0xc1 }}, { "abcdefghbcdefghicdefghijdefghijkefghijklfghijklmghijklmnhijklmnoijklmnopjklmnopqklmnopqrlmnopqrsmnopqrstnopqrstu", { 0xcf, 0x5b, 0x16, 0xa7, 0x78, 0xaf, 0x83, 0x80, 0x03, 0x6c, 0xe5, 0x9e, 0x7b, 0x04, 0x92, 0x37, 0x0b, 0x24, 0x9b, 0x11, 0xe8, 0xf0, 0x7a, 0x51, 0xaf, 0xac, 0x45, 0x03, 0x7a, 0xfe, 0xe9, 0xd1 }}, }; for (size_t i = 0; i < ELEMENTSOF(array); i++) assert(memcmp(SHA256_DIRECT(array[i].string, strlen8(array[i].string)), array[i].hash, HASH_VALUE_SIZE) == 0); #endif } EFI_STATUS process_random_seed(EFI_FILE *root_dir) { uint8_t random_bytes[DESIRED_SEED_SIZE], hash_key[HASH_VALUE_SIZE]; _cleanup_free_ struct linux_efi_random_seed *new_seed_table = NULL; struct linux_efi_random_seed *previous_seed_table = NULL; _cleanup_free_ void *seed = NULL, *system_token = NULL; _cleanup_(file_closep) EFI_FILE *handle = NULL; _cleanup_free_ EFI_FILE_INFO *info = NULL; struct sha256_ctx hash; uint64_t uefi_monotonic_counter = 0; size_t size, rsize, wsize; bool seeded_by_efi = false; EFI_STATUS err; EFI_TIME now; CLEANUP_ERASE(random_bytes); CLEANUP_ERASE(hash_key); CLEANUP_ERASE(hash); assert(root_dir); assert_cc(DESIRED_SEED_SIZE == HASH_VALUE_SIZE); validate_sha256(); /* hash = LABEL || sizeof(input1) || input1 || ... || sizeof(inputN) || inputN */ sha256_init_ctx(&hash); /* Some basic domain separation in case somebody uses this data elsewhere */ sha256_process_bytes(HASH_LABEL, sizeof(HASH_LABEL) - 1, &hash); previous_seed_table = find_configuration_table(MAKE_GUID_PTR(LINUX_EFI_RANDOM_SEED_TABLE)); if (!previous_seed_table) { size = 0; sha256_process_bytes(&size, sizeof(size), &hash); } else { size = previous_seed_table->size; seeded_by_efi = size >= DESIRED_SEED_SIZE; sha256_process_bytes(&size, sizeof(size), &hash); sha256_process_bytes(previous_seed_table->seed, size, &hash); /* Zero and free the previous seed table only at the end after we've managed to install a new * one, so that in case this function fails or aborts, Linux still receives whatever the * previous bootloader chain set. So, the next line of this block is not an explicit_bzero() * call. */ } /* Request some random data from the UEFI RNG. We don't need this to work safely, but it's a good * idea to use it because it helps us for cases where users mistakenly include a random seed in * golden master images that are replicated many times. */ err = acquire_rng(random_bytes, sizeof(random_bytes)); if (err != EFI_SUCCESS) { size = 0; /* If we can't get any randomness from EFI itself, then we'll only be relying on what's in * ESP. But ESP is mutable, so if secure boot is enabled, we probably shouldn't trust that * alone, in which case we bail out early. */ if (!seeded_by_efi && secure_boot_enabled()) return EFI_NOT_FOUND; } else { seeded_by_efi = true; size = sizeof(random_bytes); } sha256_process_bytes(&size, sizeof(size), &hash); sha256_process_bytes(random_bytes, size, &hash); /* Get some system specific seed that the installer might have placed in an EFI variable. We include * it in our hash. This is protection against golden master image sloppiness, and it remains on the * system, even when disk images are duplicated or swapped out. */ size = 0; err = acquire_system_token(&system_token, &size); if ((err != EFI_SUCCESS || size < DESIRED_SEED_SIZE) && !seeded_by_efi) return err; sha256_process_bytes(&size, sizeof(size), &hash); if (system_token) { sha256_process_bytes(system_token, size, &hash); explicit_bzero_safe(system_token, size); } err = root_dir->Open( root_dir, &handle, (char16_t *) u"\\loader\\random-seed", EFI_FILE_MODE_READ | EFI_FILE_MODE_WRITE, 0); if (err != EFI_SUCCESS) { if (err != EFI_NOT_FOUND && err != EFI_WRITE_PROTECTED) log_error_status(err, "Failed to open random seed file: %m"); return err; } err = get_file_info(handle, &info, NULL); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to get file info for random seed: %m"); size = info->FileSize; if (size < RANDOM_MAX_SIZE_MIN) return log_error("Random seed file is too short."); if (size > RANDOM_MAX_SIZE_MAX) return log_error("Random seed file is too large."); seed = xmalloc(size); rsize = size; err = handle->Read(handle, &rsize, seed); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to read random seed file: %m"); if (rsize != size) { explicit_bzero_safe(seed, rsize); return log_error_status(EFI_PROTOCOL_ERROR, "Short read on random seed file."); } sha256_process_bytes(&size, sizeof(size), &hash); sha256_process_bytes(seed, size, &hash); explicit_bzero_safe(seed, size); err = handle->SetPosition(handle, 0); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to seek to beginning of random seed file: %m"); /* Let's also include the UEFI monotonic counter (which is supposedly increasing on every single * boot) in the hash, so that even if the changes to the ESP for some reason should not be * persistent, the random seed we generate will still be different on every single boot. */ err = BS->GetNextMonotonicCount(&uefi_monotonic_counter); if (err != EFI_SUCCESS && !seeded_by_efi) return log_error_status(err, "Failed to acquire UEFI monotonic counter: %m"); size = sizeof(uefi_monotonic_counter); sha256_process_bytes(&size, sizeof(size), &hash); sha256_process_bytes(&uefi_monotonic_counter, size, &hash); err = RT->GetTime(&now, NULL); size = err == EFI_SUCCESS ? sizeof(now) : 0; /* Known to be flaky, so don't bark on error. */ sha256_process_bytes(&size, sizeof(size), &hash); sha256_process_bytes(&now, size, &hash); /* hash_key = HASH(hash) */ sha256_finish_ctx(&hash, hash_key); /* hash = hash_key || 0 */ sha256_init_ctx(&hash); sha256_process_bytes(hash_key, sizeof(hash_key), &hash); sha256_process_bytes(&(const uint8_t){ 0 }, sizeof(uint8_t), &hash); /* random_bytes = HASH(hash) */ sha256_finish_ctx(&hash, random_bytes); size = sizeof(random_bytes); /* If the file size is too large, zero out the remaining bytes on disk. */ if (size < info->FileSize) { err = handle->SetPosition(handle, size); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to seek to offset of random seed file: %m"); wsize = info->FileSize - size; err = handle->Write(handle, &wsize, seed /* All zeros now */); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to write random seed file: %m"); if (wsize != info->FileSize - size) return log_error_status(EFI_PROTOCOL_ERROR, "Short write on random seed file."); err = handle->Flush(handle); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to flush random seed file: %m"); err = handle->SetPosition(handle, 0); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to seek to beginning of random seed file: %m"); /* We could truncate the file here with something like: * * info->FileSize = size; * err = handle->SetInfo(handle, &GenericFileInfo, info->Size, info); * if (err != EFI_SUCCESS) * return log_error_status(err, "Failed to truncate random seed file: %u"); * * But this is considered slightly risky, because EFI filesystem drivers are a little bit * flimsy. So instead we rely on userspace eventually truncating this when it writes a new * seed. For now the best we do is zero it. */ } /* Update the random seed on disk before we use it */ wsize = size; err = handle->Write(handle, &wsize, random_bytes); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to write random seed file: %m"); if (wsize != size) return log_error_status(EFI_PROTOCOL_ERROR, "Short write on random seed file."); err = handle->Flush(handle); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to flush random seed file: %m"); err = BS->AllocatePool(EfiACPIReclaimMemory, offsetof(struct linux_efi_random_seed, seed) + DESIRED_SEED_SIZE, (void **) &new_seed_table); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to allocate EFI table for random seed: %m"); new_seed_table->size = DESIRED_SEED_SIZE; /* hash = hash_key || 1 */ sha256_init_ctx(&hash); sha256_process_bytes(hash_key, sizeof(hash_key), &hash); sha256_process_bytes(&(const uint8_t){ 1 }, sizeof(uint8_t), &hash); /* new_seed_table->seed = HASH(hash) */ sha256_finish_ctx(&hash, new_seed_table->seed); err = BS->InstallConfigurationTable(MAKE_GUID_PTR(LINUX_EFI_RANDOM_SEED_TABLE), new_seed_table); if (err != EFI_SUCCESS) return log_error_status(err, "Failed to install EFI table for random seed: %m"); TAKE_PTR(new_seed_table); if (previous_seed_table) { /* Now that we've succeeded in installing the new table, we can safely nuke the old one. */ explicit_bzero_safe(previous_seed_table->seed, previous_seed_table->size); explicit_bzero_safe(previous_seed_table, sizeof(*previous_seed_table)); free(previous_seed_table); } return EFI_SUCCESS; }
14,568
43.690184
133
c
null
systemd-main/src/boot/efi/secure-boot.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "console.h" #include "proto/security-arch.h" #include "sbat.h" #include "secure-boot.h" #include "util.h" #include "vmm.h" bool secure_boot_enabled(void) { bool secure = false; /* avoid false maybe-uninitialized warning */ EFI_STATUS err; err = efivar_get_boolean_u8(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"SecureBoot", &secure); return err == EFI_SUCCESS && secure; } SecureBootMode secure_boot_mode(void) { bool secure, audit = false, deployed = false, setup = false; EFI_STATUS err; err = efivar_get_boolean_u8(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"SecureBoot", &secure); if (err != EFI_SUCCESS) return SECURE_BOOT_UNSUPPORTED; /* We can assume false for all these if they are abscent (AuditMode and * DeployedMode may not exist on older firmware). */ (void) efivar_get_boolean_u8(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"AuditMode", &audit); (void) efivar_get_boolean_u8(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"DeployedMode", &deployed); (void) efivar_get_boolean_u8(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"SetupMode", &setup); return decode_secure_boot_mode(secure, audit, deployed, setup); } #ifdef SBAT_DISTRO static const char sbat[] _used_ _section_(".sbat") = SBAT_SECTION_TEXT; #endif EFI_STATUS secure_boot_enroll_at(EFI_FILE *root_dir, const char16_t *path, bool force) { assert(root_dir); assert(path); EFI_STATUS err; clear_screen(COLOR_NORMAL); /* Enrolling secure boot keys is safe to do in virtualized environments as there is nothing * we can brick there. */ bool is_safe = in_hypervisor(); if (!is_safe && !force) return EFI_SUCCESS; printf("Enrolling secure boot keys from directory: %ls\n", path); if (!is_safe) { printf("Warning: Enrolling custom Secure Boot keys might soft-brick your machine!\n"); unsigned timeout_sec = 15; for (;;) { printf("\rEnrolling in %2u s, press any key to abort.", timeout_sec); uint64_t key; err = console_key_read(&key, 1000 * 1000); if (err == EFI_NOT_READY) continue; if (err == EFI_TIMEOUT) { if (timeout_sec == 0) /* continue enrolling keys */ break; timeout_sec--; continue; } if (err != EFI_SUCCESS) return log_error_status( err, "Error waiting for user input to enroll Secure Boot keys: %m"); /* user aborted, returning EFI_SUCCESS here allows the user to go back to the menu */ return EFI_SUCCESS; } } _cleanup_(file_closep) EFI_FILE *dir = NULL; err = open_directory(root_dir, path, &dir); if (err != EFI_SUCCESS) return log_error_status(err, "Failed opening keys directory %ls: %m", path); struct { const char16_t *name; const char16_t *filename; const EFI_GUID vendor; char *buffer; size_t size; } sb_vars[] = { { u"db", u"db.auth", EFI_IMAGE_SECURITY_DATABASE_GUID, NULL, 0 }, { u"KEK", u"KEK.auth", EFI_GLOBAL_VARIABLE, NULL, 0 }, { u"PK", u"PK.auth", EFI_GLOBAL_VARIABLE, NULL, 0 }, }; /* Make sure all keys files exist before we start enrolling them by loading them from the disk first. */ for (size_t i = 0; i < ELEMENTSOF(sb_vars); i++) { err = file_read(dir, sb_vars[i].filename, 0, 0, &sb_vars[i].buffer, &sb_vars[i].size); if (err != EFI_SUCCESS) { log_error_status(err, "Failed reading file %ls\\%ls: %m", path, sb_vars[i].filename); goto out_deallocate; } } for (size_t i = 0; i < ELEMENTSOF(sb_vars); i++) { uint32_t sb_vars_opts = EFI_VARIABLE_NON_VOLATILE | EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS | EFI_VARIABLE_TIME_BASED_AUTHENTICATED_WRITE_ACCESS; err = efivar_set_raw(&sb_vars[i].vendor, sb_vars[i].name, sb_vars[i].buffer, sb_vars[i].size, sb_vars_opts); if (err != EFI_SUCCESS) { log_error_status(err, "Failed to write %ls secure boot variable: %m", sb_vars[i].name); goto out_deallocate; } } /* The system should be in secure boot mode now and we could continue a regular boot. But at least * TPM PCR7 measurements should change on next boot. Reboot now so that any OS we load does not end * up relying on the old PCR state. */ RT->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL); assert_not_reached(); out_deallocate: for (size_t i = 0; i < ELEMENTSOF(sb_vars); i++) free(sb_vars[i].buffer); return err; } static struct SecurityOverride { EFI_SECURITY_ARCH_PROTOCOL *security; EFI_SECURITY2_ARCH_PROTOCOL *security2; EFI_SECURITY_FILE_AUTHENTICATION_STATE original_hook; EFI_SECURITY2_FILE_AUTHENTICATION original_hook2; security_validator_t validator; const void *validator_ctx; } security_override; static EFIAPI EFI_STATUS security_hook( const EFI_SECURITY_ARCH_PROTOCOL *this, uint32_t authentication_status, const EFI_DEVICE_PATH *file) { assert(security_override.validator); assert(security_override.security); assert(security_override.original_hook); if (security_override.validator(security_override.validator_ctx, file, NULL, 0)) return EFI_SUCCESS; return security_override.original_hook(security_override.security, authentication_status, file); } static EFIAPI EFI_STATUS security2_hook( const EFI_SECURITY2_ARCH_PROTOCOL *this, const EFI_DEVICE_PATH *device_path, void *file_buffer, size_t file_size, bool boot_policy) { assert(security_override.validator); assert(security_override.security2); assert(security_override.original_hook2); if (security_override.validator(security_override.validator_ctx, device_path, file_buffer, file_size)) return EFI_SUCCESS; return security_override.original_hook2( security_override.security2, device_path, file_buffer, file_size, boot_policy); } /* This replaces the platform provided security arch protocols hooks (defined in the UEFI Platform * Initialization Specification) with our own that uses the given validator to decide if a image is to be * trusted. If not running in secure boot or the protocols are not available nothing happens. The override * must be removed with uninstall_security_override() after LoadImage() has been called. * * This is a hack as we do not own the security protocol instances and modifying them is not an official part * of their spec. But there is little else we can do to circumvent secure boot short of implementing our own * PE loader. We could replace the firmware instances with our own instance using * ReinstallProtocolInterface(), but some firmware will still use the old ones. */ void install_security_override(security_validator_t validator, const void *validator_ctx) { EFI_STATUS err; assert(validator); if (!secure_boot_enabled()) return; security_override = (struct SecurityOverride) { .validator = validator, .validator_ctx = validator_ctx, }; EFI_SECURITY_ARCH_PROTOCOL *security = NULL; err = BS->LocateProtocol(MAKE_GUID_PTR(EFI_SECURITY_ARCH_PROTOCOL), NULL, (void **) &security); if (err == EFI_SUCCESS) { security_override.security = security; security_override.original_hook = security->FileAuthenticationState; security->FileAuthenticationState = security_hook; } EFI_SECURITY2_ARCH_PROTOCOL *security2 = NULL; err = BS->LocateProtocol(MAKE_GUID_PTR(EFI_SECURITY2_ARCH_PROTOCOL), NULL, (void **) &security2); if (err == EFI_SUCCESS) { security_override.security2 = security2; security_override.original_hook2 = security2->FileAuthentication; security2->FileAuthentication = security2_hook; } } void uninstall_security_override(void) { if (security_override.original_hook) security_override.security->FileAuthenticationState = security_override.original_hook; if (security_override.original_hook2) security_override.security2->FileAuthentication = security_override.original_hook2; }
9,437
40.761062
124
c
null
systemd-main/src/boot/efi/splash.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "graphics.h" #include "logarithm.h" #include "proto/graphics-output.h" #include "splash.h" #include "unaligned-fundamental.h" #include "util.h" struct bmp_file { char signature[2]; uint32_t size; uint16_t reserved[2]; uint32_t offset; } _packed_; /* we require at least BITMAPINFOHEADER, later versions are accepted, but their features ignored */ struct bmp_dib { uint32_t size; uint32_t x; uint32_t y; uint16_t planes; uint16_t depth; uint32_t compression; uint32_t image_size; int32_t x_pixel_meter; int32_t y_pixel_meter; uint32_t colors_used; uint32_t colors_important; uint32_t channel_mask_r; uint32_t channel_mask_g; uint32_t channel_mask_b; uint32_t channel_mask_a; } _packed_; #define SIZEOF_BMP_DIB offsetof(struct bmp_dib, channel_mask_r) #define SIZEOF_BMP_DIB_RGB offsetof(struct bmp_dib, channel_mask_a) #define SIZEOF_BMP_DIB_RGBA sizeof(struct bmp_dib) struct bmp_map { uint8_t blue; uint8_t green; uint8_t red; uint8_t reserved; } _packed_; static EFI_STATUS bmp_parse_header( const uint8_t *bmp, size_t size, struct bmp_dib **ret_dib, struct bmp_map **ret_map, const uint8_t **pixmap) { assert(bmp); assert(ret_dib); assert(ret_map); assert(pixmap); if (size < sizeof(struct bmp_file) + SIZEOF_BMP_DIB) return EFI_INVALID_PARAMETER; /* check file header */ struct bmp_file *file = (struct bmp_file *) bmp; if (file->signature[0] != 'B' || file->signature[1] != 'M') return EFI_INVALID_PARAMETER; if (file->size != size) return EFI_INVALID_PARAMETER; if (file->size < file->offset) return EFI_INVALID_PARAMETER; /* check device-independent bitmap */ struct bmp_dib *dib = (struct bmp_dib *) (bmp + sizeof(struct bmp_file)); if (dib->size < SIZEOF_BMP_DIB) return EFI_UNSUPPORTED; switch (dib->depth) { case 1: case 4: case 8: case 24: if (dib->compression != 0) return EFI_UNSUPPORTED; break; case 16: case 32: if (dib->compression != 0 && dib->compression != 3) return EFI_UNSUPPORTED; break; default: return EFI_UNSUPPORTED; } size_t row_size = ((size_t) dib->depth * dib->x + 31) / 32 * 4; if (file->size - file->offset < dib->y * row_size) return EFI_INVALID_PARAMETER; if (row_size * dib->y > 64 * 1024 * 1024) return EFI_INVALID_PARAMETER; /* check color table */ struct bmp_map *map = (struct bmp_map *) (bmp + sizeof(struct bmp_file) + dib->size); if (file->offset < sizeof(struct bmp_file) + dib->size) return EFI_INVALID_PARAMETER; if (file->offset > sizeof(struct bmp_file) + dib->size) { uint32_t map_count = 0; if (dib->colors_used) map_count = dib->colors_used; else if (IN_SET(dib->depth, 1, 4, 8)) map_count = 1 << dib->depth; size_t map_size = file->offset - (sizeof(struct bmp_file) + dib->size); if (map_size != sizeof(struct bmp_map) * map_count) return EFI_INVALID_PARAMETER; } *ret_map = map; *ret_dib = dib; *pixmap = bmp + file->offset; return EFI_SUCCESS; } enum Channels { R, G, B, A, _CHANNELS_MAX }; static void read_channel_maks( const struct bmp_dib *dib, uint32_t channel_mask[static _CHANNELS_MAX], uint8_t channel_shift[static _CHANNELS_MAX], uint8_t channel_scale[static _CHANNELS_MAX]) { assert(dib); if (IN_SET(dib->depth, 16, 32) && dib->size >= SIZEOF_BMP_DIB_RGB) { channel_mask[R] = dib->channel_mask_r; channel_mask[G] = dib->channel_mask_g; channel_mask[B] = dib->channel_mask_b; channel_shift[R] = __builtin_ctz(dib->channel_mask_r); channel_shift[G] = __builtin_ctz(dib->channel_mask_g); channel_shift[B] = __builtin_ctz(dib->channel_mask_b); channel_scale[R] = 0xff / ((1 << popcount(dib->channel_mask_r)) - 1); channel_scale[G] = 0xff / ((1 << popcount(dib->channel_mask_g)) - 1); channel_scale[B] = 0xff / ((1 << popcount(dib->channel_mask_b)) - 1); if (dib->size >= SIZEOF_BMP_DIB_RGBA && dib->channel_mask_a != 0) { channel_mask[A] = dib->channel_mask_a; channel_shift[A] = __builtin_ctz(dib->channel_mask_a); channel_scale[A] = 0xff / ((1 << popcount(dib->channel_mask_a)) - 1); } else { channel_mask[A] = 0; channel_shift[A] = 0; channel_scale[A] = 0; } } else { bool bpp16 = dib->depth == 16; channel_mask[R] = bpp16 ? 0x7C00 : 0xFF0000; channel_mask[G] = bpp16 ? 0x03E0 : 0x00FF00; channel_mask[B] = bpp16 ? 0x001F : 0x0000FF; channel_mask[A] = bpp16 ? 0x0000 : 0x000000; channel_shift[R] = bpp16 ? 0xA : 0x10; channel_shift[G] = bpp16 ? 0x5 : 0x08; channel_shift[B] = bpp16 ? 0x0 : 0x00; channel_shift[A] = bpp16 ? 0x0 : 0x00; channel_scale[R] = bpp16 ? 0x08 : 0x1; channel_scale[G] = bpp16 ? 0x08 : 0x1; channel_scale[B] = bpp16 ? 0x08 : 0x1; channel_scale[A] = bpp16 ? 0x00 : 0x0; } } static EFI_STATUS bmp_to_blt( EFI_GRAPHICS_OUTPUT_BLT_PIXEL *buf, struct bmp_dib *dib, struct bmp_map *map, const uint8_t *pixmap) { const uint8_t *in; assert(buf); assert(dib); assert(map); assert(pixmap); uint32_t channel_mask[_CHANNELS_MAX]; uint8_t channel_shift[_CHANNELS_MAX], channel_scale[_CHANNELS_MAX]; read_channel_maks(dib, channel_mask, channel_shift, channel_scale); /* transform and copy pixels */ in = pixmap; for (uint32_t y = 0; y < dib->y; y++) { EFI_GRAPHICS_OUTPUT_BLT_PIXEL *out = &buf[(dib->y - y - 1) * dib->x]; for (uint32_t x = 0; x < dib->x; x++, in++, out++) { switch (dib->depth) { case 1: { for (unsigned i = 0; i < 8 && x < dib->x; i++) { out->Red = map[((*in) >> (7 - i)) & 1].red; out->Green = map[((*in) >> (7 - i)) & 1].green; out->Blue = map[((*in) >> (7 - i)) & 1].blue; out++; x++; } out--; x--; break; } case 4: { unsigned i = (*in) >> 4; out->Red = map[i].red; out->Green = map[i].green; out->Blue = map[i].blue; if (x < (dib->x - 1)) { out++; x++; i = (*in) & 0x0f; out->Red = map[i].red; out->Green = map[i].green; out->Blue = map[i].blue; } break; } case 8: out->Red = map[*in].red; out->Green = map[*in].green; out->Blue = map[*in].blue; break; case 24: out->Red = in[2]; out->Green = in[1]; out->Blue = in[0]; in += 2; break; case 16: case 32: { uint32_t i = dib->depth == 16 ? unaligned_read_ne16(in) : unaligned_read_ne32(in); uint8_t r = ((i & channel_mask[R]) >> channel_shift[R]) * channel_scale[R], g = ((i & channel_mask[G]) >> channel_shift[G]) * channel_scale[G], b = ((i & channel_mask[B]) >> channel_shift[B]) * channel_scale[B], a = 0xFFu; if (channel_mask[A] != 0) a = ((i & channel_mask[A]) >> channel_shift[A]) * channel_scale[A]; out->Red = (out->Red * (0xFFu - a) + r * a) >> 8; out->Green = (out->Green * (0xFFu - a) + g * a) >> 8; out->Blue = (out->Blue * (0xFFu - a) + b * a) >> 8; in += dib->depth == 16 ? 1 : 3; break; } } } /* add row padding; new lines always start at 32 bit boundary */ size_t row_size = in - pixmap; in += ((row_size + 3) & ~3) - row_size; } return EFI_SUCCESS; } EFI_STATUS graphics_splash(const uint8_t *content, size_t len) { EFI_GRAPHICS_OUTPUT_BLT_PIXEL background = {}; EFI_GRAPHICS_OUTPUT_PROTOCOL *GraphicsOutput = NULL; struct bmp_dib *dib; struct bmp_map *map; const uint8_t *pixmap; size_t x_pos = 0, y_pos = 0; EFI_STATUS err; if (len == 0) return EFI_SUCCESS; assert(content); if (strcaseeq16(ST->FirmwareVendor, u"Apple")) { background.Red = 0xc0; background.Green = 0xc0; background.Blue = 0xc0; } err = BS->LocateProtocol(MAKE_GUID_PTR(EFI_GRAPHICS_OUTPUT_PROTOCOL), NULL, (void **) &GraphicsOutput); if (err != EFI_SUCCESS) return err; err = bmp_parse_header(content, len, &dib, &map, &pixmap); if (err != EFI_SUCCESS) return err; if (dib->x < GraphicsOutput->Mode->Info->HorizontalResolution) x_pos = (GraphicsOutput->Mode->Info->HorizontalResolution - dib->x) / 2; if (dib->y < GraphicsOutput->Mode->Info->VerticalResolution) y_pos = (GraphicsOutput->Mode->Info->VerticalResolution - dib->y) / 2; err = GraphicsOutput->Blt( GraphicsOutput, &background, EfiBltVideoFill, 0, 0, 0, 0, GraphicsOutput->Mode->Info->HorizontalResolution, GraphicsOutput->Mode->Info->VerticalResolution, 0); if (err != EFI_SUCCESS) return err; /* Read in current screen content to perform proper alpha blending. */ _cleanup_free_ EFI_GRAPHICS_OUTPUT_BLT_PIXEL *blt = xnew( EFI_GRAPHICS_OUTPUT_BLT_PIXEL, dib->x * dib->y); err = GraphicsOutput->Blt( GraphicsOutput, blt, EfiBltVideoToBltBuffer, x_pos, y_pos, 0, 0, dib->x, dib->y, 0); if (err != EFI_SUCCESS) return err; err = bmp_to_blt(blt, dib, map, pixmap); if (err != EFI_SUCCESS) return err; err = graphics_mode(true); if (err != EFI_SUCCESS) return err; return GraphicsOutput->Blt( GraphicsOutput, blt, EfiBltBufferToVideo, 0, 0, x_pos, y_pos, dib->x, dib->y, 0); }
12,763
37.101493
111
c
null
systemd-main/src/boot/efi/test-bcd.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "bcd.h" #include "compress.h" #include "fileio.h" #include "tests.h" #include "utf8.h" /* Include the implementation directly, so we can poke at some internals. */ #include "bcd.c" static void load_bcd(const char *path, void **ret_bcd, size_t *ret_bcd_len) { size_t len; _cleanup_free_ char *fn = NULL, *compressed = NULL; assert_se(get_testdata_dir(path, &fn) >= 0); assert_se(read_full_file_full(AT_FDCWD, fn, UINT64_MAX, SIZE_MAX, 0, NULL, &compressed, &len) >= 0); assert_se(decompress_blob_zstd(compressed, len, ret_bcd, ret_bcd_len, SIZE_MAX) >= 0); } static void test_get_bcd_title_one( const char *path, const char16_t *title_expect, size_t title_len_expect) { size_t len; _cleanup_free_ void *bcd = NULL; log_info("/* %s(%s) */", __func__, path); load_bcd(path, &bcd, &len); char16_t *title = get_bcd_title(bcd, len); if (title_expect) { assert_se(title); assert_se(memcmp(title, title_expect, title_len_expect) == 0); } else assert_se(!title); } TEST(get_bcd_title) { test_get_bcd_title_one("test-bcd/win10.bcd.zst", u"Windows 10", sizeof(u"Windows 10")); test_get_bcd_title_one("test-bcd/description-bad-type.bcd.zst", NULL, 0); test_get_bcd_title_one("test-bcd/description-empty.bcd.zst", NULL, 0); test_get_bcd_title_one("test-bcd/description-missing.bcd.zst", NULL, 0); test_get_bcd_title_one("test-bcd/description-too-small.bcd.zst", NULL, 0); test_get_bcd_title_one("test-bcd/displayorder-bad-name.bcd.zst", NULL, 0); test_get_bcd_title_one("test-bcd/displayorder-bad-size.bcd.zst", NULL, 0); test_get_bcd_title_one("test-bcd/displayorder-bad-type.bcd.zst", NULL, 0); test_get_bcd_title_one("test-bcd/empty.bcd.zst", NULL, 0); } TEST(base_block) { size_t len; BaseBlock backup; uint8_t *bcd_base; _cleanup_free_ BaseBlock *bcd = NULL; load_bcd("test-bcd/win10.bcd.zst", (void **) &bcd, &len); backup = *bcd; bcd_base = (uint8_t *) bcd; assert_se(get_bcd_title(bcd_base, len)); /* Try various "corruptions" of the base block. */ assert_se(!get_bcd_title(bcd_base, sizeof(BaseBlock) - 1)); bcd->sig = 0; assert_se(!get_bcd_title(bcd_base, len)); *bcd = backup; bcd->version_minor = 2; assert_se(!get_bcd_title(bcd_base, len)); *bcd = backup; bcd->version_major = 4; assert_se(!get_bcd_title(bcd_base, len)); *bcd = backup; bcd->type = 1; assert_se(!get_bcd_title(bcd_base, len)); *bcd = backup; bcd->primary_seqnum++; assert_se(!get_bcd_title(bcd_base, len)); *bcd = backup; } TEST(bad_bcd) { size_t len; uint8_t *hbins; uint32_t offset; _cleanup_free_ void *bcd = NULL; /* This BCD hive has been manipulated to have bad offsets/sizes at various places. */ load_bcd("test-bcd/corrupt.bcd.zst", &bcd, &len); assert_se(len >= HIVE_CELL_OFFSET); hbins = (uint8_t *) bcd + HIVE_CELL_OFFSET; len -= HIVE_CELL_OFFSET; offset = ((BaseBlock *) bcd)->root_cell_offset; const Key *root = get_key(hbins, len, offset, "\0"); assert_se(root); assert_se(!get_key(hbins, sizeof(Key) - 1, offset, "\0")); assert_se(!get_key(hbins, len, offset, "\0BadOffset\0")); assert_se(!get_key(hbins, len, offset, "\0BadSig\0")); assert_se(!get_key(hbins, len, offset, "\0BadKeyNameLen\0")); assert_se(!get_key(hbins, len, offset, "\0SubkeyBadOffset\0Dummy\0")); assert_se(!get_key(hbins, len, offset, "\0SubkeyBadSig\0Dummy\0")); assert_se(!get_key(hbins, len, offset, "\0SubkeyBadNEntries\0Dummy\0")); assert_se(!get_key_value(hbins, len, root, "Dummy")); const Key *kv_bad_offset = get_key(hbins, len, offset, "\0KeyValuesBadOffset\0"); assert_se(kv_bad_offset); assert_se(!get_key_value(hbins, len, kv_bad_offset, "Dummy")); const Key *kv_bad_n_key_values = get_key(hbins, len, offset, "\0KeyValuesBadNKeyValues\0"); assert_se(kv_bad_n_key_values); assert_se(!get_key_value(hbins, len, kv_bad_n_key_values, "Dummy")); const Key *kv = get_key(hbins, len, offset, "\0KeyValues\0"); assert_se(kv); assert_se(!get_key_value(hbins, len, kv, "BadOffset")); assert_se(!get_key_value(hbins, len, kv, "BadSig")); assert_se(!get_key_value(hbins, len, kv, "BadNameLen")); assert_se(!get_key_value(hbins, len, kv, "InlineData")); assert_se(!get_key_value(hbins, len, kv, "BadDataOffset")); assert_se(!get_key_value(hbins, len, kv, "BadDataSize")); } TEST(argv_bcds) { for (int i = 1; i < saved_argc; i++) { size_t len; _cleanup_free_ void *bcd = NULL; assert_se(read_full_file_full( AT_FDCWD, saved_argv[i], UINT64_MAX, SIZE_MAX, 0, NULL, (char **) &bcd, &len) >= 0); char16_t *title = get_bcd_title(bcd, len); if (title) { _cleanup_free_ char *title_utf8 = utf16_to_utf8(title, char16_strlen(title) * 2); log_info("%s: \"%s\"", saved_argv[i], title_utf8); } else log_info("%s: Bad BCD", saved_argv[i]); } } DEFINE_TEST_MAIN(LOG_INFO);
5,843
34.852761
108
c
null
systemd-main/src/boot/efi/ticks.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "ticks.h" #include "util.h" #include "vmm.h" #if defined(__i386__) || defined(__x86_64__) # include <cpuid.h> static uint64_t ticks_read_arch(void) { /* The TSC might or might not be virtualized in VMs (and thus might not be accurate or start at zero * at boot), depending on hypervisor and CPU functionality. If it's not virtualized it's not useful * for keeping time, hence don't attempt to use it. */ if (in_hypervisor()) return 0; return __builtin_ia32_rdtsc(); } static uint64_t ticks_freq_arch(void) { /* Detect TSC frequency from CPUID information if available. */ unsigned max_leaf, ebx, ecx, edx; if (__get_cpuid(0, &max_leaf, &ebx, &ecx, &edx) == 0) return 0; /* Leaf 0x15 is Intel only. */ if (max_leaf < 0x15 || ebx != signature_INTEL_ebx || ecx != signature_INTEL_ecx || edx != signature_INTEL_edx) return 0; unsigned denominator, numerator, crystal_hz; __cpuid(0x15, denominator, numerator, crystal_hz, edx); if (denominator == 0 || numerator == 0) return 0; uint64_t freq = crystal_hz; if (crystal_hz == 0) { /* If the crystal frquency is not available, try to deduce it from * the processor frequency leaf if available. */ if (max_leaf < 0x16) return 0; unsigned core_mhz; __cpuid(0x16, core_mhz, ebx, ecx, edx); freq = core_mhz * 1000ULL * 1000ULL * denominator / numerator; } return freq * numerator / denominator; } #elif defined(__aarch64__) static uint64_t ticks_read_arch(void) { uint64_t val; asm volatile("mrs %0, cntvct_el0" : "=r"(val)); return val; } static uint64_t ticks_freq_arch(void) { uint64_t freq; asm volatile("mrs %0, cntfrq_el0" : "=r"(freq)); return freq; } #else static uint64_t ticks_read_arch(void) { return 0; } static uint64_t ticks_freq_arch(void) { return 0; } #endif static uint64_t ticks_freq(void) { static uint64_t cache = 0; if (cache != 0) return cache; cache = ticks_freq_arch(); if (cache != 0) return cache; /* As a fallback, count ticks during a millisecond delay. */ uint64_t ticks_start = ticks_read_arch(); BS->Stall(1000); uint64_t ticks_end = ticks_read_arch(); if (ticks_end < ticks_start) /* Check for an overflow (which is not that unlikely, given on some * archs the value is 32-bit) */ return 0; cache = (ticks_end - ticks_start) * 1000UL; return cache; } uint64_t time_usec(void) { uint64_t ticks = ticks_read_arch(); if (ticks == 0) return 0; uint64_t freq = ticks_freq(); if (freq == 0) return 0; return 1000UL * 1000UL * ticks / freq; }
3,138
27.026786
108
c
null
systemd-main/src/boot/efi/ubsan.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "log.h" typedef struct { const char *filename; uint32_t line; uint32_t column; } SourceLocation; /* Note that all ubsan handlers have a pointer to a type-specific struct passed as first argument. * Since we do not inspect the extra data in it we can just treat it as a SourceLocation struct * directly to keep things simple. */ #define HANDLER(name, ...) \ _used_ _noreturn_ void __ubsan_handle_##name(__VA_ARGS__); \ void __ubsan_handle_##name(__VA_ARGS__) { \ log_error("systemd-boot: %s in %s@%u:%u", \ __func__, \ location->filename, \ location->line, \ location->column); \ freeze(); \ } #define UNARY_HANDLER(name) HANDLER(name, SourceLocation *location, uintptr_t v) #define BINARY_HANDLER(name) HANDLER(name, SourceLocation *location, uintptr_t v1, uintptr_t v2) UNARY_HANDLER(load_invalid_value); UNARY_HANDLER(negate_overflow); UNARY_HANDLER(out_of_bounds); UNARY_HANDLER(type_mismatch_v1); UNARY_HANDLER(vla_bound_not_positive); BINARY_HANDLER(add_overflow); BINARY_HANDLER(divrem_overflow); BINARY_HANDLER(implicit_conversion); BINARY_HANDLER(mul_overflow); BINARY_HANDLER(pointer_overflow); BINARY_HANDLER(shift_out_of_bounds); BINARY_HANDLER(sub_overflow); HANDLER(builtin_unreachable, SourceLocation *location); HANDLER(invalid_builtin, SourceLocation *location); HANDLER(nonnull_arg, SourceLocation *location); HANDLER(nonnull_return_v1, SourceLocation *attr_location, SourceLocation *location);
1,870
38.808511
98
c
null
systemd-main/src/boot/efi/util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "device-path-util.h" #include "proto/device-path.h" #include "proto/simple-text-io.h" #include "ticks.h" #include "util.h" #include "version.h" EFI_STATUS parse_boolean(const char *v, bool *b) { assert(b); if (!v) return EFI_INVALID_PARAMETER; if (streq8(v, "1") || streq8(v, "yes") || streq8(v, "y") || streq8(v, "true") || streq8(v, "t") || streq8(v, "on")) { *b = true; return EFI_SUCCESS; } if (streq8(v, "0") || streq8(v, "no") || streq8(v, "n") || streq8(v, "false") || streq8(v, "f") || streq8(v, "off")) { *b = false; return EFI_SUCCESS; } return EFI_INVALID_PARAMETER; } EFI_STATUS efivar_set_raw(const EFI_GUID *vendor, const char16_t *name, const void *buf, size_t size, uint32_t flags) { assert(vendor); assert(name); assert(buf || size == 0); flags |= EFI_VARIABLE_BOOTSERVICE_ACCESS | EFI_VARIABLE_RUNTIME_ACCESS; return RT->SetVariable((char16_t *) name, (EFI_GUID *) vendor, flags, size, (void *) buf); } EFI_STATUS efivar_set(const EFI_GUID *vendor, const char16_t *name, const char16_t *value, uint32_t flags) { assert(vendor); assert(name); return efivar_set_raw(vendor, name, value, value ? strsize16(value) : 0, flags); } EFI_STATUS efivar_set_uint_string(const EFI_GUID *vendor, const char16_t *name, size_t i, uint32_t flags) { assert(vendor); assert(name); _cleanup_free_ char16_t *str = xasprintf("%zu", i); return efivar_set(vendor, name, str, flags); } EFI_STATUS efivar_set_uint32_le(const EFI_GUID *vendor, const char16_t *name, uint32_t value, uint32_t flags) { uint8_t buf[4]; assert(vendor); assert(name); buf[0] = (uint8_t)(value >> 0U & 0xFF); buf[1] = (uint8_t)(value >> 8U & 0xFF); buf[2] = (uint8_t)(value >> 16U & 0xFF); buf[3] = (uint8_t)(value >> 24U & 0xFF); return efivar_set_raw(vendor, name, buf, sizeof(buf), flags); } EFI_STATUS efivar_set_uint64_le(const EFI_GUID *vendor, const char16_t *name, uint64_t value, uint32_t flags) { uint8_t buf[8]; assert(vendor); assert(name); buf[0] = (uint8_t)(value >> 0U & 0xFF); buf[1] = (uint8_t)(value >> 8U & 0xFF); buf[2] = (uint8_t)(value >> 16U & 0xFF); buf[3] = (uint8_t)(value >> 24U & 0xFF); buf[4] = (uint8_t)(value >> 32U & 0xFF); buf[5] = (uint8_t)(value >> 40U & 0xFF); buf[6] = (uint8_t)(value >> 48U & 0xFF); buf[7] = (uint8_t)(value >> 56U & 0xFF); return efivar_set_raw(vendor, name, buf, sizeof(buf), flags); } EFI_STATUS efivar_get(const EFI_GUID *vendor, const char16_t *name, char16_t **ret) { _cleanup_free_ char16_t *buf = NULL; EFI_STATUS err; char16_t *val; size_t size; assert(vendor); assert(name); err = efivar_get_raw(vendor, name, (char **) &buf, &size); if (err != EFI_SUCCESS) return err; /* Make sure there are no incomplete characters in the buffer */ if ((size % sizeof(char16_t)) != 0) return EFI_INVALID_PARAMETER; if (!ret) return EFI_SUCCESS; /* Return buffer directly if it happens to be NUL terminated already */ if (size >= sizeof(char16_t) && buf[size / sizeof(char16_t) - 1] == 0) { *ret = TAKE_PTR(buf); return EFI_SUCCESS; } /* Make sure a terminating NUL is available at the end */ val = xmalloc(size + sizeof(char16_t)); memcpy(val, buf, size); val[size / sizeof(char16_t) - 1] = 0; /* NUL terminate */ *ret = val; return EFI_SUCCESS; } EFI_STATUS efivar_get_uint_string(const EFI_GUID *vendor, const char16_t *name, size_t *ret) { _cleanup_free_ char16_t *val = NULL; EFI_STATUS err; uint64_t u; assert(vendor); assert(name); err = efivar_get(vendor, name, &val); if (err != EFI_SUCCESS) return err; if (!parse_number16(val, &u, NULL) || u > SIZE_MAX) return EFI_INVALID_PARAMETER; if (ret) *ret = u; return EFI_SUCCESS; } EFI_STATUS efivar_get_uint32_le(const EFI_GUID *vendor, const char16_t *name, uint32_t *ret) { _cleanup_free_ char *buf = NULL; size_t size; EFI_STATUS err; assert(vendor); assert(name); err = efivar_get_raw(vendor, name, &buf, &size); if (err != EFI_SUCCESS) return err; if (size != sizeof(uint32_t)) return EFI_BUFFER_TOO_SMALL; if (ret) *ret = (uint32_t) buf[0] << 0U | (uint32_t) buf[1] << 8U | (uint32_t) buf[2] << 16U | (uint32_t) buf[3] << 24U; return EFI_SUCCESS; } EFI_STATUS efivar_get_uint64_le(const EFI_GUID *vendor, const char16_t *name, uint64_t *ret) { _cleanup_free_ char *buf = NULL; size_t size; EFI_STATUS err; assert(vendor); assert(name); err = efivar_get_raw(vendor, name, &buf, &size); if (err != EFI_SUCCESS) return err; if (size != sizeof(uint64_t)) return EFI_BUFFER_TOO_SMALL; if (ret) *ret = (uint64_t) buf[0] << 0U | (uint64_t) buf[1] << 8U | (uint64_t) buf[2] << 16U | (uint64_t) buf[3] << 24U | (uint64_t) buf[4] << 32U | (uint64_t) buf[5] << 40U | (uint64_t) buf[6] << 48U | (uint64_t) buf[7] << 56U; return EFI_SUCCESS; } EFI_STATUS efivar_get_raw(const EFI_GUID *vendor, const char16_t *name, char **ret, size_t *ret_size) { EFI_STATUS err; assert(vendor); assert(name); size_t size = 0; err = RT->GetVariable((char16_t *) name, (EFI_GUID *) vendor, NULL, &size, NULL); if (err != EFI_BUFFER_TOO_SMALL) return err; _cleanup_free_ void *buf = xmalloc(size); err = RT->GetVariable((char16_t *) name, (EFI_GUID *) vendor, NULL, &size, buf); if (err != EFI_SUCCESS) return err; if (ret) *ret = TAKE_PTR(buf); if (ret_size) *ret_size = size; return EFI_SUCCESS; } EFI_STATUS efivar_get_boolean_u8(const EFI_GUID *vendor, const char16_t *name, bool *ret) { _cleanup_free_ char *b = NULL; size_t size; EFI_STATUS err; assert(vendor); assert(name); err = efivar_get_raw(vendor, name, &b, &size); if (err != EFI_SUCCESS) return err; if (ret) *ret = *b > 0; return EFI_SUCCESS; } void efivar_set_time_usec(const EFI_GUID *vendor, const char16_t *name, uint64_t usec) { assert(vendor); assert(name); if (usec == 0) usec = time_usec(); if (usec == 0) return; _cleanup_free_ char16_t *str = xasprintf("%" PRIu64, usec); efivar_set(vendor, name, str, 0); } void convert_efi_path(char16_t *path) { assert(path); for (size_t i = 0, fixed = 0;; i++) { /* Fix device path node separator. */ path[fixed] = (path[i] == '/') ? '\\' : path[i]; /* Double '\' is not allowed in EFI file paths. */ if (fixed > 0 && path[fixed - 1] == '\\' && path[fixed] == '\\') continue; if (path[i] == '\0') break; fixed++; } } char16_t *xstr8_to_path(const char *str8) { assert(str8); char16_t *path = xstr8_to_16(str8); convert_efi_path(path); return path; } void mangle_stub_cmdline(char16_t *cmdline) { char16_t *p = cmdline; if (!cmdline) return; for (; *cmdline != '\0'; cmdline++) /* Convert ASCII control characters to spaces. */ if (*cmdline <= 0x1F) *cmdline = ' '; /* chomp the trailing whitespaces */ while (cmdline != p) { --cmdline; if (*cmdline != ' ') break; *cmdline = '\0'; } } EFI_STATUS chunked_read(EFI_FILE *file, size_t *size, void *buf) { EFI_STATUS err; assert(file); assert(size); assert(buf); /* This is a drop-in replacement for EFI_FILE->Read() with the same API behavior. * Some broken firmwares cannot handle large file reads and will instead return * an error. As a workaround, read such files in small chunks. * Note that we cannot just try reading the whole file first on such firmware as * that will permanently break the handle even if it is re-opened. * * https://github.com/systemd/systemd/issues/25911 */ if (*size == 0) return EFI_SUCCESS; size_t read = 0, remaining = *size; while (remaining > 0) { size_t chunk = MIN(1024U * 1024U, remaining); err = file->Read(file, &chunk, (uint8_t *) buf + read); if (err != EFI_SUCCESS) return err; if (chunk == 0) /* Caller requested more bytes than are in file. */ break; assert(chunk <= remaining); read += chunk; remaining -= chunk; } *size = read; return EFI_SUCCESS; } EFI_STATUS file_read(EFI_FILE *dir, const char16_t *name, size_t off, size_t size, char **ret, size_t *ret_size) { _cleanup_(file_closep) EFI_FILE *handle = NULL; _cleanup_free_ char *buf = NULL; EFI_STATUS err; assert(dir); assert(name); assert(ret); err = dir->Open(dir, &handle, (char16_t*) name, EFI_FILE_MODE_READ, 0ULL); if (err != EFI_SUCCESS) return err; if (size == 0) { _cleanup_free_ EFI_FILE_INFO *info = NULL; err = get_file_info(handle, &info, NULL); if (err != EFI_SUCCESS) return err; size = info->FileSize; } if (off > 0) { err = handle->SetPosition(handle, off); if (err != EFI_SUCCESS) return err; } /* Allocate some extra bytes to guarantee the result is NUL-terminated for char and char16_t strings. */ size_t extra = size % sizeof(char16_t) + sizeof(char16_t); buf = xmalloc(size + extra); err = chunked_read(handle, &size, buf); if (err != EFI_SUCCESS) return err; /* Note that chunked_read() changes size to reflect the actual bytes read. */ memset(buf + size, 0, extra); *ret = TAKE_PTR(buf); if (ret_size) *ret_size = size; return err; } void print_at(size_t x, size_t y, size_t attr, const char16_t *str) { assert(str); ST->ConOut->SetCursorPosition(ST->ConOut, x, y); ST->ConOut->SetAttribute(ST->ConOut, attr); ST->ConOut->OutputString(ST->ConOut, (char16_t *) str); } void clear_screen(size_t attr) { log_wait(); ST->ConOut->SetAttribute(ST->ConOut, attr); ST->ConOut->ClearScreen(ST->ConOut); } void sort_pointer_array( void **array, size_t n_members, compare_pointer_func_t compare) { assert(array || n_members == 0); assert(compare); if (n_members <= 1) return; for (size_t i = 1; i < n_members; i++) { size_t k; void *entry = array[i]; for (k = i; k > 0; k--) { if (compare(array[k - 1], entry) <= 0) break; array[k] = array[k - 1]; } array[k] = entry; } } EFI_STATUS get_file_info(EFI_FILE *handle, EFI_FILE_INFO **ret, size_t *ret_size) { size_t size = offsetof(EFI_FILE_INFO, FileName) + 256; _cleanup_free_ EFI_FILE_INFO *fi = NULL; EFI_STATUS err; assert(handle); assert(ret); fi = xmalloc(size); err = handle->GetInfo(handle, MAKE_GUID_PTR(EFI_FILE_INFO), &size, fi); if (err == EFI_BUFFER_TOO_SMALL) { free(fi); fi = xmalloc(size); /* GetInfo tells us the required size, let's use that now */ err = handle->GetInfo(handle, MAKE_GUID_PTR(EFI_FILE_INFO), &size, fi); } if (err != EFI_SUCCESS) return err; *ret = TAKE_PTR(fi); if (ret_size) *ret_size = size; return EFI_SUCCESS; } EFI_STATUS readdir( EFI_FILE *handle, EFI_FILE_INFO **buffer, size_t *buffer_size) { EFI_STATUS err; size_t sz; assert(handle); assert(buffer); assert(buffer_size); /* buffer/buffer_size are both in and output parameters. Should be zero-initialized initially, and * the specified buffer needs to be freed by caller, after final use. */ if (!*buffer) { /* Some broken firmware violates the EFI spec by still advancing the readdir * position when returning EFI_BUFFER_TOO_SMALL, effectively skipping over any files when * the buffer was too small. Therefore, start with a buffer that should handle FAT32 max * file name length. * As a side effect, most readdir() calls will now be slightly faster. */ sz = sizeof(EFI_FILE_INFO) + 256 * sizeof(char16_t); *buffer = xmalloc(sz); *buffer_size = sz; } else sz = *buffer_size; err = handle->Read(handle, &sz, *buffer); if (err == EFI_BUFFER_TOO_SMALL) { free(*buffer); *buffer = xmalloc(sz); *buffer_size = sz; err = handle->Read(handle, &sz, *buffer); } if (err != EFI_SUCCESS) return err; if (sz == 0) { /* End of directory */ free(*buffer); *buffer = NULL; *buffer_size = 0; } return EFI_SUCCESS; } bool is_ascii(const char16_t *f) { if (!f) return false; for (; *f != 0; f++) if (*f > 127) return false; return true; } char16_t **strv_free(char16_t **v) { if (!v) return NULL; for (char16_t **i = v; *i; i++) free(*i); free(v); return NULL; } EFI_STATUS open_directory( EFI_FILE *root, const char16_t *path, EFI_FILE **ret) { _cleanup_(file_closep) EFI_FILE *dir = NULL; _cleanup_free_ EFI_FILE_INFO *file_info = NULL; EFI_STATUS err; assert(root); /* Opens a file, and then verifies it is actually a directory */ err = root->Open(root, &dir, (char16_t *) path, EFI_FILE_MODE_READ, 0); if (err != EFI_SUCCESS) return err; err = get_file_info(dir, &file_info, NULL); if (err != EFI_SUCCESS) return err; if (!FLAGS_SET(file_info->Attribute, EFI_FILE_DIRECTORY)) return EFI_LOAD_ERROR; *ret = TAKE_PTR(dir); return EFI_SUCCESS; } uint64_t get_os_indications_supported(void) { uint64_t osind; EFI_STATUS err; /* Returns the supported OS indications. If we can't acquire it, returns a zeroed out mask, i.e. no * supported features. */ err = efivar_get_uint64_le(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"OsIndicationsSupported", &osind); if (err != EFI_SUCCESS) return 0; return osind; } __attribute__((noinline)) void notify_debugger(const char *identity, volatile bool wait) { #ifdef EFI_DEBUG printf("%s@%p %s\n", identity, &__ImageBase, GIT_VERSION); if (wait) printf("Waiting for debugger to attach...\n"); /* This is a poor programmer's breakpoint to wait until a debugger * has attached to us. Just "set variable wait = 0" or "return" to continue. */ while (wait) /* Prefer asm based stalling so that gdb has a source location to present. */ # if defined(__i386__) || defined(__x86_64__) asm volatile("pause"); # elif defined(__aarch64__) asm volatile("wfi"); # else BS->Stall(5000); # endif #endif } #if defined(__i386__) || defined(__x86_64__) static inline uint8_t inb(uint16_t port) { uint8_t value; asm volatile("inb %1, %0" : "=a"(value) : "Nd"(port)); return value; } static inline void outb(uint16_t port, uint8_t value) { asm volatile("outb %0, %1" : : "a"(value), "Nd"(port)); } void beep(unsigned beep_count) { enum { PITCH = 500, BEEP_DURATION_USEC = 100 * 1000, WAIT_DURATION_USEC = 400 * 1000, PIT_FREQUENCY = 0x1234dd, SPEAKER_CONTROL_PORT = 0x61, SPEAKER_ON_MASK = 0x03, TIMER_PORT_MAGIC = 0xB6, TIMER_CONTROL_PORT = 0x43, TIMER_CONTROL2_PORT = 0x42, }; /* Set frequency. */ uint32_t counter = PIT_FREQUENCY / PITCH; outb(TIMER_CONTROL_PORT, TIMER_PORT_MAGIC); outb(TIMER_CONTROL2_PORT, counter & 0xFF); outb(TIMER_CONTROL2_PORT, (counter >> 8) & 0xFF); uint8_t value = inb(SPEAKER_CONTROL_PORT); while (beep_count > 0) { /* Turn speaker on. */ value |= SPEAKER_ON_MASK; outb(SPEAKER_CONTROL_PORT, value); BS->Stall(BEEP_DURATION_USEC); /* Turn speaker off. */ value &= ~SPEAKER_ON_MASK; outb(SPEAKER_CONTROL_PORT, value); beep_count--; if (beep_count > 0) BS->Stall(WAIT_DURATION_USEC); } } #endif EFI_STATUS open_volume(EFI_HANDLE device, EFI_FILE **ret_file) { EFI_STATUS err; EFI_FILE *file; EFI_SIMPLE_FILE_SYSTEM_PROTOCOL *volume; assert(ret_file); err = BS->HandleProtocol(device, MAKE_GUID_PTR(EFI_SIMPLE_FILE_SYSTEM_PROTOCOL), (void **) &volume); if (err != EFI_SUCCESS) return err; err = volume->OpenVolume(volume, &file); if (err != EFI_SUCCESS) return err; *ret_file = file; return EFI_SUCCESS; } void *find_configuration_table(const EFI_GUID *guid) { for (size_t i = 0; i < ST->NumberOfTableEntries; i++) if (efi_guid_equal(&ST->ConfigurationTable[i].VendorGuid, guid)) return ST->ConfigurationTable[i].VendorTable; return NULL; } char16_t *get_extra_dir(const EFI_DEVICE_PATH *file_path) { if (!file_path) return NULL; /* A device path is allowed to have more than one file path node. If that is the case they are * supposed to be concatenated. Unfortunately, the device path to text protocol simply converts the * nodes individually and then combines those with the usual '/' for device path nodes. But this does * not create a legal EFI file path that the file protocol can use. */ /* Make sure we really only got file paths. */ for (const EFI_DEVICE_PATH *node = file_path; !device_path_is_end(node); node = device_path_next_node(node)) if (node->Type != MEDIA_DEVICE_PATH || node->SubType != MEDIA_FILEPATH_DP) return NULL; _cleanup_free_ char16_t *file_path_str = NULL; if (device_path_to_str(file_path, &file_path_str) != EFI_SUCCESS) return NULL; convert_efi_path(file_path_str); return xasprintf("%ls.extra.d", file_path_str); }
20,623
29.736215
119
c
null
systemd-main/src/boot/efi/util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "efi.h" #include "log.h" #include "proto/file-io.h" #include "string-util-fundamental.h" /* This is provided by linker script. */ extern uint8_t __ImageBase; static inline void free(void *p) { if (!p) return; /* Debugging an invalid free requires trace logging to find the call site or a debugger attached. For * release builds it is not worth the bother to even warn when we cannot even print a call stack. */ #ifdef EFI_DEBUG assert_se(BS->FreePool(p) == EFI_SUCCESS); #else (void) BS->FreePool(p); #endif } static inline void freep(void *p) { free(*(void **) p); } #define _cleanup_free_ _cleanup_(freep) _malloc_ _alloc_(1) _returns_nonnull_ _warn_unused_result_ static inline void *xmalloc(size_t size) { void *p; assert_se(BS->AllocatePool(EfiLoaderData, size, &p) == EFI_SUCCESS); return p; } _malloc_ _alloc_(1, 2) _returns_nonnull_ _warn_unused_result_ static inline void *xmalloc_multiply(size_t size, size_t n) { assert_se(!__builtin_mul_overflow(size, n, &size)); return xmalloc(size); } /* Use malloc attribute as this never returns p like userspace realloc. */ _malloc_ _alloc_(3) _returns_nonnull_ _warn_unused_result_ static inline void *xrealloc(void *p, size_t old_size, size_t new_size) { void *t = xmalloc(new_size); new_size = MIN(old_size, new_size); if (new_size > 0) memcpy(t, p, new_size); free(p); return t; } #define xnew(type, n) ((type *) xmalloc_multiply(sizeof(type), (n))) typedef struct { EFI_PHYSICAL_ADDRESS addr; size_t n_pages; } Pages; static inline void cleanup_pages(Pages *p) { if (p->n_pages == 0) return; #ifdef EFI_DEBUG assert_se(BS->FreePages(p->addr, p->n_pages) == EFI_SUCCESS); #else (void) BS->FreePages(p->addr, p->n_pages); #endif } #define _cleanup_pages_ _cleanup_(cleanup_pages) static inline Pages xmalloc_pages( EFI_ALLOCATE_TYPE type, EFI_MEMORY_TYPE memory_type, size_t n_pages, EFI_PHYSICAL_ADDRESS addr) { assert_se(BS->AllocatePages(type, memory_type, n_pages, &addr) == EFI_SUCCESS); return (Pages) { .addr = addr, .n_pages = n_pages, }; } EFI_STATUS parse_boolean(const char *v, bool *b); EFI_STATUS efivar_set(const EFI_GUID *vendor, const char16_t *name, const char16_t *value, uint32_t flags); EFI_STATUS efivar_set_raw(const EFI_GUID *vendor, const char16_t *name, const void *buf, size_t size, uint32_t flags); EFI_STATUS efivar_set_uint_string(const EFI_GUID *vendor, const char16_t *name, size_t i, uint32_t flags); EFI_STATUS efivar_set_uint32_le(const EFI_GUID *vendor, const char16_t *NAME, uint32_t value, uint32_t flags); EFI_STATUS efivar_set_uint64_le(const EFI_GUID *vendor, const char16_t *name, uint64_t value, uint32_t flags); void efivar_set_time_usec(const EFI_GUID *vendor, const char16_t *name, uint64_t usec); EFI_STATUS efivar_get(const EFI_GUID *vendor, const char16_t *name, char16_t **ret); EFI_STATUS efivar_get_raw(const EFI_GUID *vendor, const char16_t *name, char **ret, size_t *ret_size); EFI_STATUS efivar_get_uint_string(const EFI_GUID *vendor, const char16_t *name, size_t *ret); EFI_STATUS efivar_get_uint32_le(const EFI_GUID *vendor, const char16_t *name, uint32_t *ret); EFI_STATUS efivar_get_uint64_le(const EFI_GUID *vendor, const char16_t *name, uint64_t *ret); EFI_STATUS efivar_get_boolean_u8(const EFI_GUID *vendor, const char16_t *name, bool *ret); void convert_efi_path(char16_t *path); char16_t *xstr8_to_path(const char *stra); void mangle_stub_cmdline(char16_t *cmdline); EFI_STATUS chunked_read(EFI_FILE *file, size_t *size, void *buf); EFI_STATUS file_read(EFI_FILE *dir, const char16_t *name, size_t off, size_t size, char **content, size_t *content_size); static inline void file_closep(EFI_FILE **handle) { if (!*handle) return; (*handle)->Close(*handle); } static inline void unload_imagep(EFI_HANDLE *image) { if (*image) (void) BS->UnloadImage(*image); } /* * Allocated random UUID, intended to be shared across tools that implement * the (ESP)\loader\entries\<vendor>-<revision>.conf convention and the * associated EFI variables. */ #define LOADER_GUID \ { 0x4a67b082, 0x0a4c, 0x41cf, { 0xb6, 0xc7, 0x44, 0x0b, 0x29, 0xbb, 0x8c, 0x4f } } /* Note that GUID is evaluated multiple times! */ #define GUID_FORMAT_STR "%08X-%04X-%04X-%02X%02X-%02X%02X%02X%02X%02X%02X" #define GUID_FORMAT_VAL(g) (g).Data1, (g).Data2, (g).Data3, (g).Data4[0], (g).Data4[1], \ (g).Data4[2], (g).Data4[3], (g).Data4[4], (g).Data4[5], (g).Data4[6], (g).Data4[7] void print_at(size_t x, size_t y, size_t attr, const char16_t *str); void clear_screen(size_t attr); typedef int (*compare_pointer_func_t)(const void *a, const void *b); void sort_pointer_array(void **array, size_t n_members, compare_pointer_func_t compare); EFI_STATUS get_file_info(EFI_FILE *handle, EFI_FILE_INFO **ret, size_t *ret_size); EFI_STATUS readdir(EFI_FILE *handle, EFI_FILE_INFO **buffer, size_t *buffer_size); bool is_ascii(const char16_t *f); char16_t **strv_free(char16_t **l); static inline void strv_freep(char16_t ***p) { strv_free(*p); } EFI_STATUS open_directory(EFI_FILE *root_dir, const char16_t *path, EFI_FILE **ret); /* Conversion between EFI_PHYSICAL_ADDRESS and pointers is not obvious. The former is always 64-bit, even on * 32-bit archs. And gcc complains if we cast a pointer to an integer of a different size. Hence let's do the * conversion indirectly: first into uintptr_t and then extended to EFI_PHYSICAL_ADDRESS. */ static inline EFI_PHYSICAL_ADDRESS POINTER_TO_PHYSICAL_ADDRESS(const void *p) { return (EFI_PHYSICAL_ADDRESS) (uintptr_t) p; } static inline void *PHYSICAL_ADDRESS_TO_POINTER(EFI_PHYSICAL_ADDRESS addr) { /* On 32-bit systems the address might not be convertible (as pointers are 32-bit but * EFI_PHYSICAL_ADDRESS 64-bit) */ assert(addr <= UINTPTR_MAX); return (void *) (uintptr_t) addr; } uint64_t get_os_indications_supported(void); /* If EFI_DEBUG, print our name and version and also report the address of the image base so a debugger can * be attached. See debug-sd-boot.sh for how this can be done. */ void notify_debugger(const char *identity, bool wait); /* On x86 the compiler assumes a different incoming stack alignment than what we get. * This will cause long long variables to be misaligned when building with * '-mlong-double' (for correct struct layouts). Normally, the compiler realigns the * stack itself on entry, but we have to do this ourselves here as the compiler does * not know that this is our entry point. */ #ifdef __i386__ # define _realign_stack_ __attribute__((force_align_arg_pointer)) #else # define _realign_stack_ #endif #define DEFINE_EFI_MAIN_FUNCTION(func, identity, wait_for_debugger) \ EFI_SYSTEM_TABLE *ST; \ EFI_BOOT_SERVICES *BS; \ EFI_RUNTIME_SERVICES *RT; \ _realign_stack_ \ EFIAPI EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *system_table); \ EFIAPI EFI_STATUS efi_main(EFI_HANDLE image, EFI_SYSTEM_TABLE *system_table) { \ ST = system_table; \ BS = system_table->BootServices; \ RT = system_table->RuntimeServices; \ __stack_chk_guard_init(); \ notify_debugger((identity), (wait_for_debugger)); \ EFI_STATUS err = func(image); \ log_wait(); \ return err; \ } #if defined(__i386__) || defined(__x86_64__) void beep(unsigned beep_count); #else static inline void beep(unsigned beep_count) {} #endif EFI_STATUS open_volume(EFI_HANDLE device, EFI_FILE **ret_file); static inline bool efi_guid_equal(const EFI_GUID *a, const EFI_GUID *b) { return memcmp(a, b, sizeof(EFI_GUID)) == 0; } void *find_configuration_table(const EFI_GUID *guid); char16_t *get_extra_dir(const EFI_DEVICE_PATH *file_path);
8,791
40.276995
121
h