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/fundamental/macro-fundamental.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #if !SD_BOOT # include <assert.h> #endif #include <limits.h> #include <stdalign.h> #include <stdbool.h> #include <stddef.h> #include <stdint.h> #define _align_(x) __attribute__((__aligned__(x))) #define _alignas_(x) __attribute__((__aligned__(alignof(x)))) #define _alignptr_ __attribute__((__aligned__(sizeof(void *)))) #define _cleanup_(x) __attribute__((__cleanup__(x))) #define _const_ __attribute__((__const__)) #define _deprecated_ __attribute__((__deprecated__)) #define _destructor_ __attribute__((__destructor__)) #define _hidden_ __attribute__((__visibility__("hidden"))) #define _likely_(x) (__builtin_expect(!!(x), 1)) #define _malloc_ __attribute__((__malloc__)) #define _noinline_ __attribute__((noinline)) #define _noreturn_ _Noreturn #define _packed_ __attribute__((__packed__)) #define _printf_(a, b) __attribute__((__format__(printf, a, b))) #define _public_ __attribute__((__visibility__("default"))) #define _pure_ __attribute__((__pure__)) #define _retain_ __attribute__((__retain__)) #define _returns_nonnull_ __attribute__((__returns_nonnull__)) #define _section_(x) __attribute__((__section__(x))) #define _sentinel_ __attribute__((__sentinel__)) #define _unlikely_(x) (__builtin_expect(!!(x), 0)) #define _unused_ __attribute__((__unused__)) #define _used_ __attribute__((__used__)) #define _warn_unused_result_ __attribute__((__warn_unused_result__)) #define _weak_ __attribute__((__weak__)) #define _weakref_(x) __attribute__((__weakref__(#x))) #ifdef __clang__ # define _alloc_(...) #else # define _alloc_(...) __attribute__((__alloc_size__(__VA_ARGS__))) #endif #if __GNUC__ >= 7 || (defined(__clang__) && __clang_major__ >= 10) # define _fallthrough_ __attribute__((__fallthrough__)) #else # define _fallthrough_ #endif #define XSTRINGIFY(x) #x #define STRINGIFY(x) XSTRINGIFY(x) #ifndef __COVERITY__ # define VOID_0 ((void)0) #else # define VOID_0 ((void*)0) #endif #define ELEMENTSOF(x) \ (__builtin_choose_expr( \ !__builtin_types_compatible_p(typeof(x), typeof(&*(x))), \ sizeof(x)/sizeof((x)[0]), \ VOID_0)) #define XCONCATENATE(x, y) x ## y #define CONCATENATE(x, y) XCONCATENATE(x, y) #if SD_BOOT _noreturn_ void efi_assert(const char *expr, const char *file, unsigned line, const char *function); #ifdef NDEBUG #define assert(expr) #define assert_not_reached() __builtin_unreachable() #else #define assert(expr) ({ _likely_(expr) ? VOID_0 : efi_assert(#expr, __FILE__, __LINE__, __func__); }) #define assert_not_reached() efi_assert("Code should not be reached", __FILE__, __LINE__, __func__) #endif #define static_assert _Static_assert #define assert_se(expr) ({ _likely_(expr) ? VOID_0 : efi_assert(#expr, __FILE__, __LINE__, __func__); }) #endif /* This passes the argument through after (if asserts are enabled) checking that it is not null. */ #define ASSERT_PTR(expr) _ASSERT_PTR(expr, UNIQ_T(_expr_, UNIQ), assert) #define ASSERT_SE_PTR(expr) _ASSERT_PTR(expr, UNIQ_T(_expr_, UNIQ), assert_se) #define _ASSERT_PTR(expr, var, check) \ ({ \ typeof(expr) var = (expr); \ check(var); \ var; \ }) #define ASSERT_NONNEG(expr) \ ({ \ typeof(expr) _expr_ = (expr), _zero = 0; \ assert(_expr_ >= _zero); \ _expr_; \ }) #define ASSERT_SE_NONNEG(expr) \ ({ \ typeof(expr) _expr_ = (expr), _zero = 0; \ assert_se(_expr_ >= _zero); \ _expr_; \ }) #define assert_cc(expr) static_assert(expr, #expr) #define UNIQ_T(x, uniq) CONCATENATE(__unique_prefix_, CONCATENATE(x, uniq)) #define UNIQ __COUNTER__ /* Note that this works differently from pthread_once(): this macro does * not synchronize code execution, i.e. code that is run conditionalized * on this macro will run concurrently to all other code conditionalized * the same way, there's no ordering or completion enforced. */ #define ONCE __ONCE(UNIQ_T(_once_, UNIQ)) #define __ONCE(o) \ ({ \ static bool (o) = false; \ __atomic_exchange_n(&(o), true, __ATOMIC_SEQ_CST); \ }) #undef MAX #define MAX(a, b) __MAX(UNIQ, (a), UNIQ, (b)) #define __MAX(aq, a, bq, b) \ ({ \ const typeof(a) UNIQ_T(A, aq) = (a); \ const typeof(b) UNIQ_T(B, bq) = (b); \ UNIQ_T(A, aq) > UNIQ_T(B, bq) ? UNIQ_T(A, aq) : UNIQ_T(B, bq); \ }) #define IS_UNSIGNED_INTEGER_TYPE(type) \ (__builtin_types_compatible_p(typeof(type), unsigned char) || \ __builtin_types_compatible_p(typeof(type), unsigned short) || \ __builtin_types_compatible_p(typeof(type), unsigned) || \ __builtin_types_compatible_p(typeof(type), unsigned long) || \ __builtin_types_compatible_p(typeof(type), unsigned long long)) #define IS_SIGNED_INTEGER_TYPE(type) \ (__builtin_types_compatible_p(typeof(type), signed char) || \ __builtin_types_compatible_p(typeof(type), signed short) || \ __builtin_types_compatible_p(typeof(type), signed) || \ __builtin_types_compatible_p(typeof(type), signed long) || \ __builtin_types_compatible_p(typeof(type), signed long long)) /* Evaluates to (void) if _A or _B are not constant or of different types (being integers of different sizes * is also OK as long as the signedness matches) */ #define CONST_MAX(_A, _B) \ (__builtin_choose_expr( \ __builtin_constant_p(_A) && \ __builtin_constant_p(_B) && \ (__builtin_types_compatible_p(typeof(_A), typeof(_B)) || \ (IS_UNSIGNED_INTEGER_TYPE(_A) && IS_UNSIGNED_INTEGER_TYPE(_B)) || \ (IS_SIGNED_INTEGER_TYPE(_A) && IS_SIGNED_INTEGER_TYPE(_B))), \ ((_A) > (_B)) ? (_A) : (_B), \ VOID_0)) /* takes two types and returns the size of the larger one */ #define MAXSIZE(A, B) (sizeof(union _packed_ { typeof(A) a; typeof(B) b; })) #define MAX3(x, y, z) \ ({ \ const typeof(x) _c = MAX(x, y); \ MAX(_c, z); \ }) #define MAX4(x, y, z, a) \ ({ \ const typeof(x) _d = MAX3(x, y, z); \ MAX(_d, a); \ }) #undef MIN #define MIN(a, b) __MIN(UNIQ, (a), UNIQ, (b)) #define __MIN(aq, a, bq, b) \ ({ \ const typeof(a) UNIQ_T(A, aq) = (a); \ const typeof(b) UNIQ_T(B, bq) = (b); \ UNIQ_T(A, aq) < UNIQ_T(B, bq) ? UNIQ_T(A, aq) : UNIQ_T(B, bq); \ }) /* evaluates to (void) if _A or _B are not constant or of different types */ #define CONST_MIN(_A, _B) \ (__builtin_choose_expr( \ __builtin_constant_p(_A) && \ __builtin_constant_p(_B) && \ __builtin_types_compatible_p(typeof(_A), typeof(_B)), \ ((_A) < (_B)) ? (_A) : (_B), \ VOID_0)) #define MIN3(x, y, z) \ ({ \ const typeof(x) _c = MIN(x, y); \ MIN(_c, z); \ }) /* Returns true if the passed integer is a positive power of two */ #define CONST_ISPOWEROF2(x) \ ((x) > 0 && ((x) & ((x) - 1)) == 0) #define ISPOWEROF2(x) \ __builtin_choose_expr( \ __builtin_constant_p(x), \ CONST_ISPOWEROF2(x), \ ({ \ const typeof(x) _x = (x); \ CONST_ISPOWEROF2(_x); \ })) #define LESS_BY(a, b) __LESS_BY(UNIQ, (a), UNIQ, (b)) #define __LESS_BY(aq, a, bq, b) \ ({ \ const typeof(a) UNIQ_T(A, aq) = (a); \ const typeof(b) UNIQ_T(B, bq) = (b); \ UNIQ_T(A, aq) > UNIQ_T(B, bq) ? UNIQ_T(A, aq) - UNIQ_T(B, bq) : 0; \ }) #define CMP(a, b) __CMP(UNIQ, (a), UNIQ, (b)) #define __CMP(aq, a, bq, b) \ ({ \ const typeof(a) UNIQ_T(A, aq) = (a); \ const typeof(b) UNIQ_T(B, bq) = (b); \ UNIQ_T(A, aq) < UNIQ_T(B, bq) ? -1 : \ UNIQ_T(A, aq) > UNIQ_T(B, bq) ? 1 : 0; \ }) #undef CLAMP #define CLAMP(x, low, high) __CLAMP(UNIQ, (x), UNIQ, (low), UNIQ, (high)) #define __CLAMP(xq, x, lowq, low, highq, high) \ ({ \ const typeof(x) UNIQ_T(X, xq) = (x); \ const typeof(low) UNIQ_T(LOW, lowq) = (low); \ const typeof(high) UNIQ_T(HIGH, highq) = (high); \ UNIQ_T(X, xq) > UNIQ_T(HIGH, highq) ? \ UNIQ_T(HIGH, highq) : \ UNIQ_T(X, xq) < UNIQ_T(LOW, lowq) ? \ UNIQ_T(LOW, lowq) : \ UNIQ_T(X, xq); \ }) /* [(x + y - 1) / y] suffers from an integer overflow, even though the * computation should be possible in the given type. Therefore, we use * [x / y + !!(x % y)]. Note that on "Real CPUs" a division returns both the * quotient and the remainder, so both should be equally fast. */ #define DIV_ROUND_UP(x, y) __DIV_ROUND_UP(UNIQ, (x), UNIQ, (y)) #define __DIV_ROUND_UP(xq, x, yq, y) \ ({ \ const typeof(x) UNIQ_T(X, xq) = (x); \ const typeof(y) UNIQ_T(Y, yq) = (y); \ (UNIQ_T(X, xq) / UNIQ_T(Y, yq) + !!(UNIQ_T(X, xq) % UNIQ_T(Y, yq))); \ }) /* Rounds up x to the next multiple of y. Resolves to typeof(x) -1 in case of overflow */ #define __ROUND_UP(q, x, y) \ ({ \ const typeof(y) UNIQ_T(A, q) = (y); \ const typeof(x) UNIQ_T(B, q) = DIV_ROUND_UP((x), UNIQ_T(A, q)); \ typeof(x) UNIQ_T(C, q); \ __builtin_mul_overflow(UNIQ_T(B, q), UNIQ_T(A, q), &UNIQ_T(C, q)) ? (typeof(x)) -1 : UNIQ_T(C, q); \ }) #define ROUND_UP(x, y) __ROUND_UP(UNIQ, (x), (y)) #define CASE_F_1(X) case X: #define CASE_F_2(X, ...) case X: CASE_F_1( __VA_ARGS__) #define CASE_F_3(X, ...) case X: CASE_F_2( __VA_ARGS__) #define CASE_F_4(X, ...) case X: CASE_F_3( __VA_ARGS__) #define CASE_F_5(X, ...) case X: CASE_F_4( __VA_ARGS__) #define CASE_F_6(X, ...) case X: CASE_F_5( __VA_ARGS__) #define CASE_F_7(X, ...) case X: CASE_F_6( __VA_ARGS__) #define CASE_F_8(X, ...) case X: CASE_F_7( __VA_ARGS__) #define CASE_F_9(X, ...) case X: CASE_F_8( __VA_ARGS__) #define CASE_F_10(X, ...) case X: CASE_F_9( __VA_ARGS__) #define CASE_F_11(X, ...) case X: CASE_F_10( __VA_ARGS__) #define CASE_F_12(X, ...) case X: CASE_F_11( __VA_ARGS__) #define CASE_F_13(X, ...) case X: CASE_F_12( __VA_ARGS__) #define CASE_F_14(X, ...) case X: CASE_F_13( __VA_ARGS__) #define CASE_F_15(X, ...) case X: CASE_F_14( __VA_ARGS__) #define CASE_F_16(X, ...) case X: CASE_F_15( __VA_ARGS__) #define CASE_F_17(X, ...) case X: CASE_F_16( __VA_ARGS__) #define CASE_F_18(X, ...) case X: CASE_F_17( __VA_ARGS__) #define CASE_F_19(X, ...) case X: CASE_F_18( __VA_ARGS__) #define CASE_F_20(X, ...) case X: CASE_F_19( __VA_ARGS__) #define GET_CASE_F(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,_20,NAME,...) NAME #define FOR_EACH_MAKE_CASE(...) \ GET_CASE_F(__VA_ARGS__,CASE_F_20,CASE_F_19,CASE_F_18,CASE_F_17,CASE_F_16,CASE_F_15,CASE_F_14,CASE_F_13,CASE_F_12,CASE_F_11, \ CASE_F_10,CASE_F_9,CASE_F_8,CASE_F_7,CASE_F_6,CASE_F_5,CASE_F_4,CASE_F_3,CASE_F_2,CASE_F_1) \ (__VA_ARGS__) #define IN_SET(x, first, ...) \ ({ \ bool _found = false; \ /* If the build breaks in the line below, you need to extend the case macros. We use typeof(+x) \ * here to widen the type of x if it is a bit-field as this would otherwise be illegal. */ \ static const typeof(+x) __assert_in_set[] _unused_ = { first, __VA_ARGS__ }; \ assert_cc(ELEMENTSOF(__assert_in_set) <= 20); \ switch (x) { \ FOR_EACH_MAKE_CASE(first, __VA_ARGS__) \ _found = true; \ break; \ default: \ break; \ } \ _found; \ }) /* Takes inspiration from Rust's Option::take() method: reads and returns a pointer, but at the same time * resets it to NULL. See: https://doc.rust-lang.org/std/option/enum.Option.html#method.take */ #define TAKE_GENERIC(var, type, nullvalue) \ ({ \ type *_pvar_ = &(var); \ type _var_ = *_pvar_; \ type _nullvalue_ = nullvalue; \ *_pvar_ = _nullvalue_; \ _var_; \ }) #define TAKE_PTR_TYPE(ptr, type) TAKE_GENERIC(ptr, type, NULL) #define TAKE_PTR(ptr) TAKE_PTR_TYPE(ptr, typeof(ptr)) #define TAKE_STRUCT_TYPE(s, type) TAKE_GENERIC(s, type, {}) #define TAKE_STRUCT(s) TAKE_STRUCT_TYPE(s, typeof(s)) /* * STRLEN - return the length of a string literal, minus the trailing NUL byte. * Contrary to strlen(), this is a constant expression. * @x: a string literal. */ #define STRLEN(x) (sizeof(""x"") - sizeof(typeof(x[0]))) #define mfree(memory) \ ({ \ free(memory); \ (typeof(memory)) NULL; \ }) static inline size_t ALIGN_TO(size_t l, size_t ali) { assert(ISPOWEROF2(ali)); if (l > SIZE_MAX - (ali - 1)) return SIZE_MAX; /* indicate overflow */ return ((l + ali - 1) & ~(ali - 1)); } #define ALIGN2(l) ALIGN_TO(l, 2) #define ALIGN4(l) ALIGN_TO(l, 4) #define ALIGN8(l) ALIGN_TO(l, 8) #define ALIGN2_PTR(p) ((void*) ALIGN2((uintptr_t) p)) #define ALIGN4_PTR(p) ((void*) ALIGN4((uintptr_t) p)) #define ALIGN8_PTR(p) ((void*) ALIGN8((uintptr_t) p)) #define ALIGN(l) ALIGN_TO(l, sizeof(void*)) #define ALIGN_PTR(p) ((void*) ALIGN((uintptr_t) (p))) /* Checks if the specified pointer is aligned as appropriate for the specific type */ #define IS_ALIGNED16(p) (((uintptr_t) p) % alignof(uint16_t) == 0) #define IS_ALIGNED32(p) (((uintptr_t) p) % alignof(uint32_t) == 0) #define IS_ALIGNED64(p) (((uintptr_t) p) % alignof(uint64_t) == 0) /* Same as ALIGN_TO but callable in constant contexts. */ #define CONST_ALIGN_TO(l, ali) \ __builtin_choose_expr( \ __builtin_constant_p(l) && \ __builtin_constant_p(ali) && \ CONST_ISPOWEROF2(ali) && \ (l <= SIZE_MAX - (ali - 1)), /* overflow? */ \ ((l) + (ali) - 1) & ~((ali) - 1), \ VOID_0) /* Similar to ((t *) (void *) (p)) to cast a pointer. The macro asserts that the pointer has a suitable * alignment for type "t". This exists for places where otherwise "-Wcast-align=strict" would issue a * warning or if you want to assert that the cast gives a pointer of suitable alignment. */ #define CAST_ALIGN_PTR(t, p) \ ({ \ const void *_p = (p); \ assert(((uintptr_t) _p) % alignof(t) == 0); \ (t *) _p; \ }) #define UPDATE_FLAG(orig, flag, b) \ ((b) ? ((orig) | (flag)) : ((orig) & ~(flag))) #define SET_FLAG(v, flag, b) \ (v) = UPDATE_FLAG(v, flag, b) #define FLAGS_SET(v, flags) \ ((~(v) & (flags)) == 0) /* Declare a flexible array usable in a union. * This is essentially a work-around for a pointless constraint in C99 * and might go away in some future version of the standard. * * See https://git.kernel.org/cgit/linux/kernel/git/torvalds/linux.git/commit/?id=3080ea5553cc909b000d1f1d964a9041962f2c5b */ #define DECLARE_FLEX_ARRAY(type, name) \ struct { \ dummy_t __empty__ ## name; \ type name[]; \ }
19,393
47.728643
133
h
null
systemd-main/src/fundamental/memory-util-fundamental.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stddef.h> #if SD_BOOT # include "efi-string.h" #else # include <string.h> #endif #include "macro-fundamental.h" #if !SD_BOOT && HAVE_EXPLICIT_BZERO static inline void *explicit_bzero_safe(void *p, size_t l) { if (p && l > 0) explicit_bzero(p, l); return p; } #else static inline void *explicit_bzero_safe(void *p, size_t l) { if (p && l > 0) { memset(p, 0, l); __asm__ __volatile__("" : : "r"(p) : "memory"); } return p; } #endif struct VarEraser { /* NB: This is a pointer to memory to erase in case of CLEANUP_ERASE(). Pointer to pointer to memory * to erase in case of CLEANUP_ERASE_PTR() */ void *p; size_t size; }; static inline void erase_var(struct VarEraser *e) { explicit_bzero_safe(e->p, e->size); } /* Mark var to be erased when leaving scope. */ #define CLEANUP_ERASE(var) \ _cleanup_(erase_var) _unused_ struct VarEraser CONCATENATE(_eraser_, UNIQ) = { \ .p = &(var), \ .size = sizeof(var), \ } static inline void erase_varp(struct VarEraser *e) { /* Very similar to erase_var(), but assumes `p` is a pointer to a pointer whose memory shall be destructed. */ if (!e->p) return; explicit_bzero_safe(*(void**) e->p, e->size); } /* Mark pointer so that memory pointed to is erased when leaving scope. Note: this takes a pointer to the * specified pointer, instead of just a copy of it. This is to allow callers to invalidate the pointer after * use, if they like, disabling our automatic erasure (for example because they succeeded with whatever they * wanted to do and now intend to return the allocated buffer to their caller without it being erased). */ #define CLEANUP_ERASE_PTR(ptr, sz) \ _cleanup_(erase_varp) _unused_ struct VarEraser CONCATENATE(_eraser_, UNIQ) = { \ .p = (ptr), \ .size = (sz), \ }
2,318
33.61194
118
h
null
systemd-main/src/fundamental/sha256.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* Stolen from glibc and converted to our style. In glibc it comes with the following copyright blurb: */ /* Functions to compute SHA256 message digest of files or memory blocks. according to the definition of SHA256 in FIPS 180-2. Copyright (C) 2007-2022 Free Software Foundation, Inc. This file is part of the GNU C Library. The GNU C Library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. The GNU C 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 Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with the GNU C Library; if not, see <https://www.gnu.org/licenses/>. */ #include <stdbool.h> #if SD_BOOT # include "efi-string.h" #else # include <string.h> #endif #include "macro-fundamental.h" #include "sha256.h" #include "unaligned-fundamental.h" #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ # define SWAP(n) \ (((n) << 24) | (((n) & 0xff00) << 8) | (((n) >> 8) & 0xff00) | ((n) >> 24)) # define SWAP64(n) \ (((n) << 56) \ | (((n) & 0xff00) << 40) \ | (((n) & 0xff0000) << 24) \ | (((n) & 0xff000000) << 8) \ | (((n) >> 8) & 0xff000000) \ | (((n) >> 24) & 0xff0000) \ | (((n) >> 40) & 0xff00) \ | ((n) >> 56)) #else # define SWAP(n) (n) # define SWAP64(n) (n) #endif /* This array contains the bytes used to pad the buffer to the next 64-byte boundary. (FIPS 180-2:5.1.1) */ static const uint8_t fillbuf[64] = { 0x80, 0 /* , 0, 0, ... */ }; /* Constants for SHA256 from FIPS 180-2:4.2.2. */ static const uint32_t K[64] = { 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 }; static void sha256_process_block(const void *, size_t, struct sha256_ctx *); /* Initialize structure containing state of computation. (FIPS 180-2:5.3.2) */ void sha256_init_ctx(struct sha256_ctx *ctx) { assert(ctx); ctx->H[0] = 0x6a09e667; ctx->H[1] = 0xbb67ae85; ctx->H[2] = 0x3c6ef372; ctx->H[3] = 0xa54ff53a; ctx->H[4] = 0x510e527f; ctx->H[5] = 0x9b05688c; ctx->H[6] = 0x1f83d9ab; ctx->H[7] = 0x5be0cd19; ctx->total64 = 0; ctx->buflen = 0; } /* Process the remaining bytes in the internal buffer and the usual prolog according to the standard and write the result to RESBUF. */ uint8_t *sha256_finish_ctx(struct sha256_ctx *ctx, uint8_t resbuf[static SHA256_DIGEST_SIZE]) { /* Take yet unprocessed bytes into account. */ uint32_t bytes = ctx->buflen; size_t pad; assert(ctx); assert(resbuf); /* Now count remaining bytes. */ ctx->total64 += bytes; pad = bytes >= 56 ? 64 + 56 - bytes : 56 - bytes; memcpy(&ctx->buffer[bytes], fillbuf, pad); /* Put the 64-bit file length in *bits* at the end of the buffer. */ ctx->buffer32[(bytes + pad + 4) / 4] = SWAP(ctx->total[TOTAL64_low] << 3); ctx->buffer32[(bytes + pad) / 4] = SWAP((ctx->total[TOTAL64_high] << 3) | (ctx->total[TOTAL64_low] >> 29)); /* Process last bytes. */ sha256_process_block(ctx->buffer, bytes + pad + 8, ctx); /* Put result from CTX in first 32 bytes following RESBUF. */ for (size_t i = 0; i < 8; ++i) unaligned_write_ne32(resbuf + i * sizeof(uint32_t), SWAP(ctx->H[i])); return resbuf; } void sha256_process_bytes(const void *buffer, size_t len, struct sha256_ctx *ctx) { assert(buffer); assert(ctx); /* When we already have some bits in our internal buffer concatenate both inputs first. */ if (ctx->buflen != 0) { size_t left_over = ctx->buflen; size_t add = 128 - left_over > len ? len : 128 - left_over; memcpy(&ctx->buffer[left_over], buffer, add); ctx->buflen += add; if (ctx->buflen > 64) { sha256_process_block(ctx->buffer, ctx->buflen & ~63, ctx); ctx->buflen &= 63; /* The regions in the following copy operation cannot overlap. */ memcpy(ctx->buffer, &ctx->buffer[(left_over + add) & ~63], ctx->buflen); } buffer = (const char *) buffer + add; len -= add; } /* Process available complete blocks. */ if (len >= 64) { if (IS_ALIGNED32(buffer)) { sha256_process_block(buffer, len & ~63, ctx); buffer = (const char *) buffer + (len & ~63); len &= 63; } else while (len > 64) { memcpy(ctx->buffer, buffer, 64); sha256_process_block(ctx->buffer, 64, ctx); buffer = (const char *) buffer + 64; len -= 64; } } /* Move remaining bytes into internal buffer. */ if (len > 0) { size_t left_over = ctx->buflen; memcpy(&ctx->buffer[left_over], buffer, len); left_over += len; if (left_over >= 64) { sha256_process_block(ctx->buffer, 64, ctx); left_over -= 64; memcpy(ctx->buffer, &ctx->buffer[64], left_over); } ctx->buflen = left_over; } } /* Process LEN bytes of BUFFER, accumulating context into CTX. It is assumed that LEN % 64 == 0. */ static void sha256_process_block(const void *buffer, size_t len, struct sha256_ctx *ctx) { const uint32_t *words = ASSERT_PTR(buffer); size_t nwords = len / sizeof(uint32_t); assert(ctx); uint32_t a = ctx->H[0]; uint32_t b = ctx->H[1]; uint32_t c = ctx->H[2]; uint32_t d = ctx->H[3]; uint32_t e = ctx->H[4]; uint32_t f = ctx->H[5]; uint32_t g = ctx->H[6]; uint32_t h = ctx->H[7]; /* First increment the byte count. FIPS 180-2 specifies the possible length of the file up to 2^64 bits. Here we only compute the number of bytes. */ ctx->total64 += len; /* Process all bytes in the buffer with 64 bytes in each round of the loop. */ while (nwords > 0) { uint32_t W[64]; uint32_t a_save = a; uint32_t b_save = b; uint32_t c_save = c; uint32_t d_save = d; uint32_t e_save = e; uint32_t f_save = f; uint32_t g_save = g; uint32_t h_save = h; /* Operators defined in FIPS 180-2:4.1.2. */ #define Ch(x, y, z) ((x & y) ^ (~x & z)) #define Maj(x, y, z) ((x & y) ^ (x & z) ^ (y & z)) #define S0(x) (CYCLIC (x, 2) ^ CYCLIC (x, 13) ^ CYCLIC (x, 22)) #define S1(x) (CYCLIC (x, 6) ^ CYCLIC (x, 11) ^ CYCLIC (x, 25)) #define R0(x) (CYCLIC (x, 7) ^ CYCLIC (x, 18) ^ (x >> 3)) #define R1(x) (CYCLIC (x, 17) ^ CYCLIC (x, 19) ^ (x >> 10)) /* It is unfortunate that C does not provide an operator for cyclic rotation. Hope the C compiler is smart enough. */ #define CYCLIC(w, s) ((w >> s) | (w << (32 - s))) /* Compute the message schedule according to FIPS 180-2:6.2.2 step 2. */ for (size_t t = 0; t < 16; ++t) { W[t] = SWAP (*words); ++words; } for (size_t t = 16; t < 64; ++t) W[t] = R1 (W[t - 2]) + W[t - 7] + R0 (W[t - 15]) + W[t - 16]; /* The actual computation according to FIPS 180-2:6.2.2 step 3. */ for (size_t t = 0; t < 64; ++t) { uint32_t T1 = h + S1 (e) + Ch (e, f, g) + K[t] + W[t]; uint32_t T2 = S0 (a) + Maj (a, b, c); h = g; g = f; f = e; e = d + T1; d = c; c = b; b = a; a = T1 + T2; } /* Add the starting values of the context according to FIPS 180-2:6.2.2 step 4. */ a += a_save; b += b_save; c += c_save; d += d_save; e += e_save; f += f_save; g += g_save; h += h_save; /* Prepare for the next round. */ nwords -= 16; } /* Put checksum in context given as argument. */ ctx->H[0] = a; ctx->H[1] = b; ctx->H[2] = c; ctx->H[3] = d; ctx->H[4] = e; ctx->H[5] = f; ctx->H[6] = g; ctx->H[7] = h; } uint8_t* sha256_direct(const void *buffer, size_t sz, uint8_t result[static SHA256_DIGEST_SIZE]) { struct sha256_ctx ctx; sha256_init_ctx(&ctx); sha256_process_bytes(buffer, sz, &ctx); return sha256_finish_ctx(&ctx, result); }
10,778
36.688811
105
c
null
systemd-main/src/fundamental/sha256.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stddef.h> #include <stdint.h> #define SHA256_DIGEST_SIZE 32 struct sha256_ctx { uint32_t H[8]; union { uint64_t total64; #define TOTAL64_low (1 - (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__)) #define TOTAL64_high (__BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__) uint32_t total[2]; }; uint32_t buflen; union { uint8_t buffer[128]; /* NB: always correctly aligned for UINT32. */ uint32_t buffer32[32]; uint64_t buffer64[16]; }; }; void sha256_init_ctx(struct sha256_ctx *ctx); uint8_t *sha256_finish_ctx(struct sha256_ctx *ctx, uint8_t resbuf[static SHA256_DIGEST_SIZE]); void sha256_process_bytes(const void *buffer, size_t len, struct sha256_ctx *ctx); static inline void sha256_process_bytes_and_size(const void *buffer, size_t len, struct sha256_ctx *ctx) { sha256_process_bytes(&len, sizeof(len), ctx); sha256_process_bytes(buffer, len, ctx); } uint8_t* sha256_direct(const void *buffer, size_t sz, uint8_t result[static SHA256_DIGEST_SIZE]); #define SHA256_DIRECT(buffer, sz) sha256_direct(buffer, sz, (uint8_t[SHA256_DIGEST_SIZE]) {})
1,262
30.575
106
h
null
systemd-main/src/fundamental/string-util-fundamental.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #if !SD_BOOT # include <ctype.h> #endif #include "macro-fundamental.h" #include "string-util-fundamental.h" sd_char *startswith(const sd_char *s, const sd_char *prefix) { size_t l; assert(s); assert(prefix); l = strlen(prefix); if (!strneq(s, prefix, l)) return NULL; return (sd_char*) s + l; } sd_char *startswith_no_case(const sd_char *s, const sd_char *prefix) { size_t l; assert(s); assert(prefix); l = strlen(prefix); if (!strncaseeq(s, prefix, l)) return NULL; return (sd_char*) s + l; } sd_char* endswith(const sd_char *s, const sd_char *postfix) { size_t sl, pl; assert(s); assert(postfix); sl = strlen(s); pl = strlen(postfix); if (pl == 0) return (sd_char*) s + sl; if (sl < pl) return NULL; if (strcmp(s + sl - pl, postfix) != 0) return NULL; return (sd_char*) s + sl - pl; } sd_char* endswith_no_case(const sd_char *s, const sd_char *postfix) { size_t sl, pl; assert(s); assert(postfix); sl = strlen(s); pl = strlen(postfix); if (pl == 0) return (sd_char*) s + sl; if (sl < pl) return NULL; if (strcasecmp(s + sl - pl, postfix) != 0) return NULL; return (sd_char*) s + sl - pl; } static bool is_valid_version_char(sd_char a) { return ascii_isdigit(a) || ascii_isalpha(a) || IN_SET(a, '~', '-', '^', '.'); } int strverscmp_improved(const sd_char *a, const sd_char *b) { /* This function is similar to strverscmp(3), but it treats '-' and '.' as separators. * * The logic is based on rpm's rpmvercmp(), but unlike rpmvercmp(), it distiguishes e.g. * '123a' and '123.a', with '123a' being newer. * * It allows direct comparison of strings which contain both a version and a release; e.g. * '247.2-3.1.fc33.x86_64' or '5.11.0-0.rc5.20210128git76c057c84d28.137.fc34'. * * The input string is split into segments. Each segment is numeric or alphabetic, and may be * prefixed with the following: * '~' : used for pre-releases, a segment prefixed with this is the oldest, * '-' : used for the separator between version and release, * '^' : used for patched releases, a segment with this is newer than one with '-'. * '.' : used for point releases. * Note that no prefix segment is the newest. All non-supported characters are dropped, and * handled as a separator of segments, e.g., '123_a' is equivalent to '123a'. * * By using this, version strings can be sorted like following: * (older) 122.1 * ^ 123~rc1-1 * | 123 * | 123-a * | 123-a.1 * | 123-1 * | 123-1.1 * | 123^post1 * | 123.a-1 * | 123.1-1 * v 123a-1 * (newer) 124-1 */ a = strempty(a); b = strempty(b); for (;;) { const sd_char *aa, *bb; int r; /* Drop leading invalid characters. */ while (*a != '\0' && !is_valid_version_char(*a)) a++; while (*b != '\0' && !is_valid_version_char(*b)) b++; /* Handle '~'. Used for pre-releases, e.g. 123~rc1, or 4.5~alpha1 */ if (*a == '~' || *b == '~') { /* The string prefixed with '~' is older. */ r = CMP(*a != '~', *b != '~'); if (r != 0) return r; /* Now both strings are prefixed with '~'. Compare remaining strings. */ a++; b++; } /* If at least one string reaches the end, then longer is newer. * Note that except for '~' prefixed segments, a string which has more segments is newer. * So, this check must be after the '~' check. */ if (*a == '\0' || *b == '\0') return CMP(*a, *b); /* Handle '-', which separates version and release, e.g 123.4-3.1.fc33.x86_64 */ if (*a == '-' || *b == '-') { /* The string prefixed with '-' is older (e.g., 123-9 vs 123.1-1) */ r = CMP(*a != '-', *b != '-'); if (r != 0) return r; a++; b++; } /* Handle '^'. Used for patched release. */ if (*a == '^' || *b == '^') { r = CMP(*a != '^', *b != '^'); if (r != 0) return r; a++; b++; } /* Handle '.'. Used for point releases. */ if (*a == '.' || *b == '.') { r = CMP(*a != '.', *b != '.'); if (r != 0) return r; a++; b++; } if (ascii_isdigit(*a) || ascii_isdigit(*b)) { /* Find the leading numeric segments. One may be an empty string. So, * numeric segments are always newer than alpha segments. */ for (aa = a; ascii_isdigit(*aa); aa++) ; for (bb = b; ascii_isdigit(*bb); bb++) ; /* Check if one of the strings was empty, but the other not. */ r = CMP(a != aa, b != bb); if (r != 0) return r; /* Skip leading '0', to make 00123 equivalent to 123. */ while (*a == '0') a++; while (*b == '0') b++; /* To compare numeric segments without parsing their values, first compare the * lengths of the segments. Eg. 12345 vs 123, longer is newer. */ r = CMP(aa - a, bb - b); if (r != 0) return r; /* Then, compare them as strings. */ r = CMP(strncmp(a, b, aa - a), 0); if (r != 0) return r; } else { /* Find the leading non-numeric segments. */ for (aa = a; ascii_isalpha(*aa); aa++) ; for (bb = b; ascii_isalpha(*bb); bb++) ; /* Note that the segments are usually not NUL-terminated. */ r = CMP(strncmp(a, b, MIN(aa - a, bb - b)), 0); if (r != 0) return r; /* Longer is newer, e.g. abc vs abcde. */ r = CMP(aa - a, bb - b); if (r != 0) return r; } /* The current segments are equivalent. Let's move to the next one. */ a = aa; b = bb; } }
7,849
33.279476
105
c
null
systemd-main/src/fundamental/string-util-fundamental.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #if SD_BOOT # include "efi.h" # include "efi-string.h" #else # include <string.h> #endif #include "macro-fundamental.h" #if SD_BOOT # define strlen strlen16 # define strcmp strcmp16 # define strncmp strncmp16 # define strcasecmp strcasecmp16 # define strncasecmp strncasecmp16 # define STR_C(str) (L ## str) typedef char16_t sd_char; #else # define STR_C(str) (str) typedef char sd_char; #endif #define streq(a,b) (strcmp((a),(b)) == 0) #define strneq(a, b, n) (strncmp((a), (b), (n)) == 0) #define strcaseeq(a,b) (strcasecmp((a),(b)) == 0) #define strncaseeq(a, b, n) (strncasecmp((a), (b), (n)) == 0) static inline int strcmp_ptr(const sd_char *a, const sd_char *b) { if (a && b) return strcmp(a, b); return CMP(a, b); } static inline int strcasecmp_ptr(const sd_char *a, const sd_char *b) { if (a && b) return strcasecmp(a, b); return CMP(a, b); } static inline bool streq_ptr(const sd_char *a, const sd_char *b) { return strcmp_ptr(a, b) == 0; } static inline bool strcaseeq_ptr(const sd_char *a, const sd_char *b) { return strcasecmp_ptr(a, b) == 0; } static inline size_t strlen_ptr(const sd_char *s) { if (!s) return 0; return strlen(s); } sd_char *startswith(const sd_char *s, const sd_char *prefix) _pure_; sd_char *startswith_no_case(const sd_char *s, const sd_char *prefix) _pure_; sd_char *endswith(const sd_char *s, const sd_char *postfix) _pure_; sd_char *endswith_no_case(const sd_char *s, const sd_char *postfix) _pure_; static inline bool isempty(const sd_char *a) { return !a || a[0] == '\0'; } static inline const sd_char *strempty(const sd_char *s) { return s ?: STR_C(""); } static inline const sd_char *yes_no(bool b) { return b ? STR_C("yes") : STR_C("no"); } static inline const sd_char* comparison_operator(int result) { return result < 0 ? STR_C("<") : result > 0 ? STR_C(">") : STR_C("=="); } int strverscmp_improved(const sd_char *a, const sd_char *b); /* Like startswith(), but operates on arbitrary memory blocks */ static inline void *memory_startswith(const void *p, size_t sz, const sd_char *token) { assert(token); size_t n = strlen(token) * sizeof(sd_char); if (sz < n) return NULL; assert(p); if (memcmp(p, token, n) != 0) return NULL; return (uint8_t*) p + n; } #define _STRV_FOREACH(s, l, i) \ for (typeof(*(l)) *s, *i = (l); (s = i) && *i; i++) #define STRV_FOREACH(s, l) \ _STRV_FOREACH(s, l, UNIQ_T(i, UNIQ)) static inline bool ascii_isdigit(sd_char a) { /* A pure ASCII, locale independent version of isdigit() */ return a >= '0' && a <= '9'; } static inline bool ascii_ishex(sd_char a) { return ascii_isdigit(a) || (a >= 'a' && a <= 'f') || (a >= 'A' && a <= 'F'); } static inline bool ascii_isalpha(sd_char a) { /* A pure ASCII, locale independent version of isalpha() */ return (a >= 'a' && a <= 'z') || (a >= 'A' && a <= 'Z'); }
3,229
26.372881
87
h
null
systemd-main/src/fundamental/tpm-pcr.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stddef.h> #include "tpm-pcr.h" const char* const unified_sections[_UNIFIED_SECTION_MAX + 1] = { [UNIFIED_SECTION_LINUX] = ".linux", [UNIFIED_SECTION_OSREL] = ".osrel", [UNIFIED_SECTION_CMDLINE] = ".cmdline", [UNIFIED_SECTION_INITRD] = ".initrd", [UNIFIED_SECTION_SPLASH] = ".splash", [UNIFIED_SECTION_DTB] = ".dtb", [UNIFIED_SECTION_UNAME] = ".uname", [UNIFIED_SECTION_SBAT] = ".sbat", [UNIFIED_SECTION_PCRSIG] = ".pcrsig", [UNIFIED_SECTION_PCRPKEY] = ".pcrpkey", NULL, };
639
31
64
c
null
systemd-main/src/fundamental/tpm-pcr.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "macro-fundamental.h" /* The various TPM PCRs we measure into from sd-stub and sd-boot. */ /* This TPM PCR is where we extend the sd-stub "payloads" into, before using them. i.e. the kernel ELF image, * embedded initrd, and so on. In contrast to PCR 4 (which also contains this data, given the whole * surrounding PE image is measured into it) this should be reasonably pre-calculatable, because it *only* * consists of static data from the kernel PE image. */ #define TPM_PCR_INDEX_KERNEL_IMAGE 11U /* This TPM PCR is where sd-stub extends the kernel command line and any passed credentials into. */ #define TPM_PCR_INDEX_KERNEL_PARAMETERS 12U /* This TPM PCR is where we extend the initrd sysext images into which we pass to the booted kernel */ #define TPM_PCR_INDEX_INITRD_SYSEXTS 13U /* This TPM PCR is where we measure the root fs volume key (and maybe /var/'s) if it is split off */ #define TPM_PCR_INDEX_VOLUME_KEY 15U /* List of PE sections that have special meaning for us in unified kernels. This is the canonical order in * which we measure the sections into TPM PCR 11 (see above). PLEASE DO NOT REORDER! */ typedef enum UnifiedSection { UNIFIED_SECTION_LINUX, UNIFIED_SECTION_OSREL, UNIFIED_SECTION_CMDLINE, UNIFIED_SECTION_INITRD, UNIFIED_SECTION_SPLASH, UNIFIED_SECTION_DTB, UNIFIED_SECTION_UNAME, UNIFIED_SECTION_SBAT, UNIFIED_SECTION_PCRSIG, UNIFIED_SECTION_PCRPKEY, _UNIFIED_SECTION_MAX, } UnifiedSection; extern const char* const unified_sections[_UNIFIED_SECTION_MAX + 1]; static inline bool unified_section_measure(UnifiedSection section) { /* Don't include the PCR signature in the PCR measurements, since they sign the expected result of * the measurement, and hence shouldn't be input to it. */ return section >= 0 && section < _UNIFIED_SECTION_MAX && section != UNIFIED_SECTION_PCRSIG; }
2,011
42.73913
109
h
null
systemd-main/src/fundamental/unaligned-fundamental.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdint.h> static inline uint16_t unaligned_read_ne16(const void *_u) { const struct __attribute__((__packed__, __may_alias__)) { uint16_t x; } *u = _u; return u->x; } static inline uint32_t unaligned_read_ne32(const void *_u) { const struct __attribute__((__packed__, __may_alias__)) { uint32_t x; } *u = _u; return u->x; } static inline uint64_t unaligned_read_ne64(const void *_u) { const struct __attribute__((__packed__, __may_alias__)) { uint64_t x; } *u = _u; return u->x; } static inline void unaligned_write_ne16(void *_u, uint16_t a) { struct __attribute__((__packed__, __may_alias__)) { uint16_t x; } *u = _u; u->x = a; } static inline void unaligned_write_ne32(void *_u, uint32_t a) { struct __attribute__((__packed__, __may_alias__)) { uint32_t x; } *u = _u; u->x = a; } static inline void unaligned_write_ne64(void *_u, uint64_t a) { struct __attribute__((__packed__, __may_alias__)) { uint64_t x; } *u = _u; u->x = a; }
1,115
26.219512
88
h
null
systemd-main/src/fuzz/fuzz-bootspec.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <string.h> #include "bootspec.h" #include "env-util.h" #include "escape.h" #include "fuzz.h" #include "fd-util.h" #include "json.h" static int json_dispatch_config(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) { BootConfig *config = ASSERT_PTR(userdata); const char *s = json_variant_string(variant); if (!s) return -EINVAL; _cleanup_fclose_ FILE *f = NULL; assert_se(f = data_to_file((const uint8_t*) s, strlen(s))); (void) boot_loader_read_conf(config, f, "memstream"); return 0; } static int json_dispatch_entries(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) { BootConfig *config = ASSERT_PTR(userdata); JsonVariant *entry; JSON_VARIANT_ARRAY_FOREACH(entry, variant) { if (!json_variant_is_array(entry) || json_variant_elements(entry) < 1) return -EINVAL; JsonVariant *v; const char *id = NULL, *raw = NULL; _cleanup_free_ char *data = NULL; ssize_t len = -ENODATA; v = json_variant_by_index(entry, 0); if (v) id = json_variant_string(v); if (!id) continue; v = json_variant_by_index(entry, 1); if (v) raw = json_variant_string(v); if (raw) len = cunescape(raw, UNESCAPE_RELAX | UNESCAPE_ACCEPT_NUL, &data); if (len >= 0) { _cleanup_fclose_ FILE *f = NULL; assert_se(f = data_to_file((const uint8_t*) data, len)); assert_se(boot_config_load_type1(config, f, "/", "/entries", id) != -ENOMEM); } } return 0; } static int json_dispatch_loader(const char *name, JsonVariant *variant, JsonDispatchFlags flags, void *userdata) { BootConfig *config = ASSERT_PTR(userdata); _cleanup_strv_free_ char **entries = NULL; int r; r = json_dispatch_strv(name, variant, flags, &entries); if (r < 0) return r; (void) boot_config_augment_from_loader(config, entries, false); return 0; } static const JsonDispatch data_dispatch[] = { { "config", JSON_VARIANT_STRING, json_dispatch_config, 0, 0 }, { "entries", JSON_VARIANT_ARRAY, json_dispatch_entries, 0, 0 }, { "loader", JSON_VARIANT_ARRAY, json_dispatch_loader, 0, 0 }, {} }; int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_free_ const char *datadup = NULL; _cleanup_(boot_config_free) BootConfig config = BOOT_CONFIG_NULL; int r; if (outside_size_range(size, 0, 65536)) return 0; /* Disable most logging if not running standalone */ if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); assert_se(datadup = memdup_suffix0(data, size)); _cleanup_(json_variant_unrefp) JsonVariant *v = NULL; r = json_parse(datadup, 0, &v, NULL, NULL); if (r < 0) return 0; r = json_dispatch(v, data_dispatch, NULL, 0, &config); if (r < 0) return 0; assert_se(boot_config_finalize(&config) >= 0); (void) boot_config_select_special_entries(&config, /* skip_efivars= */ false); _cleanup_close_ int orig_stdout_fd = -EBADF; if (getenv_bool("SYSTEMD_FUZZ_OUTPUT") <= 0) { orig_stdout_fd = fcntl(fileno(stdout), F_DUPFD_CLOEXEC, 3); if (orig_stdout_fd < 0) log_warning_errno(orig_stdout_fd, "Failed to duplicate fd 1: %m"); else assert_se(freopen("/dev/null", "w", stdout)); } (void) show_boot_entries(&config, JSON_FORMAT_OFF); (void) show_boot_entries(&config, JSON_FORMAT_PRETTY); if (orig_stdout_fd >= 0) assert_se(freopen(FORMAT_PROC_FD_PATH(orig_stdout_fd), "w", stdout)); return 0; }
4,282
32.992063
115
c
null
systemd-main/src/fuzz/fuzz-calendarspec.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "calendarspec.h" #include "fd-util.h" #include "fuzz.h" #include "string-util.h" #include "time-util.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_(calendar_spec_freep) CalendarSpec *cspec = NULL; _cleanup_free_ char *str = NULL; int r; if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); assert_se(str = memdup_suffix0(data, size)); size_t l1 = strlen(str); const char* usecs = l1 < size ? str + l1 + 1 : ""; r = calendar_spec_from_string(str, &cspec); if (r < 0) { log_debug_errno(r, "Failed to parse \"%s\": %m", str); return 0; } _cleanup_free_ char *p = NULL; assert_se(calendar_spec_valid(cspec)); assert_se(calendar_spec_to_string(cspec, &p) == 0); assert(p); log_debug("spec: %s → %s", str, p); _cleanup_(calendar_spec_freep) CalendarSpec *cspec2 = NULL; assert_se(calendar_spec_from_string(p, &cspec2) >= 0); assert_se(calendar_spec_valid(cspec2)); usec_t usec = 0; (void) parse_time(usecs, &usec, 1); /* If timezone is set, calendar_spec_next_usec() would fork, bleh :( * Let's not try that. */ cspec->timezone = mfree(cspec->timezone); log_debug("00: %s", strna(FORMAT_TIMESTAMP(usec))); for (unsigned i = 1; i <= 20; i++) { r = calendar_spec_next_usec(cspec, usec, &usec); if (r < 0) { log_debug_errno(r, "%02u: %m", i); break; } log_debug("%02u: %s", i, FORMAT_TIMESTAMP(usec)); } return 0; }
1,818
29.830508
76
c
null
systemd-main/src/fuzz/fuzz-catalog.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "catalog.h" #include "fd-util.h" #include "fs-util.h" #include "fuzz.h" #include "tmpfile-util.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_(unlink_tempfilep) char name[] = "/tmp/fuzz-catalog.XXXXXX"; _cleanup_close_ int fd = -EBADF; _cleanup_ordered_hashmap_free_free_free_ OrderedHashmap *h = NULL; if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); assert_se(h = ordered_hashmap_new(&catalog_hash_ops)); fd = mkostemp_safe(name); assert_se(fd >= 0); assert_se(write(fd, data, size) == (ssize_t) size); (void) catalog_import_file(h, name); return 0; }
757
27.074074
77
c
null
systemd-main/src/fuzz/fuzz-compress.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include "alloc-util.h" #include "compress.h" #include "fuzz.h" typedef struct header { uint32_t alg:2; /* We have only three compression algorithms so far, but we might add more in the * future. Let's make this a bit wider so our fuzzer cases remain stable in the * future. */ uint32_t sw_len; uint32_t sw_alloc; uint32_t reserved[3]; /* Extra space to keep fuzz cases stable in case we need to * add stuff in the future. */ uint8_t data[]; } header; int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_free_ void *buf = NULL, *buf2 = NULL; int r; if (size < offsetof(header, data) + 1) return 0; const header *h = (struct header*) data; const size_t data_len = size - offsetof(header, data); int alg = h->alg; /* We don't want to fill the logs with messages about parse errors. * Disable most logging if not running standalone */ if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); log_info("Using compression %s, data size=%zu", compression_to_string(alg), data_len); buf = malloc(MAX(size, 128u)); /* Make the buffer a bit larger for very small data */ if (!buf) { log_oom(); return 0; } size_t csize; r = compress_blob(alg, h->data, data_len, buf, size, &csize); if (r < 0) { log_error_errno(r, "Compression failed: %m"); return 0; } log_debug("Compressed %zu bytes to → %zu bytes", data_len, csize); size_t sw_alloc = MAX(h->sw_alloc, 1u); buf2 = malloc(sw_alloc); if (!buf2) { log_oom(); return 0; } size_t sw_len = MIN(data_len - 1, h->sw_len); r = decompress_startswith(alg, buf, csize, &buf2, h->data, sw_len, h->data[sw_len]); assert_se(r > 0); return 0; }
2,175
30.085714
105
c
null
systemd-main/src/fuzz/fuzz-env-file.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdio.h> #include "alloc-util.h" #include "env-file.h" #include "fd-util.h" #include "fuzz.h" #include "strv.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_fclose_ FILE *f = NULL; _cleanup_strv_free_ char **rl = NULL, **rlp = NULL; if (outside_size_range(size, 0, 65536)) return 0; f = data_to_file(data, size); assert_se(f); /* We don't want to fill the logs with messages about parse errors. * Disable most logging if not running standalone */ if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); (void) load_env_file(f, NULL, &rl); assert_se(fseek(f, 0, SEEK_SET) == 0); (void) load_env_file_pairs(f, NULL, &rlp); return 0; }
864
26.03125
75
c
null
systemd-main/src/fuzz/fuzz-hostname-setup.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "fd-util.h" #include "fuzz.h" #include "hostname-setup.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_fclose_ FILE *f = NULL; _cleanup_free_ char *ret = NULL; f = data_to_file(data, size); assert_se(f); /* We don't want to fill the logs with messages about parse errors. * Disable most logging if not running standalone */ if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); (void) read_etc_hostname_stream(f, &ret); return 0; }
645
25.916667
75
c
null
systemd-main/src/fuzz/fuzz-json.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "env-util.h" #include "fd-util.h" #include "fuzz.h" #include "json.h" #include "memstream-util.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_(memstream_done) MemStream m = {}; _cleanup_(json_variant_unrefp) JsonVariant *v = NULL; _cleanup_fclose_ FILE *f = NULL; FILE *g = NULL; int r; /* Disable most logging if not running standalone */ if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); f = data_to_file(data, size); assert_se(f); r = json_parse_file(f, NULL, 0, &v, NULL, NULL); if (r < 0) { log_debug_errno(r, "failed to parse input: %m"); return 0; } if (getenv_bool("SYSTEMD_FUZZ_OUTPUT") <= 0) assert_se(g = memstream_init(&m)); json_variant_dump(v, 0, g ?: stdout, NULL); json_variant_dump(v, JSON_FORMAT_PRETTY|JSON_FORMAT_COLOR|JSON_FORMAT_SOURCE, g ?: stdout, NULL); bool sorted = json_variant_is_sorted(v); log_debug("json_variant_is_sorted: %s", yes_no(sorted)); r = json_variant_sort(&v); log_debug_errno(r, "json_variant_sort: %d/%m", r); sorted = json_variant_is_sorted(v); log_debug("json_variant_is_sorted: %s", yes_no(sorted)); assert_se(r < 0 || sorted); bool normalized = json_variant_is_normalized(v); log_debug("json_variant_is_normalized: %s", yes_no(normalized)); r = json_variant_normalize(&v); log_debug_errno(r, "json_variant_normalize: %d/%m", r); normalized = json_variant_is_normalized(v); log_debug("json_variant_is_normalized: %s", yes_no(normalized)); assert_se(r < 0 || normalized); double real = json_variant_real(v); log_debug("json_variant_real: %lf", real); bool negative = json_variant_is_negative(v); log_debug("json_variant_is_negative: %s", yes_no(negative)); bool blank = json_variant_is_blank_object(v); log_debug("json_variant_is_blank_object: %s", yes_no(blank)); blank = json_variant_is_blank_array(v); log_debug("json_variant_is_blank_array: %s", yes_no(blank)); size_t elements = json_variant_elements(v); log_debug("json_variant_elements: %zu", elements); for (size_t i = 0; i <= elements + 2; i++) (void) json_variant_by_index(v, i); assert_se(json_variant_equal(v, v)); assert_se(!json_variant_equal(v, NULL)); assert_se(!json_variant_equal(NULL, v)); bool sensitive = json_variant_is_sensitive(v); log_debug("json_variant_is_sensitive: %s", yes_no(sensitive)); json_variant_sensitive(v); sensitive = json_variant_is_sensitive(v); log_debug("json_variant_is_sensitive: %s", yes_no(sensitive)); const char *source; unsigned line, column; assert_se(json_variant_get_source(v, &source, &line, &column) == 0); log_debug("json_variant_get_source: %s:%u:%u", source ?: "-", line, column); r = json_variant_set_field_string(&v, "a", "string-a"); log_debug_errno(r, "json_set_field_string: %d/%m", r); r = json_variant_set_field_integer(&v, "b", -12345); log_debug_errno(r, "json_set_field_integer: %d/%m", r); r = json_variant_set_field_unsigned(&v, "c", 12345); log_debug_errno(r, "json_set_field_unsigned: %d/%m", r); r = json_variant_set_field_boolean(&v, "d", false); log_debug_errno(r, "json_set_field_boolean: %d/%m", r); r = json_variant_set_field_strv(&v, "e", STRV_MAKE("e-1", "e-2", "e-3")); log_debug_errno(r, "json_set_field_strv: %d/%m", r); r = json_variant_filter(&v, STRV_MAKE("a", "b", "c", "d", "e")); log_debug_errno(r, "json_variant_filter: %d/%m", r); /* I assume we can merge v with itself… */ r = json_variant_merge(&v, v); log_debug_errno(r, "json_variant_merge: %d/%m", r); r = json_variant_append_array(&v, v); log_debug_errno(r, "json_variant_append_array: %d/%m", r); return 0; }
4,251
35.033898
105
c
null
systemd-main/src/fuzz/fuzz-main.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "fileio.h" #include "fuzz.h" #include "log.h" #include "parse-util.h" #include "string-util.h" #include "tests.h" /* This is a test driver for the systemd fuzzers that provides main function * for regression testing outside of oss-fuzz (https://github.com/google/oss-fuzz) * * It reads files named on the command line and passes them one by one into the * fuzzer that it is compiled into. */ /* This one was borrowed from * https://github.com/google/oss-fuzz/blob/646fca1b506b056db3a60d32c4a1a7398f171c94/infra/base-images/base-runner/bad_build_check#L19 */ #define NUMBER_OF_RUNS 4 int main(int argc, char **argv) { int r; test_setup_logging(LOG_DEBUG); unsigned number_of_runs = NUMBER_OF_RUNS; const char *v = getenv("SYSTEMD_FUZZ_RUNS"); if (!isempty(v)) { r = safe_atou(v, &number_of_runs); if (r < 0) return log_error_errno(r, "Failed to parse SYSTEMD_FUZZ_RUNS=%s: %m", v); } for (int i = 1; i < argc; i++) { _cleanup_free_ char *buf = NULL; size_t size; char *name; name = argv[i]; r = read_full_file(name, &buf, &size); if (r < 0) { log_error_errno(r, "Failed to open '%s': %m", name); return EXIT_FAILURE; } printf("%s... ", name); fflush(stdout); for (unsigned j = 0; j < number_of_runs; j++) if (LLVMFuzzerTestOneInput((uint8_t*)buf, size) == EXIT_TEST_SKIP) return EXIT_TEST_SKIP; printf("ok\n"); } return EXIT_SUCCESS; }
1,841
31.315789
133
c
null
systemd-main/src/fuzz/fuzz-time-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "fd-util.h" #include "fuzz.h" #include "time-util.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_free_ char *str = NULL; usec_t usec; if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); assert_se(str = memdup_suffix0(data, size)); (void) parse_timestamp(str, &usec); (void) parse_sec(str, &usec); (void) parse_sec_fix_0(str, &usec); (void) parse_sec_def_infinity(str, &usec); (void) parse_time(str, &usec, USEC_PER_SEC); (void) parse_nsec(str, &usec); (void) timezone_is_valid(str, LOG_DEBUG); return 0; }
746
25.678571
62
c
null
systemd-main/src/fuzz/fuzz-udev-database.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "device-internal.h" #include "device-private.h" #include "fd-util.h" #include "fs-util.h" #include "fuzz.h" #include "tmpfile-util.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_(sd_device_unrefp) sd_device *dev = NULL; _cleanup_(unlink_tempfilep) char filename[] = "/tmp/fuzz-udev-database.XXXXXX"; _cleanup_fclose_ FILE *f = NULL; if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); assert_se(fmkostemp_safe(filename, "r+", &f) == 0); if (size != 0) assert_se(fwrite(data, size, 1, f) == 1); fflush(f); assert_se(device_new_aux(&dev) >= 0); (void) device_read_db_internal_filename(dev, filename); return 0; }
825
29.592593
87
c
null
systemd-main/src/fuzz/fuzz-varlink.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include "errno-util.h" #include "fd-util.h" #include "fuzz.h" #include "hexdecoct.h" #include "io-util.h" #include "varlink.h" #include "log.h" static FILE *null = NULL; static int method_something(Varlink *v, JsonVariant *p, VarlinkMethodFlags flags, void *userdata) { json_variant_dump(p, JSON_FORMAT_NEWLINE|JSON_FORMAT_PRETTY, null, NULL); return 0; } static int reply_callback(Varlink *v, JsonVariant *p, const char *error_id, VarlinkReplyFlags flags, void *userdata) { json_variant_dump(p, JSON_FORMAT_NEWLINE|JSON_FORMAT_PRETTY, null, NULL); return 0; } static int io_callback(sd_event_source *s, int fd, uint32_t revents, void *userdata) { struct iovec *iov = ASSERT_PTR(userdata); bool write_eof = false, read_eof = false; assert(s); assert(fd >= 0); if ((revents & (EPOLLOUT|EPOLLHUP|EPOLLERR)) && iov->iov_len > 0) { ssize_t n; /* never write more than 143 bytes a time, to make broken up recv()s on the other side more * likely, and thus test some additional code paths. */ n = send(fd, iov->iov_base, MIN(iov->iov_len, 143U), MSG_NOSIGNAL|MSG_DONTWAIT); if (n < 0) { if (ERRNO_IS_DISCONNECT(errno)) write_eof = true; else assert_se(errno == EAGAIN); } else IOVEC_INCREMENT(iov, 1, n); } if (revents & EPOLLIN) { char c[137]; ssize_t n; n = recv(fd, c, sizeof(c), MSG_DONTWAIT); if (n < 0) { if (ERRNO_IS_DISCONNECT(errno)) read_eof = true; else assert_se(errno == EAGAIN); } else if (n == 0) read_eof = true; else hexdump(null, c, (size_t) n); } /* After we wrote everything we could turn off EPOLLOUT. And if we reached read EOF too turn off the * whole thing. */ if (write_eof || iov->iov_len == 0) { if (read_eof) assert_se(sd_event_source_set_enabled(s, SD_EVENT_OFF) >= 0); else assert_se(sd_event_source_set_io_events(s, EPOLLIN) >= 0); } return 0; } static int idle_callback(sd_event_source *s, void *userdata) { assert(s); /* Called as idle callback when there's nothing else to do anymore */ sd_event_exit(sd_event_source_get_event(s), 0); return 0; } int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { struct iovec server_iov = IOVEC_MAKE((void*) data, size), client_iov = IOVEC_MAKE((void*) data, size); /* Important: the declaration order matters here! we want that the fds are closed on return after the * event sources, hence we declare the fds first, the event sources second */ _cleanup_close_pair_ int server_pair[2] = PIPE_EBADF, client_pair[2] = PIPE_EBADF; _cleanup_(sd_event_source_unrefp) sd_event_source *idle_event_source = NULL, *server_event_source = NULL, *client_event_source = NULL; _cleanup_(varlink_server_unrefp) VarlinkServer *s = NULL; _cleanup_(varlink_flush_close_unrefp) Varlink *c = NULL; _cleanup_(sd_event_unrefp) sd_event *e = NULL; log_set_max_level(LOG_CRIT); log_parse_environment(); assert_se(null = fopen("/dev/null", "we")); assert_se(sd_event_default(&e) >= 0); /* Test one: write the data as method call to a server */ assert_se(socketpair(AF_UNIX, SOCK_STREAM, 0, server_pair) >= 0); assert_se(varlink_server_new(&s, 0) >= 0); assert_se(varlink_server_set_description(s, "myserver") >= 0); assert_se(varlink_server_attach_event(s, e, 0) >= 0); assert_se(varlink_server_add_connection(s, server_pair[0], NULL) >= 0); TAKE_FD(server_pair[0]); assert_se(varlink_server_bind_method(s, "io.test.DoSomething", method_something) >= 0); assert_se(sd_event_add_io(e, &server_event_source, server_pair[1], EPOLLIN|EPOLLOUT, io_callback, &server_iov) >= 0); /* Test two: write the data as method response to a client */ assert_se(socketpair(AF_UNIX, SOCK_STREAM, 0, client_pair) >= 0); assert_se(varlink_connect_fd(&c, client_pair[0]) >= 0); TAKE_FD(client_pair[0]); assert_se(varlink_set_description(c, "myclient") >= 0); assert_se(varlink_attach_event(c, e, 0) >= 0); assert_se(varlink_bind_reply(c, reply_callback) >= 0); assert_se(varlink_invoke(c, "io.test.DoSomething", NULL) >= 0); assert_se(sd_event_add_io(e, &client_event_source, client_pair[1], EPOLLIN|EPOLLOUT, io_callback, &client_iov) >= 0); assert_se(sd_event_add_defer(e, &idle_event_source, idle_callback, NULL) >= 0); assert_se(sd_event_source_set_priority(idle_event_source, SD_EVENT_PRIORITY_IDLE) >= 0); assert_se(sd_event_loop(e) >= 0); null = safe_fclose(null); return 0; }
5,343
39.793893
125
c
null
systemd-main/src/fuzz/fuzz.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stddef.h> #include <stdint.h> #include "env-util.h" #include "fileio.h" /* The entry point into the fuzzer */ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size); static inline FILE* data_to_file(const uint8_t *data, size_t size) { if (size == 0) return fopen("/dev/null", "re"); else return fmemopen_unlocked((char*) data, size, "r"); } /* Check if we are within the specified size range. * The upper limit is ignored if FUZZ_USE_SIZE_LIMIT is unset. */ static inline bool outside_size_range(size_t size, size_t lower, size_t upper) { if (size < lower) return true; if (size > upper) return FUZZ_USE_SIZE_LIMIT; return false; } /* Force value to not be optimized away. */ #define DO_NOT_OPTIMIZE(value) ({ asm volatile("" : : "g"(value) : "memory"); })
947
27.727273
80
h
null
systemd-main/src/getty-generator/getty-generator.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <unistd.h> #include "alloc-util.h" #include "creds-util.h" #include "errno-util.h" #include "fd-util.h" #include "fileio.h" #include "generator.h" #include "initrd-util.h" #include "log.h" #include "mkdir-label.h" #include "parse-util.h" #include "path-util.h" #include "proc-cmdline.h" #include "process-util.h" #include "strv.h" #include "terminal-util.h" #include "unit-name.h" #include "virt.h" static const char *arg_dest = NULL; static bool arg_enabled = true; static int add_symlink(const char *fservice, const char *tservice) { const char *from, *to; assert(fservice); assert(tservice); from = strjoina(SYSTEM_DATA_UNIT_DIR "/", fservice); to = strjoina(arg_dest, "/getty.target.wants/", tservice); (void) mkdir_parents_label(to, 0755); if (symlink(from, to) < 0) { /* In case console=hvc0 is passed this will very likely result in EEXIST */ if (errno == EEXIST) return 0; return log_error_errno(errno, "Failed to create symlink %s: %m", to); } return 0; } static int add_serial_getty(const char *tty) { _cleanup_free_ char *n = NULL; int r; assert(tty); log_debug("Automatically adding serial getty for /dev/%s.", tty); r = unit_name_from_path_instance("serial-getty", tty, ".service", &n); if (r < 0) return log_error_errno(r, "Failed to generate service name: %m"); return add_symlink("[email protected]", n); } static int add_container_getty(const char *tty) { _cleanup_free_ char *n = NULL; int r; assert(tty); log_debug("Automatically adding container getty for /dev/pts/%s.", tty); r = unit_name_from_path_instance("container-getty", tty, ".service", &n); if (r < 0) return log_error_errno(r, "Failed to generate service name: %m"); return add_symlink("[email protected]", n); } static int verify_tty(const char *name) { _cleanup_close_ int fd = -EBADF; const char *p; /* Some TTYs are weird and have been enumerated but don't work * when you try to use them, such as classic ttyS0 and * friends. Let's check that and open the device and run * isatty() on it. */ p = strjoina("/dev/", name); /* O_NONBLOCK is essential here, to make sure we don't wait * for DCD */ fd = open(p, O_RDWR|O_NONBLOCK|O_NOCTTY|O_CLOEXEC|O_NOFOLLOW); if (fd < 0) return -errno; errno = 0; if (isatty(fd) <= 0) return errno_or_else(EIO); return 0; } static int run_container(void) { _cleanup_free_ char *container_ttys = NULL; int r; log_debug("Automatically adding console shell."); r = add_symlink("console-getty.service", "console-getty.service"); if (r < 0) return r; /* When $container_ttys is set for PID 1, spawn gettys on all ptys named therein. * Note that despite the variable name we only support ptys here. */ (void) getenv_for_pid(1, "container_ttys", &container_ttys); for (const char *p = container_ttys;;) { _cleanup_free_ char *word = NULL; r = extract_first_word(&p, &word, NULL, 0); if (r < 0) return log_error_errno(r, "Failed to parse $container_ttys: %m"); if (r == 0) return 0; const char *tty = word; /* First strip off /dev/ if it is specified */ tty = path_startswith(tty, "/dev/") ?: tty; /* Then, make sure it's actually a pty */ tty = path_startswith(tty, "pts/"); if (!tty) continue; r = add_container_getty(tty); if (r < 0) return r; } } static int add_credential_gettys(void) { static const struct { const char *credential_name; int (*func)(const char *tty); } table[] = { { "getty.ttys.serial", add_serial_getty }, { "getty.ttys.container", add_container_getty }, }; int r; FOREACH_ARRAY(t, table, ELEMENTSOF(table)) { _cleanup_free_ char *b = NULL; size_t sz = 0; r = read_credential_with_decryption(t->credential_name, (void*) &b, &sz); if (r < 0) return r; if (r == 0) continue; _cleanup_fclose_ FILE *f = NULL; f = fmemopen_unlocked(b, sz, "r"); if (!f) return log_oom(); for (;;) { _cleanup_free_ char *tty = NULL; char *s; r = read_line(f, PATH_MAX, &tty); if (r == 0) break; if (r < 0) { log_error_errno(r, "Failed to parse credential %s: %m", t->credential_name); break; } s = strstrip(tty); if (startswith(s, "#")) continue; r = t->func(s); if (r < 0) return r; } } return 0; } static int parse_proc_cmdline_item(const char *key, const char *value, void *data) { int r; assert(key); if (proc_cmdline_key_streq(key, "systemd.getty_auto")) { r = value ? parse_boolean(value) : 1; if (r < 0) log_warning_errno(r, "Failed to parse getty_auto switch \"%s\", ignoring: %m", value); else arg_enabled = r; } return 0; } static int run(const char *dest, const char *dest_early, const char *dest_late) { _cleanup_free_ char *getty_auto = NULL; int r; assert_se(arg_dest = dest); if (in_initrd()) { log_debug("Skipping generator, running in the initrd."); return EXIT_SUCCESS; } r = proc_cmdline_parse(parse_proc_cmdline_item, NULL, 0); if (r < 0) log_warning_errno(r, "Failed to parse kernel command line, ignoring: %m"); r = getenv_for_pid(1, "SYSTEMD_GETTY_AUTO", &getty_auto); if (r < 0) log_warning_errno(r, "Failed to parse $SYSTEMD_GETTY_AUTO environment variable, ignoring: %m"); else if (r > 0) { r = parse_boolean(getty_auto); if (r < 0) log_warning_errno(r, "Failed to parse $SYSTEMD_GETTY_AUTO value \"%s\", ignoring: %m", getty_auto); else arg_enabled = r; } if (!arg_enabled) { log_debug("Disabled, exiting."); return 0; } r = add_credential_gettys(); if (r < 0) return r; if (detect_container() > 0) /* Add console shell and look at $container_ttys, but don't do add any * further magic if we are in a container. */ return run_container(); /* Automatically add in a serial getty on all active kernel consoles */ _cleanup_free_ char *active = NULL; (void) read_one_line_file("/sys/class/tty/console/active", &active); for (const char *p = active;;) { _cleanup_free_ char *tty = NULL; r = extract_first_word(&p, &tty, NULL, 0); if (r < 0) return log_error_errno(r, "Failed to parse /sys/class/tty/console/active: %m"); if (r == 0) break; /* We assume that gettys on virtual terminals are started via manual configuration and do * this magic only for non-VC terminals. */ if (isempty(tty) || tty_is_vc(tty)) continue; if (verify_tty(tty) < 0) continue; r = add_serial_getty(tty); if (r < 0) return r; } /* Automatically add in a serial getty on the first virtualizer console */ FOREACH_STRING(j, "hvc0", "xvc0", "hvsi0", "sclp_line0", "ttysclp0", "3270!tty1") { _cleanup_free_ char *p = NULL; p = path_join("/sys/class/tty", j); if (!p) return log_oom(); if (access(p, F_OK) < 0) continue; r = add_serial_getty(j); if (r < 0) return r; } return 0; } DEFINE_MAIN_GENERATOR_FUNCTION(run);
9,356
30.086379
123
c
null
systemd-main/src/hibernate-resume/hibernate-resume.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <sys/stat.h> #include "devnum-util.h" #include "initrd-util.h" #include "log.h" #include "main-func.h" #include "parse-util.h" #include "sleep-util.h" static const char *arg_resume_device = NULL; static uint64_t arg_resume_offset = 0; /* in memory pages */ static int run(int argc, char *argv[]) { struct stat st; int r; log_setup(); if (argc < 2 || argc > 3) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program expects one or two arguments."); umask(0022); if (!in_initrd()) return 0; arg_resume_device = argv[1]; if (argc == 3) { r = safe_atou64(argv[2], &arg_resume_offset); if (r < 0) return log_error_errno(r, "Failed to parse resume offset %s: %m", argv[2]); } if (stat(arg_resume_device, &st) < 0) return log_error_errno(errno, "Failed to stat resume device '%s': %m", arg_resume_device); if (!S_ISBLK(st.st_mode)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Resume device '%s' is not a block device.", arg_resume_device); /* The write shall not return if a resume takes place. */ r = write_resume_config(st.st_rdev, arg_resume_offset, arg_resume_device); log_full_errno(r < 0 ? LOG_ERR : LOG_DEBUG, r < 0 ? r : SYNTHETIC_ERRNO(ENOENT), "Unable to resume from device '%s' (" DEVNUM_FORMAT_STR ") offset %" PRIu64 ", continuing boot process.", arg_resume_device, DEVNUM_FORMAT_VAL(st.st_rdev), arg_resume_offset); return r; } DEFINE_MAIN_FUNCTION(run);
1,814
31.410714
128
c
null
systemd-main/src/home/home-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "dns-domain.h" #include "home-util.h" #include "libcrypt-util.h" #include "memory-util.h" #include "path-util.h" #include "string-util.h" #include "strv.h" #include "user-util.h" bool suitable_user_name(const char *name) { /* Checks whether the specified name is suitable for management via homed. Note that client-side * we usually validate with the simple valid_user_group_name(), while server-side we are a bit more * restrictive, so that we can change the rules server-side without having to update things * client-side too. */ if (!valid_user_group_name(name, 0)) return false; /* We generally rely on NSS to tell us which users not to care for, but let's filter out some * particularly well-known users. */ if (STR_IN_SET(name, "root", "nobody", NOBODY_USER_NAME, NOBODY_GROUP_NAME)) return false; /* Let's also defend our own namespace, as well as Debian's (unwritten?) logic of prefixing system * users with underscores. */ if (STARTSWITH_SET(name, "systemd-", "_")) return false; return true; } int suitable_realm(const char *realm) { _cleanup_free_ char *normalized = NULL; int r; /* Similar to the above: let's validate the realm a bit stricter server-side than client side */ r = dns_name_normalize(realm, 0, &normalized); /* this also checks general validity */ if (r == -EINVAL) return 0; if (r < 0) return r; if (!streq(realm, normalized)) /* is this normalized? */ return false; if (dns_name_is_root(realm)) /* Don't allow top level domain */ return false; return true; } int suitable_image_path(const char *path) { return !empty_or_root(path) && path_is_valid(path) && path_is_absolute(path); } bool supported_fstype(const char *fstype) { /* Limit the set of supported file systems a bit, as protection against little tested kernel file * systems. Also, we only support the resize ioctls for these file systems. */ return STR_IN_SET(fstype, "ext4", "btrfs", "xfs"); } int split_user_name_realm(const char *t, char **ret_user_name, char **ret_realm) { _cleanup_free_ char *user_name = NULL, *realm = NULL; const char *c; int r; assert(t); assert(ret_user_name); assert(ret_realm); c = strchr(t, '@'); if (!c) { user_name = strdup(t); if (!user_name) return -ENOMEM; } else { user_name = strndup(t, c - t); if (!user_name) return -ENOMEM; realm = strdup(c + 1); if (!realm) return -ENOMEM; } if (!suitable_user_name(user_name)) return -EINVAL; if (realm) { r = suitable_realm(realm); if (r < 0) return r; if (r == 0) return -EINVAL; } *ret_user_name = TAKE_PTR(user_name); *ret_realm = TAKE_PTR(realm); return 0; } int bus_message_append_secret(sd_bus_message *m, UserRecord *secret) { _cleanup_(erase_and_freep) char *formatted = NULL; JsonVariant *v; int r; assert(m); assert(secret); if (!FLAGS_SET(secret->mask, USER_RECORD_SECRET)) return sd_bus_message_append(m, "s", "{}"); v = json_variant_by_key(secret->json, "secret"); if (!v) return -EINVAL; r = json_variant_format(v, 0, &formatted); if (r < 0) return r; (void) sd_bus_message_sensitive(m); return sd_bus_message_append(m, "s", formatted); } const char *home_record_dir(void) { return secure_getenv("SYSTEMD_HOME_RECORD_DIR") ?: "/var/lib/systemd/home/"; }
4,204
29.035714
107
c
null
systemd-main/src/home/homectl-fido2.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #if HAVE_LIBFIDO2 #include <fido.h> #endif #include "ask-password-api.h" #include "errno-util.h" #include "format-table.h" #include "hexdecoct.h" #include "homectl-fido2.h" #include "homectl-pkcs11.h" #include "libcrypt-util.h" #include "libfido2-util.h" #include "locale-util.h" #include "memory-util.h" #include "random-util.h" #include "strv.h" #if HAVE_LIBFIDO2 static int add_fido2_credential_id( JsonVariant **v, const void *cid, size_t cid_size) { _cleanup_(json_variant_unrefp) JsonVariant *w = NULL; _cleanup_strv_free_ char **l = NULL; _cleanup_free_ char *escaped = NULL; ssize_t escaped_size; int r; assert(v); assert(cid); escaped_size = base64mem(cid, cid_size, &escaped); if (escaped_size < 0) return log_error_errno(escaped_size, "Failed to base64 encode FIDO2 credential ID: %m"); w = json_variant_ref(json_variant_by_key(*v, "fido2HmacCredential")); if (w) { r = json_variant_strv(w, &l); if (r < 0) return log_error_errno(r, "Failed to parse FIDO2 credential ID list: %m"); if (strv_contains(l, escaped)) return 0; } r = strv_extend(&l, escaped); if (r < 0) return log_oom(); w = json_variant_unref(w); r = json_variant_new_array_strv(&w, l); if (r < 0) return log_error_errno(r, "Failed to create FIDO2 credential ID JSON: %m"); r = json_variant_set_field(v, "fido2HmacCredential", w); if (r < 0) return log_error_errno(r, "Failed to update FIDO2 credential ID: %m"); return 0; } static int add_fido2_salt( JsonVariant **v, const void *cid, size_t cid_size, const void *fido2_salt, size_t fido2_salt_size, const void *secret, size_t secret_size, Fido2EnrollFlags lock_with) { _cleanup_(json_variant_unrefp) JsonVariant *l = NULL, *w = NULL, *e = NULL; _cleanup_(erase_and_freep) char *base64_encoded = NULL, *hashed = NULL; ssize_t base64_encoded_size; int r; /* Before using UNIX hashing on the supplied key we base64 encode it, since crypt_r() and friends * expect a NUL terminated string, and we use a binary key */ base64_encoded_size = base64mem(secret, secret_size, &base64_encoded); if (base64_encoded_size < 0) return log_error_errno(base64_encoded_size, "Failed to base64 encode secret key: %m"); r = hash_password(base64_encoded, &hashed); if (r < 0) return log_error_errno(errno_or_else(EINVAL), "Failed to UNIX hash secret key: %m"); r = json_build(&e, JSON_BUILD_OBJECT( JSON_BUILD_PAIR("credential", JSON_BUILD_BASE64(cid, cid_size)), JSON_BUILD_PAIR("salt", JSON_BUILD_BASE64(fido2_salt, fido2_salt_size)), JSON_BUILD_PAIR("hashedPassword", JSON_BUILD_STRING(hashed)), JSON_BUILD_PAIR("up", JSON_BUILD_BOOLEAN(FLAGS_SET(lock_with, FIDO2ENROLL_UP))), JSON_BUILD_PAIR("uv", JSON_BUILD_BOOLEAN(FLAGS_SET(lock_with, FIDO2ENROLL_UV))), JSON_BUILD_PAIR("clientPin", JSON_BUILD_BOOLEAN(FLAGS_SET(lock_with, FIDO2ENROLL_PIN))))); if (r < 0) return log_error_errno(r, "Failed to build FIDO2 salt JSON key object: %m"); w = json_variant_ref(json_variant_by_key(*v, "privileged")); l = json_variant_ref(json_variant_by_key(w, "fido2HmacSalt")); r = json_variant_append_array(&l, e); if (r < 0) return log_error_errno(r, "Failed append FIDO2 salt: %m"); r = json_variant_set_field(&w, "fido2HmacSalt", l); if (r < 0) return log_error_errno(r, "Failed to set FDO2 salt: %m"); r = json_variant_set_field(v, "privileged", w); if (r < 0) return log_error_errno(r, "Failed to update privileged field: %m"); return 0; } #endif int identity_add_fido2_parameters( JsonVariant **v, const char *device, Fido2EnrollFlags lock_with, int cred_alg) { #if HAVE_LIBFIDO2 JsonVariant *un, *realm, *rn; _cleanup_(erase_and_freep) void *secret = NULL, *salt = NULL; _cleanup_(erase_and_freep) char *used_pin = NULL; size_t cid_size, salt_size, secret_size; _cleanup_free_ void *cid = NULL; const char *fido_un; int r; assert(v); assert(device); un = json_variant_by_key(*v, "userName"); if (!un) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "userName field of user record is missing"); if (!json_variant_is_string(un)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "userName field of user record is not a string"); realm = json_variant_by_key(*v, "realm"); if (realm) { if (!json_variant_is_string(realm)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "realm field of user record is not a string"); fido_un = strjoina(json_variant_string(un), json_variant_string(realm)); } else fido_un = json_variant_string(un); rn = json_variant_by_key(*v, "realName"); if (rn && !json_variant_is_string(rn)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "realName field of user record is not a string"); r = fido2_generate_hmac_hash( device, /* rp_id= */ "io.systemd.home", /* rp_name= */ "Home Directory", /* user_id= */ fido_un, strlen(fido_un), /* We pass the user ID and name as the same */ /* user_name= */ fido_un, /* user_display_name= */ rn ? json_variant_string(rn) : NULL, /* user_icon_name= */ NULL, /* askpw_icon_name= */ "user-home", lock_with, cred_alg, &cid, &cid_size, &salt, &salt_size, &secret, &secret_size, &used_pin, &lock_with); if (r < 0) return r; r = add_fido2_credential_id( v, cid, cid_size); if (r < 0) return r; r = add_fido2_salt( v, cid, cid_size, salt, salt_size, secret, secret_size, lock_with); if (r < 0) return r; /* If we acquired the PIN also include it in the secret section of the record, so that systemd-homed * can use it if it needs to, given that it likely needs to decrypt the key again to pass to LUKS or * fscrypt. */ r = identity_add_token_pin(v, used_pin); if (r < 0) return r; return 0; #else return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "FIDO2 tokens not supported on this build."); #endif }
7,938
36.448113
129
c
null
systemd-main/src/home/homectl-pkcs11.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "errno-util.h" #include "format-table.h" #include "hexdecoct.h" #include "homectl-pkcs11.h" #include "libcrypt-util.h" #include "memory-util.h" #include "openssl-util.h" #include "pkcs11-util.h" #include "random-util.h" #include "strv.h" static int add_pkcs11_encrypted_key( JsonVariant **v, const char *uri, const void *encrypted_key, size_t encrypted_key_size, const void *decrypted_key, size_t decrypted_key_size) { _cleanup_(json_variant_unrefp) JsonVariant *l = NULL, *w = NULL, *e = NULL; _cleanup_(erase_and_freep) char *base64_encoded = NULL, *hashed = NULL; ssize_t base64_encoded_size; int r; assert(v); assert(uri); assert(encrypted_key); assert(encrypted_key_size > 0); assert(decrypted_key); assert(decrypted_key_size > 0); /* Before using UNIX hashing on the supplied key we base64 encode it, since crypt_r() and friends * expect a NUL terminated string, and we use a binary key */ base64_encoded_size = base64mem(decrypted_key, decrypted_key_size, &base64_encoded); if (base64_encoded_size < 0) return log_error_errno(base64_encoded_size, "Failed to base64 encode secret key: %m"); r = hash_password(base64_encoded, &hashed); if (r < 0) return log_error_errno(errno_or_else(EINVAL), "Failed to UNIX hash secret key: %m"); r = json_build(&e, JSON_BUILD_OBJECT( JSON_BUILD_PAIR("uri", JSON_BUILD_STRING(uri)), JSON_BUILD_PAIR("data", JSON_BUILD_BASE64(encrypted_key, encrypted_key_size)), JSON_BUILD_PAIR("hashedPassword", JSON_BUILD_STRING(hashed)))); if (r < 0) return log_error_errno(r, "Failed to build encrypted JSON key object: %m"); w = json_variant_ref(json_variant_by_key(*v, "privileged")); l = json_variant_ref(json_variant_by_key(w, "pkcs11EncryptedKey")); r = json_variant_append_array(&l, e); if (r < 0) return log_error_errno(r, "Failed append PKCS#11 encrypted key: %m"); r = json_variant_set_field(&w, "pkcs11EncryptedKey", l); if (r < 0) return log_error_errno(r, "Failed to set PKCS#11 encrypted key: %m"); r = json_variant_set_field(v, "privileged", w); if (r < 0) return log_error_errno(r, "Failed to update privileged field: %m"); return 0; } static int add_pkcs11_token_uri(JsonVariant **v, const char *uri) { _cleanup_(json_variant_unrefp) JsonVariant *w = NULL; _cleanup_strv_free_ char **l = NULL; int r; assert(v); assert(uri); w = json_variant_ref(json_variant_by_key(*v, "pkcs11TokenUri")); if (w) { r = json_variant_strv(w, &l); if (r < 0) return log_error_errno(r, "Failed to parse PKCS#11 token list: %m"); if (strv_contains(l, uri)) return 0; } r = strv_extend(&l, uri); if (r < 0) return log_oom(); w = json_variant_unref(w); r = json_variant_new_array_strv(&w, l); if (r < 0) return log_error_errno(r, "Failed to create PKCS#11 token URI JSON: %m"); r = json_variant_set_field(v, "pkcs11TokenUri", w); if (r < 0) return log_error_errno(r, "Failed to update PKCS#11 token URI list: %m"); return 0; } int identity_add_token_pin(JsonVariant **v, const char *pin) { _cleanup_(json_variant_unrefp) JsonVariant *w = NULL, *l = NULL; _cleanup_strv_free_erase_ char **pins = NULL; int r; assert(v); if (isempty(pin)) return 0; w = json_variant_ref(json_variant_by_key(*v, "secret")); l = json_variant_ref(json_variant_by_key(w, "tokenPin")); r = json_variant_strv(l, &pins); if (r < 0) return log_error_errno(r, "Failed to convert PIN array: %m"); if (strv_contains(pins, pin)) return 0; r = strv_extend(&pins, pin); if (r < 0) return log_oom(); strv_uniq(pins); l = json_variant_unref(l); r = json_variant_new_array_strv(&l, pins); if (r < 0) return log_error_errno(r, "Failed to allocate new PIN array JSON: %m"); json_variant_sensitive(l); r = json_variant_set_field(&w, "tokenPin", l); if (r < 0) return log_error_errno(r, "Failed to update PIN field: %m"); r = json_variant_set_field(v, "secret", w); if (r < 0) return log_error_errno(r, "Failed to update secret object: %m"); return 1; } static int acquire_pkcs11_certificate( const char *uri, const char *askpw_friendly_name, const char *askpw_icon_name, X509 **ret_cert, char **ret_pin_used) { #if HAVE_P11KIT return pkcs11_acquire_certificate(uri, askpw_friendly_name, askpw_icon_name, ret_cert, ret_pin_used); #else return log_error_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "PKCS#11 tokens not supported on this build."); #endif } int identity_add_pkcs11_key_data(JsonVariant **v, const char *uri) { _cleanup_(erase_and_freep) void *decrypted_key = NULL, *encrypted_key = NULL; _cleanup_(erase_and_freep) char *pin = NULL; size_t decrypted_key_size, encrypted_key_size; _cleanup_(X509_freep) X509 *cert = NULL; EVP_PKEY *pkey; int r; assert(v); r = acquire_pkcs11_certificate(uri, "home directory operation", "user-home", &cert, &pin); if (r < 0) return r; pkey = X509_get0_pubkey(cert); if (!pkey) return log_error_errno(SYNTHETIC_ERRNO(EIO), "Failed to extract public key from X.509 certificate."); r = rsa_pkey_to_suitable_key_size(pkey, &decrypted_key_size); if (r < 0) return log_error_errno(r, "Failed to extract RSA key size from X509 certificate."); log_debug("Generating %zu bytes random key.", decrypted_key_size); decrypted_key = malloc(decrypted_key_size); if (!decrypted_key) return log_oom(); r = crypto_random_bytes(decrypted_key, decrypted_key_size); if (r < 0) return log_error_errno(r, "Failed to generate random key: %m"); r = rsa_encrypt_bytes(pkey, decrypted_key, decrypted_key_size, &encrypted_key, &encrypted_key_size); if (r < 0) return log_error_errno(r, "Failed to encrypt key: %m"); /* Add the token URI to the public part of the record. */ r = add_pkcs11_token_uri(v, uri); if (r < 0) return r; /* Include the encrypted version of the random key we just generated in the privileged part of the record */ r = add_pkcs11_encrypted_key( v, uri, encrypted_key, encrypted_key_size, decrypted_key, decrypted_key_size); if (r < 0) return r; /* If we acquired the PIN also include it in the secret section of the record, so that systemd-homed * can use it if it needs to, given that it likely needs to decrypt the key again to pass to LUKS or * fscrypt. */ r = identity_add_token_pin(v, pin); if (r < 0) return r; return 0; }
7,825
34.73516
117
c
null
systemd-main/src/home/homectl-recovery-key.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "errno-util.h" #include "glyph-util.h" #include "homectl-recovery-key.h" #include "libcrypt-util.h" #include "memory-util.h" #include "qrcode-util.h" #include "random-util.h" #include "recovery-key.h" #include "strv.h" #include "terminal-util.h" static int add_privileged(JsonVariant **v, const char *hashed) { _cleanup_(json_variant_unrefp) JsonVariant *e = NULL, *w = NULL, *l = NULL; int r; assert(v); assert(hashed); r = json_build(&e, JSON_BUILD_OBJECT( JSON_BUILD_PAIR("type", JSON_BUILD_CONST_STRING("modhex64")), JSON_BUILD_PAIR("hashedPassword", JSON_BUILD_STRING(hashed)))); if (r < 0) return log_error_errno(r, "Failed to build recover key JSON object: %m"); json_variant_sensitive(e); w = json_variant_ref(json_variant_by_key(*v, "privileged")); l = json_variant_ref(json_variant_by_key(w, "recoveryKey")); r = json_variant_append_array(&l, e); if (r < 0) return log_error_errno(r, "Failed append recovery key: %m"); r = json_variant_set_field(&w, "recoveryKey", l); if (r < 0) return log_error_errno(r, "Failed to set recovery key array: %m"); r = json_variant_set_field(v, "privileged", w); if (r < 0) return log_error_errno(r, "Failed to update privileged field: %m"); return 0; } static int add_public(JsonVariant **v) { _cleanup_strv_free_ char **types = NULL; int r; assert(v); r = json_variant_strv(json_variant_by_key(*v, "recoveryKeyType"), &types); if (r < 0) return log_error_errno(r, "Failed to parse recovery key type list: %m"); r = strv_extend(&types, "modhex64"); if (r < 0) return log_oom(); r = json_variant_set_field_strv(v, "recoveryKeyType", types); if (r < 0) return log_error_errno(r, "Failed to update recovery key types: %m"); return 0; } static int add_secret(JsonVariant **v, const char *password) { _cleanup_(json_variant_unrefp) JsonVariant *w = NULL, *l = NULL; _cleanup_strv_free_erase_ char **passwords = NULL; int r; assert(v); assert(password); w = json_variant_ref(json_variant_by_key(*v, "secret")); l = json_variant_ref(json_variant_by_key(w, "password")); r = json_variant_strv(l, &passwords); if (r < 0) return log_error_errno(r, "Failed to convert password array: %m"); r = strv_extend(&passwords, password); if (r < 0) return log_oom(); r = json_variant_new_array_strv(&l, passwords); if (r < 0) return log_error_errno(r, "Failed to allocate new password array JSON: %m"); json_variant_sensitive(l); r = json_variant_set_field(&w, "password", l); if (r < 0) return log_error_errno(r, "Failed to update password field: %m"); r = json_variant_set_field(v, "secret", w); if (r < 0) return log_error_errno(r, "Failed to update secret object: %m"); return 0; } int identity_add_recovery_key(JsonVariant **v) { _cleanup_(erase_and_freep) char *password = NULL, *hashed = NULL; int r; assert(v); /* First, let's generate a secret key */ r = make_recovery_key(&password); if (r < 0) return log_error_errno(r, "Failed to generate recovery key: %m"); /* Let's UNIX hash it */ r = hash_password(password, &hashed); if (r < 0) return log_error_errno(errno_or_else(EINVAL), "Failed to UNIX hash secret key: %m"); /* Let's now add the "privileged" version of the recovery key */ r = add_privileged(v, hashed); if (r < 0) return r; /* Let's then add the public information about the recovery key */ r = add_public(v); if (r < 0) return r; /* Finally, let's add the new key to the secret part, too */ r = add_secret(v, password); if (r < 0) return r; /* We output the key itself with a trailing newline to stdout and the decoration around it to stderr * instead. */ fflush(stdout); fprintf(stderr, "A secret recovery key has been generated for this account:\n\n" " %s%s%s", emoji_enabled() ? special_glyph(SPECIAL_GLYPH_LOCK_AND_KEY) : "", emoji_enabled() ? " " : "", ansi_highlight()); fflush(stderr); fputs(password, stdout); fflush(stdout); fputs(ansi_normal(), stderr); fflush(stderr); fputc('\n', stdout); fflush(stdout); fputs("\nPlease save this secret recovery key at a secure location. It may be used to\n" "regain access to the account if the other configured access credentials have\n" "been lost or forgotten. The recovery key may be entered in place of a password\n" "whenever authentication is requested.\n", stderr); fflush(stderr); (void) print_qrcode(stderr, "You may optionally scan the recovery key off screen", password); return 0; }
5,491
32.084337
108
c
null
systemd-main/src/home/homed-conf.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "conf-parser.h" #include "constants.h" #include "home-util.h" #include "homed-conf.h" int manager_parse_config_file(Manager *m) { assert(m); return config_parse_config_file("homed.conf", "Home\0", config_item_perf_lookup, homed_gperf_lookup, CONFIG_PARSE_WARN, m); } DEFINE_CONFIG_PARSE_ENUM(config_parse_default_storage, user_storage, UserStorage, "Failed to parse default storage setting"); int config_parse_default_file_system_type( const char *unit, const char *filename, unsigned line, const char *section, unsigned section_line, const char *lvalue, int ltype, const char *rvalue, void *data, void *userdata) { char **s = ASSERT_PTR(data); assert(rvalue); if (!isempty(rvalue) && !supported_fstype(rvalue)) { log_syntax(unit, LOG_WARNING, filename, line, 0, "Unsupported file system, ignoring: %s", rvalue); return 0; } return free_and_strdup_warn(s, empty_to_null(rvalue)); }
1,279
28.767442
125
c
null
systemd-main/src/home/homed-home-bus.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-bus.h" #include "bus-object.h" #include "homed-home.h" int bus_home_client_is_trusted(Home *h, sd_bus_message *message); int bus_home_get_record_json(Home *h, sd_bus_message *message, char **ret, bool *ret_incomplete); int bus_home_method_activate(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_deactivate(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_unregister(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_realize(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_remove(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_fixate(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_authenticate(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_update(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_update_record(Home *home, sd_bus_message *message, UserRecord *hr, sd_bus_error *error); int bus_home_method_resize(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_change_password(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_lock(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_unlock(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_acquire(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_ref(sd_bus_message *message, void *userdata, sd_bus_error *error); int bus_home_method_release(sd_bus_message *message, void *userdata, sd_bus_error *error); extern const BusObjectImplementation home_object; int bus_home_path(Home *h, char **ret); int bus_home_emit_change(Home *h); int bus_home_emit_remove(Home *h);
1,943
54.542857
108
h
null
systemd-main/src/home/homed-manager.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <openssl/evp.h> #include "sd-bus.h" #include "sd-device.h" #include "sd-event.h" typedef struct Manager Manager; #include "hashmap.h" #include "homed-home.h" #include "varlink.h" /* The LUKS free disk space rebalancing logic goes through this state machine */ typedef enum RebalanceState { REBALANCE_OFF, /* No rebalancing enabled */ REBALANCE_IDLE, /* Rebalancing enabled, but currently nothing scheduled */ REBALANCE_WAITING, /* Rebalancing has been requested for a later point in time */ REBALANCE_PENDING, /* Rebalancing has been requested and will be executed ASAP */ REBALANCE_SHRINKING, /* Rebalancing ongoing, and we are running all shrinking operations */ REBALANCE_GROWING, /* Rebalancing ongoign, and we are running all growing operations */ _REBALANCE_STATE_MAX, _REBALANCE_STATE_INVALID = -1, } RebalanceState; struct Manager { sd_event *event; sd_bus *bus; Hashmap *polkit_registry; Hashmap *homes_by_uid; Hashmap *homes_by_name; Hashmap *homes_by_worker_pid; Hashmap *homes_by_sysfs; bool scan_slash_home; UserStorage default_storage; char *default_file_system_type; sd_event_source *inotify_event_source; /* An event source we receive sd_notify() messages from our worker from */ sd_event_source *notify_socket_event_source; sd_device_monitor *device_monitor; sd_event_source *deferred_rescan_event_source; sd_event_source *deferred_gc_event_source; sd_event_source *deferred_auto_login_event_source; sd_event_source *rebalance_event_source; Home *gc_focus; VarlinkServer *varlink_server; char *userdb_service; EVP_PKEY *private_key; /* actually a pair of private and public key */ Hashmap *public_keys; /* key name [char*] → public key [EVP_PKEY*] */ RebalanceState rebalance_state; usec_t rebalance_interval_usec; /* In order to allow synchronous rebalance requests via bus calls we maintain two pools of bus * messages: 'rebalance_pending_methods' are the method calls we are currently operating on and * running a rebalancing operation for. 'rebalance_queued_method_calls' are the method calls that * have been queued since then and that we'll operate on once we complete the current run. */ Set *rebalance_pending_method_calls, *rebalance_queued_method_calls; }; int manager_new(Manager **ret); Manager* manager_free(Manager *m); DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_free); int manager_startup(Manager *m); int manager_augment_record_with_uid(Manager *m, UserRecord *hr); int manager_enqueue_rescan(Manager *m); int manager_enqueue_gc(Manager *m, Home *focus); int manager_schedule_rebalance(Manager *m, bool immediately); int manager_reschedule_rebalance(Manager *m); int manager_verify_user_record(Manager *m, UserRecord *hr); int manager_acquire_key_pair(Manager *m); int manager_sign_user_record(Manager *m, UserRecord *u, UserRecord **ret, sd_bus_error *error); int bus_manager_emit_auto_login_changed(Manager *m);
3,272
33.819149
105
h
null
systemd-main/src/home/homed.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/stat.h> #include <sys/types.h> #include "bus-log-control-api.h" #include "daemon-util.h" #include "homed-manager.h" #include "homed-manager-bus.h" #include "log.h" #include "main-func.h" #include "service-util.h" #include "signal-util.h" static int run(int argc, char *argv[]) { _cleanup_(manager_freep) Manager *m = NULL; _unused_ _cleanup_(notify_on_cleanup) const char *notify_stop = NULL; int r; log_setup(); r = service_parse_argv("systemd-homed.service", "A service to create, remove, change or inspect home areas.", BUS_IMPLEMENTATIONS(&manager_object, &log_control_object), argc, argv); if (r <= 0) return r; umask(0022); assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD, SIGTERM, SIGINT, SIGRTMIN+18, -1) >= 0); r = manager_new(&m); if (r < 0) return log_error_errno(r, "Could not create manager: %m"); r = manager_startup(m); if (r < 0) return log_error_errno(r, "Failed to start up daemon: %m"); notify_stop = notify_start(NOTIFY_READY, NOTIFY_STOPPING); r = sd_event_loop(m->event); if (r < 0) return log_error_errno(r, "Event loop failed: %m"); return 0; } DEFINE_MAIN_FUNCTION(run);
1,512
28.096154
101
c
null
systemd-main/src/home/homework-directory.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "homework.h" #include "user-record.h" int home_setup_directory(UserRecord *h, HomeSetup *setup); int home_activate_directory(UserRecord *h, HomeSetupFlags flags, HomeSetup *setup, PasswordCache *cache, UserRecord **ret_home); int home_create_directory_or_subvolume(UserRecord *h, HomeSetup *setup, UserRecord **ret_home); int home_resize_directory(UserRecord *h, HomeSetupFlags flags, HomeSetup *setup, PasswordCache *cache, UserRecord **ret_home);
522
46.545455
128
h
null
systemd-main/src/home/homework-fido2.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fido.h> #include "hexdecoct.h" #include "homework-fido2.h" #include "libfido2-util.h" #include "memory-util.h" #include "strv.h" int fido2_use_token( UserRecord *h, UserRecord *secret, const Fido2HmacSalt *salt, char **ret) { _cleanup_(erase_and_freep) void *hmac = NULL; size_t hmac_size; Fido2EnrollFlags flags = 0; ssize_t ss; int r; assert(h); assert(secret); assert(salt); assert(ret); /* If we know the up/uv/clientPin settings used during enrollment, let's pass this on for * authentication, or generate errors immediately if interactivity of the specified kind is not * allowed. */ if (salt->up > 0) { if (h->fido2_user_presence_permitted <= 0) return -EMEDIUMTYPE; flags |= FIDO2ENROLL_UP; } else if (salt->up < 0) /* unset? */ flags |= FIDO2ENROLL_UP_IF_NEEDED; /* compat with pre-248 */ if (salt->uv > 0) { if (h->fido2_user_verification_permitted <= 0) return -ENOCSI; flags |= FIDO2ENROLL_UV; } else if (salt->uv < 0) flags |= FIDO2ENROLL_UV_OMIT; /* compat with pre-248 */ if (salt->client_pin > 0) { if (strv_isempty(secret->token_pin)) return -ENOANO; flags |= FIDO2ENROLL_PIN; } else if (salt->client_pin < 0) flags |= FIDO2ENROLL_PIN_IF_NEEDED; /* compat with pre-248 */ r = fido2_use_hmac_hash( NULL, "io.systemd.home", salt->salt, salt->salt_size, salt->credential.id, salt->credential.size, secret->token_pin, flags, &hmac, &hmac_size); if (r < 0) return r; ss = base64mem(hmac, hmac_size, ret); if (ss < 0) return log_error_errno(ss, "Failed to base64 encode HMAC secret: %m"); return 0; }
2,277
29.373333
103
c
null
systemd-main/src/home/homework-mount.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdbool.h> int home_mount_node(const char *node, const char *fstype, bool discard, unsigned long flags, const char *extra_mount_options); int home_unshare_and_mkdir(void); int home_unshare_and_mount(const char *node, const char *fstype, bool discard, unsigned long flags, const char *extra_mount_options); int home_move_mount(const char *user_name_and_realm, const char *target); int home_shift_uid(int dir_fd, const char *target, uid_t stored_uid, uid_t exposed_uid, int *ret_mount_fd);
562
50.181818
133
h
null
systemd-main/src/home/homework-password-cache.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "homework-password-cache.h" #include "keyring-util.h" #include "missing_syscall.h" #include "user-record.h" void password_cache_free(PasswordCache *cache) { if (!cache) return; cache->pkcs11_passwords = strv_free_erase(cache->pkcs11_passwords); cache->fido2_passwords = strv_free_erase(cache->fido2_passwords); cache->keyring_passswords = strv_free_erase(cache->keyring_passswords); } void password_cache_load_keyring(UserRecord *h, PasswordCache *cache) { _cleanup_(erase_and_freep) void *p = NULL; _cleanup_free_ char *name = NULL; char **strv; key_serial_t serial; size_t sz; int r; assert(h); assert(cache); /* Loads the password we need to for automatic resizing from the kernel keyring */ name = strjoin("homework-user-", h->user_name); if (!name) return (void) log_oom(); serial = request_key("user", name, NULL, 0); if (serial == -1) return (void) log_debug_errno(errno, "Failed to request key '%s', ignoring: %m", name); r = keyring_read(serial, &p, &sz); if (r < 0) return (void) log_debug_errno(r, "Failed to read keyring key '%s', ignoring: %m", name); if (memchr(p, 0, sz)) return (void) log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Cached password contains embedded NUL byte, ignoring."); strv = new(char*, 2); if (!strv) return (void) log_oom(); strv[0] = TAKE_PTR(p); /* Note that keyring_read() will NUL terminate implicitly, hence we don't have * to NUL terminate manually here: it's a valid string. */ strv[1] = NULL; strv_free_erase(cache->keyring_passswords); cache->keyring_passswords = strv; log_debug("Successfully acquired home key from kernel keyring."); }
1,996
33.431034
128
c
null
systemd-main/src/home/homework-password-cache.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "strv.h" #include "user-record.h" typedef struct PasswordCache { /* Passwords acquired from the kernel keyring */ char **keyring_passswords; /* Decoding passwords from security tokens is expensive and typically requires user interaction, * hence cache any we already figured out. */ char **pkcs11_passwords; char **fido2_passwords; } PasswordCache; void password_cache_free(PasswordCache *cache); static inline bool password_cache_contains(const PasswordCache *cache, const char *p) { if (!cache) return false; return strv_contains(cache->pkcs11_passwords, p) || strv_contains(cache->fido2_passwords, p) || strv_contains(cache->keyring_passswords, p); } void password_cache_load_keyring(UserRecord *h, PasswordCache *cache);
916
30.62069
104
h
null
systemd-main/src/home/homework-quota.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/quota.h> #include "blockdev-util.h" #include "btrfs-util.h" #include "errno-util.h" #include "format-util.h" #include "homework-quota.h" #include "missing_magic.h" #include "quota-util.h" #include "stat-util.h" #include "user-util.h" int home_update_quota_btrfs(UserRecord *h, const char *path) { int r; assert(h); assert(path); if (h->disk_size == UINT64_MAX) return 0; /* If the user wants quota, enable it */ r = btrfs_quota_enable(path, true); if (r == -ENOTTY) return log_error_errno(r, "No btrfs quota support on subvolume %s.", path); if (r < 0) return log_error_errno(r, "Failed to enable btrfs quota support on %s.", path); r = btrfs_qgroup_set_limit(path, 0, h->disk_size); if (r < 0) return log_error_errno(r, "Faled to set disk quota on subvolume %s: %m", path); log_info("Set btrfs quota."); return 0; } int home_update_quota_classic(UserRecord *h, const char *path) { struct dqblk req; dev_t devno; int r; assert(h); assert(uid_is_valid(h->uid)); assert(path); if (h->disk_size == UINT64_MAX) return 0; r = get_block_device(path, &devno); if (r < 0) return log_error_errno(r, "Failed to determine block device of %s: %m", path); if (devno == 0) return log_error_errno(SYNTHETIC_ERRNO(ENODEV), "File system %s not backed by a block device.", path); r = quotactl_devnum(QCMD_FIXED(Q_GETQUOTA, USRQUOTA), devno, h->uid, &req); if (r < 0) { if (ERRNO_IS_NOT_SUPPORTED(r)) return log_error_errno(r, "No UID quota support on %s.", path); if (r != -ESRCH) return log_error_errno(r, "Failed to query disk quota for UID " UID_FMT ": %m", h->uid); zero(req); } else { /* Shortcut things if everything is set up properly already */ if (FLAGS_SET(req.dqb_valid, QIF_BLIMITS) && h->disk_size / QIF_DQBLKSIZE == req.dqb_bhardlimit) { log_info("Configured quota already matches the intended setting, not updating quota."); return 0; } } req.dqb_valid = QIF_BLIMITS; req.dqb_bsoftlimit = req.dqb_bhardlimit = h->disk_size / QIF_DQBLKSIZE; r = quotactl_devnum(QCMD_FIXED(Q_SETQUOTA, USRQUOTA), devno, h->uid, &req); if (r < 0) { if (r == -ESRCH) return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "UID quota not available on %s.", path); return log_error_errno(r, "Failed to set disk quota for UID " UID_FMT ": %m", h->uid); } log_info("Updated per-UID quota."); return 0; } int home_update_quota_auto(UserRecord *h, const char *path) { struct statfs sfs; int r; assert(h); if (h->disk_size == UINT64_MAX) return 0; if (!path) { path = user_record_image_path(h); if (!path) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Home record lacks image path."); } if (statfs(path, &sfs) < 0) return log_error_errno(errno, "Failed to statfs() file system: %m"); if (is_fs_type(&sfs, XFS_SB_MAGIC) || is_fs_type(&sfs, EXT4_SUPER_MAGIC)) return home_update_quota_classic(h, path); if (is_fs_type(&sfs, BTRFS_SUPER_MAGIC)) { r = btrfs_is_subvol(path); if (r < 0) return log_error_errno(errno, "Failed to test if %s is a subvolume: %m", path); if (r == 0) return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Directory %s is not a subvolume, cannot apply quota.", path); return home_update_quota_btrfs(h, path); } return log_error_errno(SYNTHETIC_ERRNO(ENOTTY), "Type of directory %s not known, cannot apply quota.", path); }
4,238
32.912
134
c
null
systemd-main/src/home/user-record-password-quality.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "bus-common-errors.h" #include "errno-util.h" #include "home-util.h" #include "libcrypt-util.h" #include "password-quality-util.h" #include "strv.h" #include "user-record-password-quality.h" #include "user-record-util.h" #if HAVE_PASSWDQC || HAVE_PWQUALITY int user_record_check_password_quality( UserRecord *hr, UserRecord *secret, sd_bus_error *error) { _cleanup_free_ char *auxerror = NULL; int r; assert(hr); assert(secret); /* This is a bit more complex than one might think at first. check_password_quality() would like to know the * old password to make security checks. We support arbitrary numbers of passwords however, hence we * call the function once for each combination of old and new password. */ /* Iterate through all new passwords */ STRV_FOREACH(pp, secret->password) { bool called = false; r = test_password_many(hr->hashed_password, *pp); if (r < 0) return r; if (r == 0) /* This is an old password as it isn't listed in the hashedPassword field, skip it */ continue; /* Check this password against all old passwords */ STRV_FOREACH(old, secret->password) { if (streq(*pp, *old)) continue; r = test_password_many(hr->hashed_password, *old); if (r < 0) return r; if (r > 0) /* This is a new password, not suitable as old password */ continue; r = check_password_quality(*pp, *old, hr->user_name, &auxerror); if (r <= 0) goto error; called = true; } if (called) continue; /* If there are no old passwords, let's call check_password_quality() without any. */ r = check_password_quality(*pp, /* old */ NULL, hr->user_name, &auxerror); if (r <= 0) goto error; } return 1; error: if (r == 0) return sd_bus_error_setf(error, BUS_ERROR_LOW_PASSWORD_QUALITY, "Password too weak: %s", auxerror); if (ERRNO_IS_NOT_SUPPORTED(r)) return 0; return log_debug_errno(r, "Failed to check password quality: %m"); } #else int user_record_check_password_quality( UserRecord *hr, UserRecord *secret, sd_bus_error *error) { return 0; } #endif
2,878
31.715909
116
c
null
systemd-main/src/home/user-record-sign.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <openssl/evp.h> #include "user-record.h" int user_record_sign(UserRecord *ur, EVP_PKEY *private_key, UserRecord **ret); enum { USER_RECORD_UNSIGNED, /* user record has no signature */ USER_RECORD_SIGNED_EXCLUSIVE, /* user record has only a signature by our own key */ USER_RECORD_SIGNED, /* user record is signed by us, but by others too */ USER_RECORD_FOREIGN, /* user record is not signed by us, but by others */ }; int user_record_verify(UserRecord *ur, EVP_PKEY *public_key); int user_record_has_signature(UserRecord *ur);
671
32.6
93
h
null
systemd-main/src/hwdb/hwdb.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include "sd-hwdb.h" #include "alloc-util.h" #include "build.h" #include "hwdb-util.h" #include "main-func.h" #include "pretty-print.h" #include "selinux-util.h" #include "terminal-util.h" #include "verbs.h" static const char *arg_hwdb_bin_dir = NULL; static const char *arg_root = NULL; static bool arg_strict = false; static int verb_query(int argc, char *argv[], void *userdata) { return hwdb_query(argv[1], arg_root); } static int verb_update(int argc, char *argv[], void *userdata) { return hwdb_update(arg_root, arg_hwdb_bin_dir, arg_strict, false); } static int help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("systemd-hwdb", "8", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...] COMMAND ...\n\n" "%sUpdate or query the hardware database.%s\n" "\nCommands:\n" " update Update the hwdb database\n" " query MODALIAS Query database and print result\n" "\nOptions:\n" " -h --help Show this help\n" " --version Show package version\n" " -s --strict When updating, return non-zero exit value on any parsing error\n" " --usr Generate in " UDEVLIBEXECDIR " instead of /etc/udev\n" " -r --root=PATH Alternative root path in the filesystem\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_VERSION = 0x100, ARG_USR, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "usr", no_argument, NULL, ARG_USR }, { "strict", no_argument, NULL, 's' }, { "root", required_argument, NULL, 'r' }, {} }; int c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "sr:h", options, NULL)) >= 0) switch (c) { case 'h': return help(); case ARG_VERSION: return version(); case ARG_USR: arg_hwdb_bin_dir = UDEVLIBEXECDIR; break; case 's': arg_strict = true; break; case 'r': arg_root = optarg; break; case '?': return -EINVAL; default: assert_not_reached(); } return 1; } static int hwdb_main(int argc, char *argv[]) { static const Verb verbs[] = { { "update", 1, 1, 0, verb_update }, { "query", 2, 2, 0, verb_query }, {}, }; return dispatch_verb(argc, argv, verbs, NULL); } static int run(int argc, char *argv[]) { int r; log_parse_environment(); log_open(); r = parse_argv(argc, argv); if (r <= 0) return r; r = mac_init(); if (r < 0) return r; return hwdb_main(argc, argv); } DEFINE_MAIN_FUNCTION(run);
3,717
26.540741
99
c
null
systemd-main/src/id128/id128.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include <stdio.h> #include "alloc-util.h" #include "build.h" #include "gpt.h" #include "id128-print.h" #include "main-func.h" #include "pretty-print.h" #include "strv.h" #include "format-table.h" #include "terminal-util.h" #include "verbs.h" static Id128PrettyPrintMode arg_mode = ID128_PRINT_ID128; static sd_id128_t arg_app = {}; static int verb_new(int argc, char **argv, void *userdata) { return id128_print_new(arg_mode); } static int verb_machine_id(int argc, char **argv, void *userdata) { sd_id128_t id; int r; if (sd_id128_is_null(arg_app)) r = sd_id128_get_machine(&id); else r = sd_id128_get_machine_app_specific(arg_app, &id); if (r < 0) return log_error_errno(r, "Failed to get %smachine-ID: %m", sd_id128_is_null(arg_app) ? "" : "app-specific "); return id128_pretty_print(id, arg_mode); } static int verb_boot_id(int argc, char **argv, void *userdata) { sd_id128_t id; int r; if (sd_id128_is_null(arg_app)) r = sd_id128_get_boot(&id); else r = sd_id128_get_boot_app_specific(arg_app, &id); if (r < 0) return log_error_errno(r, "Failed to get %sboot-ID: %m", sd_id128_is_null(arg_app) ? "" : "app-specific "); return id128_pretty_print(id, arg_mode); } static int verb_invocation_id(int argc, char **argv, void *userdata) { sd_id128_t id; int r; if (!sd_id128_is_null(arg_app)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Verb \"invocation-id\" cannot be combined with --app-specific=."); r = sd_id128_get_invocation(&id); if (r < 0) return log_error_errno(r, "Failed to get invocation-ID: %m"); return id128_pretty_print(id, arg_mode); } static int show_one(Table **table, const char *name, sd_id128_t uuid, bool first) { int r; if (arg_mode == ID128_PRINT_PRETTY) { _cleanup_free_ char *id = NULL; id = strreplace(name, "-", "_"); if (!id) return log_oom(); ascii_strupper(id); r = id128_pretty_print_sample(id, uuid); if (r < 0) return r; if (!first) puts(""); return 0; } else { if (!*table) { *table = table_new("name", "id"); if (!*table) return log_oom(); table_set_width(*table, 0); } return table_add_many(*table, TABLE_STRING, name, arg_mode == ID128_PRINT_ID128 ? TABLE_ID128 : TABLE_UUID, uuid); } } static int verb_show(int argc, char **argv, void *userdata) { _cleanup_(table_unrefp) Table *table = NULL; int r; argv = strv_skip(argv, 1); if (strv_isempty(argv)) for (const GptPartitionType *e = gpt_partition_type_table; e->name; e++) { r = show_one(&table, e->name, e->uuid, e == gpt_partition_type_table); if (r < 0) return r; } else STRV_FOREACH(p, argv) { sd_id128_t uuid; bool have_uuid; const char *id; /* Check if the argument is an actual UUID first */ have_uuid = sd_id128_from_string(*p, &uuid) >= 0; if (have_uuid) id = gpt_partition_type_uuid_to_string(uuid) ?: "XYZ"; else { GptPartitionType type; r = gpt_partition_type_from_string(*p, &type); if (r < 0) return log_error_errno(r, "Unknown identifier \"%s\".", *p); uuid = type.uuid; id = *p; } r = show_one(&table, id, uuid, p == argv); if (r < 0) return r; } if (table) { r = table_print(table, NULL); if (r < 0) return table_log_print_error(r); } return 0; } static int help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("systemd-id128", "1", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...] COMMAND\n\n" "%sGenerate and print 128-bit identifiers.%s\n" "\nCommands:\n" " new Generate a new ID\n" " machine-id Print the ID of current machine\n" " boot-id Print the ID of current boot\n" " invocation-id Print the ID of current invocation\n" " show [NAME] Print one or more well-known GPT partition type IDs\n" " help Show this help\n" "\nOptions:\n" " -h --help Show this help\n" " -p --pretty Generate samples of program code\n" " -a --app-specific=ID Generate app-specific IDs\n" " -u --uuid Output in UUID format\n" "\nSee the %s for details.\n", program_invocation_short_name, ansi_highlight(), ansi_normal(), link); return 0; } static int verb_help(int argc, char **argv, void *userdata) { return help(); } static int parse_argv(int argc, char *argv[]) { enum { ARG_VERSION = 0x100, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "pretty", no_argument, NULL, 'p' }, { "app-specific", required_argument, NULL, 'a' }, { "uuid", no_argument, NULL, 'u' }, {}, }; int c, r; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "hpa:u", options, NULL)) >= 0) switch (c) { case 'h': return help(); case ARG_VERSION: return version(); case 'p': arg_mode = ID128_PRINT_PRETTY; break; case 'a': r = sd_id128_from_string(optarg, &arg_app); if (r < 0) return log_error_errno(r, "Failed to parse \"%s\" as application-ID: %m", optarg); break; case 'u': arg_mode = ID128_PRINT_UUID; break; case '?': return -EINVAL; default: assert_not_reached(); } return 1; } static int id128_main(int argc, char *argv[]) { static const Verb verbs[] = { { "new", VERB_ANY, 1, 0, verb_new }, { "machine-id", VERB_ANY, 1, 0, verb_machine_id }, { "boot-id", VERB_ANY, 1, 0, verb_boot_id }, { "invocation-id", VERB_ANY, 1, 0, verb_invocation_id }, { "show", VERB_ANY, VERB_ANY, 0, verb_show }, { "help", VERB_ANY, VERB_ANY, 0, verb_help }, {} }; return dispatch_verb(argc, argv, verbs, NULL); } static int run(int argc, char *argv[]) { int r; log_setup(); r = parse_argv(argc, argv); if (r <= 0) return r; return id128_main(argc, argv); } DEFINE_MAIN_FUNCTION(run);
8,686
31.905303
114
c
null
systemd-main/src/import/curl-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include "alloc-util.h" #include "curl-util.h" #include "fd-util.h" #include "locale-util.h" #include "string-util.h" #include "version.h" static void curl_glue_check_finished(CurlGlue *g) { CURLMsg *msg; int k = 0; assert(g); msg = curl_multi_info_read(g->curl, &k); if (!msg) return; if (msg->msg != CURLMSG_DONE) return; if (g->on_finished) g->on_finished(g, msg->easy_handle, msg->data.result); } static int curl_glue_on_io(sd_event_source *s, int fd, uint32_t revents, void *userdata) { CurlGlue *g = ASSERT_PTR(userdata); int action, k = 0; assert(s); if (FLAGS_SET(revents, EPOLLIN | EPOLLOUT)) action = CURL_POLL_INOUT; else if (revents & EPOLLIN) action = CURL_POLL_IN; else if (revents & EPOLLOUT) action = CURL_POLL_OUT; else action = 0; if (curl_multi_socket_action(g->curl, fd, action, &k) != CURLM_OK) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to propagate IO event."); curl_glue_check_finished(g); return 0; } static int curl_glue_socket_callback(CURL *curl, curl_socket_t s, int action, void *userdata, void *socketp) { sd_event_source *io = socketp; CurlGlue *g = ASSERT_PTR(userdata); uint32_t events = 0; int r; assert(curl); if (action == CURL_POLL_REMOVE) { if (io) { sd_event_source_disable_unref(io); hashmap_remove(g->ios, FD_TO_PTR(s)); } return 0; } r = hashmap_ensure_allocated(&g->ios, &trivial_hash_ops); if (r < 0) { log_oom(); return -1; } if (action == CURL_POLL_IN) events = EPOLLIN; else if (action == CURL_POLL_OUT) events = EPOLLOUT; else if (action == CURL_POLL_INOUT) events = EPOLLIN|EPOLLOUT; if (io) { if (sd_event_source_set_io_events(io, events) < 0) return -1; if (sd_event_source_set_enabled(io, SD_EVENT_ON) < 0) return -1; } else { if (sd_event_add_io(g->event, &io, s, events, curl_glue_on_io, g) < 0) return -1; if (curl_multi_assign(g->curl, s, io) != CURLM_OK) return -1; (void) sd_event_source_set_description(io, "curl-io"); r = hashmap_put(g->ios, FD_TO_PTR(s), io); if (r < 0) { log_oom(); sd_event_source_unref(io); return -1; } } return 0; } static int curl_glue_on_timer(sd_event_source *s, uint64_t usec, void *userdata) { CurlGlue *g = ASSERT_PTR(userdata); int k = 0; assert(s); if (curl_multi_socket_action(g->curl, CURL_SOCKET_TIMEOUT, 0, &k) != CURLM_OK) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to propagate timeout."); curl_glue_check_finished(g); return 0; } static int curl_glue_timer_callback(CURLM *curl, long timeout_ms, void *userdata) { CurlGlue *g = ASSERT_PTR(userdata); usec_t usec; assert(curl); if (timeout_ms < 0) { if (g->timer) { if (sd_event_source_set_enabled(g->timer, SD_EVENT_OFF) < 0) return -1; } return 0; } usec = (usec_t) timeout_ms * USEC_PER_MSEC + USEC_PER_MSEC - 1; if (g->timer) { if (sd_event_source_set_time_relative(g->timer, usec) < 0) return -1; if (sd_event_source_set_enabled(g->timer, SD_EVENT_ONESHOT) < 0) return -1; } else { if (sd_event_add_time_relative(g->event, &g->timer, CLOCK_BOOTTIME, usec, 0, curl_glue_on_timer, g) < 0) return -1; (void) sd_event_source_set_description(g->timer, "curl-timer"); } return 0; } CurlGlue *curl_glue_unref(CurlGlue *g) { sd_event_source *io; if (!g) return NULL; if (g->curl) curl_multi_cleanup(g->curl); while ((io = hashmap_steal_first(g->ios))) sd_event_source_unref(io); hashmap_free(g->ios); sd_event_source_unref(g->timer); sd_event_unref(g->event); return mfree(g); } int curl_glue_new(CurlGlue **glue, sd_event *event) { _cleanup_(curl_glue_unrefp) CurlGlue *g = NULL; _cleanup_(curl_multi_cleanupp) CURLM *c = NULL; _cleanup_(sd_event_unrefp) sd_event *e = NULL; int r; if (event) e = sd_event_ref(event); else { r = sd_event_default(&e); if (r < 0) return r; } c = curl_multi_init(); if (!c) return -ENOMEM; g = new(CurlGlue, 1); if (!g) return -ENOMEM; *g = (CurlGlue) { .event = TAKE_PTR(e), .curl = TAKE_PTR(c), }; if (curl_multi_setopt(g->curl, CURLMOPT_SOCKETDATA, g) != CURLM_OK) return -EINVAL; if (curl_multi_setopt(g->curl, CURLMOPT_SOCKETFUNCTION, curl_glue_socket_callback) != CURLM_OK) return -EINVAL; if (curl_multi_setopt(g->curl, CURLMOPT_TIMERDATA, g) != CURLM_OK) return -EINVAL; if (curl_multi_setopt(g->curl, CURLMOPT_TIMERFUNCTION, curl_glue_timer_callback) != CURLM_OK) return -EINVAL; *glue = TAKE_PTR(g); return 0; } int curl_glue_make(CURL **ret, const char *url, void *userdata) { _cleanup_(curl_easy_cleanupp) CURL *c = NULL; const char *useragent; assert(ret); assert(url); c = curl_easy_init(); if (!c) return -ENOMEM; if (DEBUG_LOGGING) (void) curl_easy_setopt(c, CURLOPT_VERBOSE, 1L); if (curl_easy_setopt(c, CURLOPT_URL, url) != CURLE_OK) return -EIO; if (curl_easy_setopt(c, CURLOPT_PRIVATE, userdata) != CURLE_OK) return -EIO; useragent = strjoina(program_invocation_short_name, "/" GIT_VERSION); if (curl_easy_setopt(c, CURLOPT_USERAGENT, useragent) != CURLE_OK) return -EIO; if (curl_easy_setopt(c, CURLOPT_FOLLOWLOCATION, 1L) != CURLE_OK) return -EIO; if (curl_easy_setopt(c, CURLOPT_NOSIGNAL, 1L) != CURLE_OK) return -EIO; if (curl_easy_setopt(c, CURLOPT_LOW_SPEED_TIME, 60L) != CURLE_OK) return -EIO; if (curl_easy_setopt(c, CURLOPT_LOW_SPEED_LIMIT, 30L) != CURLE_OK) return -EIO; #if LIBCURL_VERSION_NUM >= 0x075500 /* libcurl 7.85.0 */ if (curl_easy_setopt(c, CURLOPT_PROTOCOLS_STR, "HTTP,HTTPS,FILE") != CURLE_OK) #else if (curl_easy_setopt(c, CURLOPT_PROTOCOLS, CURLPROTO_HTTP|CURLPROTO_HTTPS|CURLPROTO_FILE) != CURLE_OK) #endif return -EIO; *ret = TAKE_PTR(c); return 0; } int curl_glue_add(CurlGlue *g, CURL *c) { assert(g); assert(c); if (curl_multi_add_handle(g->curl, c) != CURLM_OK) return -EIO; return 0; } void curl_glue_remove_and_free(CurlGlue *g, CURL *c) { assert(g); if (!c) return; if (g->curl) curl_multi_remove_handle(g->curl, c); curl_easy_cleanup(c); } struct curl_slist *curl_slist_new(const char *first, ...) { struct curl_slist *l; va_list ap; if (!first) return NULL; l = curl_slist_append(NULL, first); if (!l) return NULL; va_start(ap, first); for (;;) { struct curl_slist *n; const char *i; i = va_arg(ap, const char*); if (!i) break; n = curl_slist_append(l, i); if (!n) { va_end(ap); curl_slist_free_all(l); return NULL; } l = n; } va_end(ap); return l; } int curl_header_strdup(const void *contents, size_t sz, const char *field, char **value) { const char *p; char *s; p = memory_startswith_no_case(contents, sz, field); if (!p) return 0; sz -= p - (const char*) contents; if (memchr(p, 0, sz)) return 0; /* Skip over preceding whitespace */ while (sz > 0 && strchr(WHITESPACE, p[0])) { p++; sz--; } /* Truncate trailing whitespace */ while (sz > 0 && strchr(WHITESPACE, p[sz-1])) sz--; s = strndup(p, sz); if (!s) return -ENOMEM; *value = s; return 1; } int curl_parse_http_time(const char *t, usec_t *ret) { _cleanup_(freelocalep) locale_t loc = (locale_t) 0; const char *e; struct tm tm; time_t v; assert(t); assert(ret); loc = newlocale(LC_TIME_MASK, "C", (locale_t) 0); if (loc == (locale_t) 0) return -errno; /* RFC822 */ e = strptime_l(t, "%a, %d %b %Y %H:%M:%S %Z", &tm, loc); if (!e || *e != 0) /* RFC 850 */ e = strptime_l(t, "%A, %d-%b-%y %H:%M:%S %Z", &tm, loc); if (!e || *e != 0) /* ANSI C */ e = strptime_l(t, "%a %b %d %H:%M:%S %Y", &tm, loc); if (!e || *e != 0) return -EINVAL; v = timegm(&tm); if (v == (time_t) -1) return -EINVAL; *ret = (usec_t) v * USEC_PER_SEC; return 0; }
10,440
26.119481
120
c
null
systemd-main/src/import/curl-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <curl/curl.h> #include <sys/types.h> #include "sd-event.h" #include "hashmap.h" #include "time-util.h" typedef struct CurlGlue CurlGlue; struct CurlGlue { sd_event *event; CURLM *curl; sd_event_source *timer; Hashmap *ios; void (*on_finished)(CurlGlue *g, CURL *curl, CURLcode code); void *userdata; }; int curl_glue_new(CurlGlue **glue, sd_event *event); CurlGlue* curl_glue_unref(CurlGlue *glue); DEFINE_TRIVIAL_CLEANUP_FUNC(CurlGlue*, curl_glue_unref); int curl_glue_make(CURL **ret, const char *url, void *userdata); int curl_glue_add(CurlGlue *g, CURL *c); void curl_glue_remove_and_free(CurlGlue *g, CURL *c); struct curl_slist *curl_slist_new(const char *first, ...) _sentinel_; int curl_header_strdup(const void *contents, size_t sz, const char *field, char **value); int curl_parse_http_time(const char *t, usec_t *ret); DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(CURL*, curl_easy_cleanup, NULL); DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(CURLM*, curl_multi_cleanup, NULL); DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct curl_slist*, curl_slist_free_all, NULL);
1,175
28.4
89
h
null
systemd-main/src/import/export-raw.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/sendfile.h> #include "sd-daemon.h" #include "alloc-util.h" #include "btrfs-util.h" #include "copy.h" #include "export-raw.h" #include "fd-util.h" #include "fs-util.h" #include "import-common.h" #include "missing_fcntl.h" #include "ratelimit.h" #include "stat-util.h" #include "string-util.h" #include "tmpfile-util.h" #define COPY_BUFFER_SIZE (16*1024) struct RawExport { sd_event *event; RawExportFinished on_finished; void *userdata; char *path; int input_fd; int output_fd; ImportCompress compress; sd_event_source *output_event_source; void *buffer; size_t buffer_size; size_t buffer_allocated; uint64_t written_compressed; uint64_t written_uncompressed; unsigned last_percent; RateLimit progress_ratelimit; struct stat st; bool eof; bool tried_reflink; bool tried_sendfile; }; RawExport *raw_export_unref(RawExport *e) { if (!e) return NULL; sd_event_source_unref(e->output_event_source); import_compress_free(&e->compress); sd_event_unref(e->event); safe_close(e->input_fd); free(e->buffer); free(e->path); return mfree(e); } int raw_export_new( RawExport **ret, sd_event *event, RawExportFinished on_finished, void *userdata) { _cleanup_(raw_export_unrefp) RawExport *e = NULL; int r; assert(ret); e = new(RawExport, 1); if (!e) return -ENOMEM; *e = (RawExport) { .output_fd = -EBADF, .input_fd = -EBADF, .on_finished = on_finished, .userdata = userdata, .last_percent = UINT_MAX, .progress_ratelimit = { 100 * USEC_PER_MSEC, 1 }, }; if (event) e->event = sd_event_ref(event); else { r = sd_event_default(&e->event); if (r < 0) return r; } *ret = TAKE_PTR(e); return 0; } static void raw_export_report_progress(RawExport *e) { unsigned percent; assert(e); if (e->written_uncompressed >= (uint64_t) e->st.st_size) percent = 100; else percent = (unsigned) ((e->written_uncompressed * UINT64_C(100)) / (uint64_t) e->st.st_size); if (percent == e->last_percent) return; if (!ratelimit_below(&e->progress_ratelimit)) return; sd_notifyf(false, "X_IMPORT_PROGRESS=%u", percent); log_info("Exported %u%%.", percent); e->last_percent = percent; } static int raw_export_process(RawExport *e) { ssize_t l; int r; assert(e); if (!e->tried_reflink && e->compress.type == IMPORT_COMPRESS_UNCOMPRESSED) { /* If we shall take an uncompressed snapshot we can * reflink source to destination directly. Let's see * if this works. */ r = reflink(e->input_fd, e->output_fd); if (r >= 0) { r = 0; goto finish; } e->tried_reflink = true; } if (!e->tried_sendfile && e->compress.type == IMPORT_COMPRESS_UNCOMPRESSED) { l = sendfile(e->output_fd, e->input_fd, NULL, COPY_BUFFER_SIZE); if (l < 0) { if (errno == EAGAIN) return 0; e->tried_sendfile = true; } else if (l == 0) { r = 0; goto finish; } else { e->written_uncompressed += l; e->written_compressed += l; raw_export_report_progress(e); return 0; } } while (e->buffer_size <= 0) { uint8_t input[COPY_BUFFER_SIZE]; if (e->eof) { r = 0; goto finish; } l = read(e->input_fd, input, sizeof(input)); if (l < 0) { r = log_error_errno(errno, "Failed to read raw file: %m"); goto finish; } if (l == 0) { e->eof = true; r = import_compress_finish(&e->compress, &e->buffer, &e->buffer_size, &e->buffer_allocated); } else { e->written_uncompressed += l; r = import_compress(&e->compress, input, l, &e->buffer, &e->buffer_size, &e->buffer_allocated); } if (r < 0) { r = log_error_errno(r, "Failed to encode: %m"); goto finish; } } l = write(e->output_fd, e->buffer, e->buffer_size); if (l < 0) { if (errno == EAGAIN) return 0; r = log_error_errno(errno, "Failed to write output file: %m"); goto finish; } assert((size_t) l <= e->buffer_size); memmove(e->buffer, (uint8_t*) e->buffer + l, e->buffer_size - l); e->buffer_size -= l; e->written_compressed += l; raw_export_report_progress(e); return 0; finish: if (r >= 0) { (void) copy_times(e->input_fd, e->output_fd, COPY_CRTIME); (void) copy_xattr(e->input_fd, NULL, e->output_fd, NULL, 0); } if (e->on_finished) e->on_finished(e, r, e->userdata); else sd_event_exit(e->event, r); return 0; } static int raw_export_on_output(sd_event_source *s, int fd, uint32_t revents, void *userdata) { RawExport *i = userdata; return raw_export_process(i); } static int raw_export_on_defer(sd_event_source *s, void *userdata) { RawExport *i = userdata; return raw_export_process(i); } static int reflink_snapshot(int fd, const char *path) { int new_fd, r; new_fd = open_parent(path, O_TMPFILE|O_CLOEXEC|O_RDWR, 0600); if (new_fd < 0) { _cleanup_free_ char *t = NULL; r = tempfn_random(path, NULL, &t); if (r < 0) return r; new_fd = open(t, O_CLOEXEC|O_CREAT|O_NOCTTY|O_RDWR, 0600); if (new_fd < 0) return -errno; (void) unlink(t); } r = reflink(fd, new_fd); if (r < 0) { safe_close(new_fd); return r; } return new_fd; } int raw_export_start(RawExport *e, const char *path, int fd, ImportCompressType compress) { _cleanup_close_ int sfd = -EBADF, tfd = -EBADF; int r; assert(e); assert(path); assert(fd >= 0); assert(compress < _IMPORT_COMPRESS_TYPE_MAX); assert(compress != IMPORT_COMPRESS_UNKNOWN); if (e->output_fd >= 0) return -EBUSY; r = fd_nonblock(fd, true); if (r < 0) return r; r = free_and_strdup(&e->path, path); if (r < 0) return r; sfd = open(path, O_RDONLY|O_CLOEXEC|O_NOCTTY); if (sfd < 0) return -errno; if (fstat(sfd, &e->st) < 0) return -errno; r = stat_verify_regular(&e->st); if (r < 0) return r; /* Try to take a reflink snapshot of the file, if we can t make the export atomic */ tfd = reflink_snapshot(sfd, path); if (tfd >= 0) e->input_fd = TAKE_FD(tfd); else e->input_fd = TAKE_FD(sfd); r = import_compress_init(&e->compress, compress); if (r < 0) return r; r = sd_event_add_io(e->event, &e->output_event_source, fd, EPOLLOUT, raw_export_on_output, e); if (r == -EPERM) { r = sd_event_add_defer(e->event, &e->output_event_source, raw_export_on_defer, e); if (r < 0) return r; r = sd_event_source_set_enabled(e->output_event_source, SD_EVENT_ON); } if (r < 0) return r; e->output_fd = fd; return r; }
8,682
25.716923
119
c
null
systemd-main/src/import/export-raw.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-event.h" #include "import-compress.h" #include "macro.h" typedef struct RawExport RawExport; typedef void (*RawExportFinished)(RawExport *export, int error, void *userdata); int raw_export_new(RawExport **export, sd_event *event, RawExportFinished on_finished, void *userdata); RawExport* raw_export_unref(RawExport *export); DEFINE_TRIVIAL_CLEANUP_FUNC(RawExport*, raw_export_unref); int raw_export_start(RawExport *export, const char *path, int fd, ImportCompressType compress);
563
28.684211
103
h
null
systemd-main/src/import/export-tar.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "sd-daemon.h" #include "alloc-util.h" #include "btrfs-util.h" #include "export-tar.h" #include "fd-util.h" #include "import-common.h" #include "process-util.h" #include "ratelimit.h" #include "string-util.h" #include "tmpfile-util.h" #define COPY_BUFFER_SIZE (16*1024) struct TarExport { sd_event *event; TarExportFinished on_finished; void *userdata; char *path; char *temp_path; int output_fd; int tar_fd; ImportCompress compress; sd_event_source *output_event_source; void *buffer; size_t buffer_size; size_t buffer_allocated; uint64_t written_compressed; uint64_t written_uncompressed; pid_t tar_pid; struct stat st; uint64_t quota_referenced; unsigned last_percent; RateLimit progress_ratelimit; bool eof; bool tried_splice; }; TarExport *tar_export_unref(TarExport *e) { if (!e) return NULL; sd_event_source_unref(e->output_event_source); if (e->tar_pid > 1) sigkill_wait(e->tar_pid); if (e->temp_path) { (void) btrfs_subvol_remove(e->temp_path, BTRFS_REMOVE_QUOTA); free(e->temp_path); } import_compress_free(&e->compress); sd_event_unref(e->event); safe_close(e->tar_fd); free(e->buffer); free(e->path); return mfree(e); } int tar_export_new( TarExport **ret, sd_event *event, TarExportFinished on_finished, void *userdata) { _cleanup_(tar_export_unrefp) TarExport *e = NULL; int r; assert(ret); e = new(TarExport, 1); if (!e) return -ENOMEM; *e = (TarExport) { .output_fd = -EBADF, .tar_fd = -EBADF, .on_finished = on_finished, .userdata = userdata, .quota_referenced = UINT64_MAX, .last_percent = UINT_MAX, .progress_ratelimit = { 100 * USEC_PER_MSEC, 1 }, }; if (event) e->event = sd_event_ref(event); else { r = sd_event_default(&e->event); if (r < 0) return r; } *ret = TAKE_PTR(e); return 0; } static void tar_export_report_progress(TarExport *e) { unsigned percent; assert(e); /* Do we have any quota info? If not, we don't know anything about the progress */ if (e->quota_referenced == UINT64_MAX) return; if (e->written_uncompressed >= e->quota_referenced) percent = 100; else percent = (unsigned) ((e->written_uncompressed * UINT64_C(100)) / e->quota_referenced); if (percent == e->last_percent) return; if (!ratelimit_below(&e->progress_ratelimit)) return; sd_notifyf(false, "X_IMPORT_PROGRESS=%u", percent); log_info("Exported %u%%.", percent); e->last_percent = percent; } static int tar_export_finish(TarExport *e) { int r; assert(e); assert(e->tar_fd >= 0); if (e->tar_pid > 0) { r = wait_for_terminate_and_check("tar", TAKE_PID(e->tar_pid), WAIT_LOG); if (r < 0) return r; if (r != EXIT_SUCCESS) return -EPROTO; } e->tar_fd = safe_close(e->tar_fd); return 0; } static int tar_export_process(TarExport *e) { ssize_t l; int r; assert(e); if (!e->tried_splice && e->compress.type == IMPORT_COMPRESS_UNCOMPRESSED) { l = splice(e->tar_fd, NULL, e->output_fd, NULL, COPY_BUFFER_SIZE, 0); if (l < 0) { if (errno == EAGAIN) return 0; e->tried_splice = true; } else if (l == 0) { r = tar_export_finish(e); goto finish; } else { e->written_uncompressed += l; e->written_compressed += l; tar_export_report_progress(e); return 0; } } while (e->buffer_size <= 0) { uint8_t input[COPY_BUFFER_SIZE]; if (e->eof) { r = tar_export_finish(e); goto finish; } l = read(e->tar_fd, input, sizeof(input)); if (l < 0) { r = log_error_errno(errno, "Failed to read tar file: %m"); goto finish; } if (l == 0) { e->eof = true; r = import_compress_finish(&e->compress, &e->buffer, &e->buffer_size, &e->buffer_allocated); } else { e->written_uncompressed += l; r = import_compress(&e->compress, input, l, &e->buffer, &e->buffer_size, &e->buffer_allocated); } if (r < 0) { r = log_error_errno(r, "Failed to encode: %m"); goto finish; } } l = write(e->output_fd, e->buffer, e->buffer_size); if (l < 0) { if (errno == EAGAIN) return 0; r = log_error_errno(errno, "Failed to write output file: %m"); goto finish; } assert((size_t) l <= e->buffer_size); memmove(e->buffer, (uint8_t*) e->buffer + l, e->buffer_size - l); e->buffer_size -= l; e->written_compressed += l; tar_export_report_progress(e); return 0; finish: if (e->on_finished) e->on_finished(e, r, e->userdata); else sd_event_exit(e->event, r); return 0; } static int tar_export_on_output(sd_event_source *s, int fd, uint32_t revents, void *userdata) { TarExport *i = userdata; return tar_export_process(i); } static int tar_export_on_defer(sd_event_source *s, void *userdata) { TarExport *i = userdata; return tar_export_process(i); } int tar_export_start(TarExport *e, const char *path, int fd, ImportCompressType compress) { _cleanup_close_ int sfd = -EBADF; int r; assert(e); assert(path); assert(fd >= 0); assert(compress < _IMPORT_COMPRESS_TYPE_MAX); assert(compress != IMPORT_COMPRESS_UNKNOWN); if (e->output_fd >= 0) return -EBUSY; sfd = open(path, O_DIRECTORY|O_RDONLY|O_NOCTTY|O_CLOEXEC); if (sfd < 0) return -errno; if (fstat(sfd, &e->st) < 0) return -errno; r = fd_nonblock(fd, true); if (r < 0) return r; r = free_and_strdup(&e->path, path); if (r < 0) return r; e->quota_referenced = UINT64_MAX; if (btrfs_might_be_subvol(&e->st)) { BtrfsQuotaInfo q; r = btrfs_subvol_get_subtree_quota_fd(sfd, 0, &q); if (r >= 0) e->quota_referenced = q.referenced; e->temp_path = mfree(e->temp_path); r = tempfn_random(path, NULL, &e->temp_path); if (r < 0) return r; /* Let's try to make a snapshot, if we can, so that the export is atomic */ r = btrfs_subvol_snapshot_at(sfd, NULL, AT_FDCWD, e->temp_path, BTRFS_SNAPSHOT_READ_ONLY|BTRFS_SNAPSHOT_RECURSIVE); if (r < 0) { log_debug_errno(r, "Couldn't create snapshot %s of %s, not exporting atomically: %m", e->temp_path, path); e->temp_path = mfree(e->temp_path); } } r = import_compress_init(&e->compress, compress); if (r < 0) return r; r = sd_event_add_io(e->event, &e->output_event_source, fd, EPOLLOUT, tar_export_on_output, e); if (r == -EPERM) { r = sd_event_add_defer(e->event, &e->output_event_source, tar_export_on_defer, e); if (r < 0) return r; r = sd_event_source_set_enabled(e->output_event_source, SD_EVENT_ON); } if (r < 0) return r; e->tar_fd = import_fork_tar_c(e->temp_path ?: e->path, &e->tar_pid); if (e->tar_fd < 0) { e->output_event_source = sd_event_source_unref(e->output_event_source); return e->tar_fd; } e->output_fd = fd; return r; }
9,017
26.577982
131
c
null
systemd-main/src/import/export-tar.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-event.h" #include "import-compress.h" #include "macro.h" typedef struct TarExport TarExport; typedef void (*TarExportFinished)(TarExport *export, int error, void *userdata); int tar_export_new(TarExport **export, sd_event *event, TarExportFinished on_finished, void *userdata); TarExport* tar_export_unref(TarExport *export); DEFINE_TRIVIAL_CLEANUP_FUNC(TarExport*, tar_export_unref); int tar_export_start(TarExport *export, const char *path, int fd, ImportCompressType compress);
563
28.684211
103
h
null
systemd-main/src/import/import-common.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <sys/types.h> #include "sd-event.h" typedef enum ImportFlags { IMPORT_FORCE = 1 << 0, /* replace existing image */ IMPORT_READ_ONLY = 1 << 1, /* make generated image read-only */ IMPORT_BTRFS_SUBVOL = 1 << 2, /* tar: preferably create images as btrfs subvols */ IMPORT_BTRFS_QUOTA = 1 << 3, /* tar: set up btrfs quota for new subvolume as child of parent subvolume */ IMPORT_CONVERT_QCOW2 = 1 << 4, /* raw: if we detect a qcow2 image, unpack it */ IMPORT_DIRECT = 1 << 5, /* import without rename games */ IMPORT_SYNC = 1 << 6, /* fsync() right before we are done */ IMPORT_FLAGS_MASK_TAR = IMPORT_FORCE|IMPORT_READ_ONLY|IMPORT_BTRFS_SUBVOL|IMPORT_BTRFS_QUOTA|IMPORT_DIRECT|IMPORT_SYNC, IMPORT_FLAGS_MASK_RAW = IMPORT_FORCE|IMPORT_READ_ONLY|IMPORT_CONVERT_QCOW2|IMPORT_DIRECT|IMPORT_SYNC, } ImportFlags; int import_fork_tar_c(const char *path, pid_t *ret); int import_fork_tar_x(const char *path, pid_t *ret); int import_mangle_os_tree(const char *path); bool import_validate_local(const char *name, ImportFlags flags); int import_allocate_event_with_signals(sd_event **ret);
1,265
42.655172
127
h
null
systemd-main/src/import/import-compress.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "import-compress.h" #include "string-table.h" void import_compress_free(ImportCompress *c) { assert(c); if (c->type == IMPORT_COMPRESS_XZ) lzma_end(&c->xz); else if (c->type == IMPORT_COMPRESS_GZIP) { if (c->encoding) deflateEnd(&c->gzip); else inflateEnd(&c->gzip); #if HAVE_BZIP2 } else if (c->type == IMPORT_COMPRESS_BZIP2) { if (c->encoding) BZ2_bzCompressEnd(&c->bzip2); else BZ2_bzDecompressEnd(&c->bzip2); #endif } c->type = IMPORT_COMPRESS_UNKNOWN; } int import_uncompress_detect(ImportCompress *c, const void *data, size_t size) { static const uint8_t xz_signature[] = { 0xfd, '7', 'z', 'X', 'Z', 0x00 }; static const uint8_t gzip_signature[] = { 0x1f, 0x8b }; static const uint8_t bzip2_signature[] = { 'B', 'Z', 'h' }; int r; assert(c); if (c->type != IMPORT_COMPRESS_UNKNOWN) return 1; if (size < MAX3(sizeof(xz_signature), sizeof(gzip_signature), sizeof(bzip2_signature))) return 0; assert(data); if (memcmp(data, xz_signature, sizeof(xz_signature)) == 0) { lzma_ret xzr; xzr = lzma_stream_decoder(&c->xz, UINT64_MAX, LZMA_TELL_UNSUPPORTED_CHECK | LZMA_CONCATENATED); if (xzr != LZMA_OK) return -EIO; c->type = IMPORT_COMPRESS_XZ; } else if (memcmp(data, gzip_signature, sizeof(gzip_signature)) == 0) { r = inflateInit2(&c->gzip, 15+16); if (r != Z_OK) return -EIO; c->type = IMPORT_COMPRESS_GZIP; #if HAVE_BZIP2 } else if (memcmp(data, bzip2_signature, sizeof(bzip2_signature)) == 0) { r = BZ2_bzDecompressInit(&c->bzip2, 0, 0); if (r != BZ_OK) return -EIO; c->type = IMPORT_COMPRESS_BZIP2; #endif } else c->type = IMPORT_COMPRESS_UNCOMPRESSED; c->encoding = false; return 1; } void import_uncompress_force_off(ImportCompress *c) { assert(c); c->type = IMPORT_COMPRESS_UNCOMPRESSED; c->encoding = false; } int import_uncompress(ImportCompress *c, const void *data, size_t size, ImportCompressCallback callback, void *userdata) { int r; assert(c); assert(callback); r = import_uncompress_detect(c, data, size); if (r <= 0) return r; if (c->encoding) return -EINVAL; if (size <= 0) return 1; assert(data); switch (c->type) { case IMPORT_COMPRESS_UNCOMPRESSED: r = callback(data, size, userdata); if (r < 0) return r; break; case IMPORT_COMPRESS_XZ: c->xz.next_in = data; c->xz.avail_in = size; while (c->xz.avail_in > 0) { uint8_t buffer[16 * 1024]; lzma_ret lzr; c->xz.next_out = buffer; c->xz.avail_out = sizeof(buffer); lzr = lzma_code(&c->xz, LZMA_RUN); if (!IN_SET(lzr, LZMA_OK, LZMA_STREAM_END)) return -EIO; if (c->xz.avail_out < sizeof(buffer)) { r = callback(buffer, sizeof(buffer) - c->xz.avail_out, userdata); if (r < 0) return r; } } break; case IMPORT_COMPRESS_GZIP: c->gzip.next_in = (void*) data; c->gzip.avail_in = size; while (c->gzip.avail_in > 0) { uint8_t buffer[16 * 1024]; c->gzip.next_out = buffer; c->gzip.avail_out = sizeof(buffer); r = inflate(&c->gzip, Z_NO_FLUSH); if (!IN_SET(r, Z_OK, Z_STREAM_END)) return -EIO; if (c->gzip.avail_out < sizeof(buffer)) { r = callback(buffer, sizeof(buffer) - c->gzip.avail_out, userdata); if (r < 0) return r; } } break; #if HAVE_BZIP2 case IMPORT_COMPRESS_BZIP2: c->bzip2.next_in = (void*) data; c->bzip2.avail_in = size; while (c->bzip2.avail_in > 0) { uint8_t buffer[16 * 1024]; c->bzip2.next_out = (char*) buffer; c->bzip2.avail_out = sizeof(buffer); r = BZ2_bzDecompress(&c->bzip2); if (!IN_SET(r, BZ_OK, BZ_STREAM_END)) return -EIO; if (c->bzip2.avail_out < sizeof(buffer)) { r = callback(buffer, sizeof(buffer) - c->bzip2.avail_out, userdata); if (r < 0) return r; } } break; #endif default: assert_not_reached(); } return 1; } int import_compress_init(ImportCompress *c, ImportCompressType t) { int r; assert(c); switch (t) { case IMPORT_COMPRESS_XZ: { lzma_ret xzr; xzr = lzma_easy_encoder(&c->xz, LZMA_PRESET_DEFAULT, LZMA_CHECK_CRC64); if (xzr != LZMA_OK) return -EIO; c->type = IMPORT_COMPRESS_XZ; break; } case IMPORT_COMPRESS_GZIP: r = deflateInit2(&c->gzip, Z_DEFAULT_COMPRESSION, Z_DEFLATED, 15 + 16, 8, Z_DEFAULT_STRATEGY); if (r != Z_OK) return -EIO; c->type = IMPORT_COMPRESS_GZIP; break; #if HAVE_BZIP2 case IMPORT_COMPRESS_BZIP2: r = BZ2_bzCompressInit(&c->bzip2, 9, 0, 0); if (r != BZ_OK) return -EIO; c->type = IMPORT_COMPRESS_BZIP2; break; #endif case IMPORT_COMPRESS_UNCOMPRESSED: c->type = IMPORT_COMPRESS_UNCOMPRESSED; break; default: return -EOPNOTSUPP; } c->encoding = true; return 0; } static int enlarge_buffer(void **buffer, size_t *buffer_size, size_t *buffer_allocated) { size_t l; void *p; if (*buffer_allocated > *buffer_size) return 0; l = MAX(16*1024U, (*buffer_size * 2)); p = realloc(*buffer, l); if (!p) return -ENOMEM; *buffer = p; *buffer_allocated = l; return 1; } int import_compress(ImportCompress *c, const void *data, size_t size, void **buffer, size_t *buffer_size, size_t *buffer_allocated) { int r; assert(c); assert(buffer); assert(buffer_size); assert(buffer_allocated); if (!c->encoding) return -EINVAL; if (size <= 0) return 0; assert(data); *buffer_size = 0; switch (c->type) { case IMPORT_COMPRESS_XZ: c->xz.next_in = data; c->xz.avail_in = size; while (c->xz.avail_in > 0) { lzma_ret lzr; r = enlarge_buffer(buffer, buffer_size, buffer_allocated); if (r < 0) return r; c->xz.next_out = (uint8_t*) *buffer + *buffer_size; c->xz.avail_out = *buffer_allocated - *buffer_size; lzr = lzma_code(&c->xz, LZMA_RUN); if (lzr != LZMA_OK) return -EIO; *buffer_size += (*buffer_allocated - *buffer_size) - c->xz.avail_out; } break; case IMPORT_COMPRESS_GZIP: c->gzip.next_in = (void*) data; c->gzip.avail_in = size; while (c->gzip.avail_in > 0) { r = enlarge_buffer(buffer, buffer_size, buffer_allocated); if (r < 0) return r; c->gzip.next_out = (uint8_t*) *buffer + *buffer_size; c->gzip.avail_out = *buffer_allocated - *buffer_size; r = deflate(&c->gzip, Z_NO_FLUSH); if (r != Z_OK) return -EIO; *buffer_size += (*buffer_allocated - *buffer_size) - c->gzip.avail_out; } break; #if HAVE_BZIP2 case IMPORT_COMPRESS_BZIP2: c->bzip2.next_in = (void*) data; c->bzip2.avail_in = size; while (c->bzip2.avail_in > 0) { r = enlarge_buffer(buffer, buffer_size, buffer_allocated); if (r < 0) return r; c->bzip2.next_out = (void*) ((uint8_t*) *buffer + *buffer_size); c->bzip2.avail_out = *buffer_allocated - *buffer_size; r = BZ2_bzCompress(&c->bzip2, BZ_RUN); if (r != BZ_RUN_OK) return -EIO; *buffer_size += (*buffer_allocated - *buffer_size) - c->bzip2.avail_out; } break; #endif case IMPORT_COMPRESS_UNCOMPRESSED: if (*buffer_allocated < size) { void *p; p = realloc(*buffer, size); if (!p) return -ENOMEM; *buffer = p; *buffer_allocated = size; } memcpy(*buffer, data, size); *buffer_size = size; break; default: return -EOPNOTSUPP; } return 0; } int import_compress_finish(ImportCompress *c, void **buffer, size_t *buffer_size, size_t *buffer_allocated) { int r; assert(c); assert(buffer); assert(buffer_size); assert(buffer_allocated); if (!c->encoding) return -EINVAL; *buffer_size = 0; switch (c->type) { case IMPORT_COMPRESS_XZ: { lzma_ret lzr; c->xz.avail_in = 0; do { r = enlarge_buffer(buffer, buffer_size, buffer_allocated); if (r < 0) return r; c->xz.next_out = (uint8_t*) *buffer + *buffer_size; c->xz.avail_out = *buffer_allocated - *buffer_size; lzr = lzma_code(&c->xz, LZMA_FINISH); if (!IN_SET(lzr, LZMA_OK, LZMA_STREAM_END)) return -EIO; *buffer_size += (*buffer_allocated - *buffer_size) - c->xz.avail_out; } while (lzr != LZMA_STREAM_END); break; } case IMPORT_COMPRESS_GZIP: c->gzip.avail_in = 0; do { r = enlarge_buffer(buffer, buffer_size, buffer_allocated); if (r < 0) return r; c->gzip.next_out = (uint8_t*) *buffer + *buffer_size; c->gzip.avail_out = *buffer_allocated - *buffer_size; r = deflate(&c->gzip, Z_FINISH); if (!IN_SET(r, Z_OK, Z_STREAM_END)) return -EIO; *buffer_size += (*buffer_allocated - *buffer_size) - c->gzip.avail_out; } while (r != Z_STREAM_END); break; #if HAVE_BZIP2 case IMPORT_COMPRESS_BZIP2: c->bzip2.avail_in = 0; do { r = enlarge_buffer(buffer, buffer_size, buffer_allocated); if (r < 0) return r; c->bzip2.next_out = (void*) ((uint8_t*) *buffer + *buffer_size); c->bzip2.avail_out = *buffer_allocated - *buffer_size; r = BZ2_bzCompress(&c->bzip2, BZ_FINISH); if (!IN_SET(r, BZ_FINISH_OK, BZ_STREAM_END)) return -EIO; *buffer_size += (*buffer_allocated - *buffer_size) - c->bzip2.avail_out; } while (r != BZ_STREAM_END); break; #endif case IMPORT_COMPRESS_UNCOMPRESSED: break; default: return -EOPNOTSUPP; } return 0; } static const char* const import_compress_type_table[_IMPORT_COMPRESS_TYPE_MAX] = { [IMPORT_COMPRESS_UNKNOWN] = "unknown", [IMPORT_COMPRESS_UNCOMPRESSED] = "uncompressed", [IMPORT_COMPRESS_XZ] = "xz", [IMPORT_COMPRESS_GZIP] = "gzip", #if HAVE_BZIP2 [IMPORT_COMPRESS_BZIP2] = "bzip2", #endif }; DEFINE_STRING_TABLE_LOOKUP(import_compress_type, ImportCompressType);
14,067
28.36952
133
c
null
systemd-main/src/import/import-compress.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #if HAVE_BZIP2 #include <bzlib.h> #endif #include <lzma.h> #include <sys/types.h> #include <zlib.h> #include "macro.h" typedef enum ImportCompressType { IMPORT_COMPRESS_UNKNOWN, IMPORT_COMPRESS_UNCOMPRESSED, IMPORT_COMPRESS_XZ, IMPORT_COMPRESS_GZIP, IMPORT_COMPRESS_BZIP2, _IMPORT_COMPRESS_TYPE_MAX, _IMPORT_COMPRESS_TYPE_INVALID = -EINVAL, } ImportCompressType; typedef struct ImportCompress { ImportCompressType type; bool encoding; union { lzma_stream xz; z_stream gzip; #if HAVE_BZIP2 bz_stream bzip2; #endif }; } ImportCompress; typedef int (*ImportCompressCallback)(const void *data, size_t size, void *userdata); void import_compress_free(ImportCompress *c); int import_uncompress_detect(ImportCompress *c, const void *data, size_t size); void import_uncompress_force_off(ImportCompress *c); int import_uncompress(ImportCompress *c, const void *data, size_t size, ImportCompressCallback callback, void *userdata); int import_compress_init(ImportCompress *c, ImportCompressType t); int import_compress(ImportCompress *c, const void *data, size_t size, void **buffer, size_t *buffer_size, size_t *buffer_allocated); int import_compress_finish(ImportCompress *c, void **buffer, size_t *buffer_size, size_t *buffer_allocated); const char* import_compress_type_to_string(ImportCompressType t) _const_; ImportCompressType import_compress_type_from_string(const char *s) _pure_;
1,586
31.387755
132
h
null
systemd-main/src/import/import-fs.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include <locale.h> #include "alloc-util.h" #include "build.h" #include "btrfs-util.h" #include "discover-image.h" #include "fd-util.h" #include "format-util.h" #include "fs-util.h" #include "hostname-util.h" #include "import-common.h" #include "import-util.h" #include "install-file.h" #include "main-func.h" #include "mkdir-label.h" #include "parse-argument.h" #include "ratelimit.h" #include "rm-rf.h" #include "signal-util.h" #include "string-util.h" #include "terminal-util.h" #include "tmpfile-util.h" #include "verbs.h" static bool arg_force = false; static bool arg_read_only = false; static bool arg_btrfs_subvol = true; static bool arg_btrfs_quota = true; static bool arg_sync = true; static bool arg_direct = false; static const char *arg_image_root = "/var/lib/machines"; typedef struct ProgressInfo { RateLimit limit; char *path; uint64_t size; bool started; bool logged_incomplete; } ProgressInfo; static void progress_info_free(ProgressInfo *p) { free(p->path); } static void progress_show(ProgressInfo *p) { assert(p); /* Show progress only every now and then. */ if (!ratelimit_below(&p->limit)) return; /* Suppress the first message, start with the second one */ if (!p->started) { p->started = true; return; } /* Mention the list is incomplete before showing first output. */ if (!p->logged_incomplete) { log_notice("(Note: file list shown below is incomplete, and is intended as sporadic progress report only.)"); p->logged_incomplete = true; } if (p->size == 0) log_info("Copying tree, currently at '%s'...", p->path); else log_info("Copying tree, currently at '%s' (@%s)...", p->path, FORMAT_BYTES(p->size)); } static int progress_path(const char *path, const struct stat *st, void *userdata) { ProgressInfo *p = ASSERT_PTR(userdata); int r; r = free_and_strdup(&p->path, path); if (r < 0) return r; p->size = 0; progress_show(p); return 0; } static int progress_bytes(uint64_t nbytes, void *userdata) { ProgressInfo *p = ASSERT_PTR(userdata); assert(p->size != UINT64_MAX); p->size += nbytes; progress_show(p); return 0; } static int import_fs(int argc, char *argv[], void *userdata) { _cleanup_(rm_rf_subvolume_and_freep) char *temp_path = NULL; _cleanup_(progress_info_free) ProgressInfo progress = {}; _cleanup_free_ char *l = NULL, *final_path = NULL; const char *path = NULL, *local = NULL, *dest = NULL; _cleanup_close_ int open_fd = -EBADF; int r, fd; if (argc >= 2) path = empty_or_dash_to_null(argv[1]); if (argc >= 3) local = empty_or_dash_to_null(argv[2]); else if (path) { r = path_extract_filename(path, &l); if (r < 0) return log_error_errno(r, "Failed to extract filename from path '%s': %m", path); local = l; } if (arg_direct) { if (!local) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No local path specified."); if (path_is_absolute(local)) final_path = strdup(local); else final_path = path_join(arg_image_root, local); if (!final_path) return log_oom(); if (!path_is_valid(final_path)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Local path name '%s' is not valid.", final_path); } else { if (local) { if (!hostname_is_valid(local, 0)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Local image name '%s' is not valid.", local); } else local = "imported"; final_path = path_join(arg_image_root, local); if (!final_path) return log_oom(); if (!arg_force) { r = image_find(IMAGE_MACHINE, local, NULL, NULL); if (r < 0) { if (r != -ENOENT) return log_error_errno(r, "Failed to check whether image '%s' exists: %m", local); } else return log_error_errno(SYNTHETIC_ERRNO(EEXIST), "Image '%s' already exists.", local); } } if (path) { open_fd = open(path, O_DIRECTORY|O_RDONLY|O_CLOEXEC); if (open_fd < 0) return log_error_errno(errno, "Failed to open directory to import: %m"); fd = open_fd; log_info("Importing '%s', saving as '%s'.", path, local); } else { _cleanup_free_ char *pretty = NULL; fd = STDIN_FILENO; (void) fd_get_path(fd, &pretty); log_info("Importing '%s', saving as '%s'.", strempty(pretty), local); } if (!arg_sync) log_info("File system synchronization on completion is off."); if (arg_direct) { if (arg_force) (void) rm_rf(final_path, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME); dest = final_path; } else { r = tempfn_random(final_path, NULL, &temp_path); if (r < 0) return log_oom(); dest = temp_path; } (void) mkdir_parents_label(dest, 0700); progress.limit = (const RateLimit) { 200*USEC_PER_MSEC, 1 }; { BLOCK_SIGNALS(SIGINT, SIGTERM); if (arg_btrfs_subvol) r = btrfs_subvol_snapshot_at_full( fd, NULL, AT_FDCWD, dest, BTRFS_SNAPSHOT_FALLBACK_COPY| BTRFS_SNAPSHOT_FALLBACK_DIRECTORY| BTRFS_SNAPSHOT_RECURSIVE| BTRFS_SNAPSHOT_SIGINT| BTRFS_SNAPSHOT_SIGTERM, progress_path, progress_bytes, &progress); else r = copy_directory_at_full( fd, NULL, AT_FDCWD, dest, COPY_REFLINK| COPY_SAME_MOUNT| COPY_HARDLINKS| COPY_SIGINT| COPY_SIGTERM| (arg_direct ? COPY_MERGE_EMPTY : 0), progress_path, progress_bytes, &progress); if (r == -EINTR) /* SIGINT/SIGTERM hit */ return log_error_errno(r, "Copy cancelled."); if (r < 0) return log_error_errno(r, "Failed to copy directory: %m"); } r = import_mangle_os_tree(dest); if (r < 0) return r; if (arg_btrfs_quota) { if (!arg_direct) (void) import_assign_pool_quota_and_warn(arg_image_root); (void) import_assign_pool_quota_and_warn(dest); } r = install_file(AT_FDCWD, dest, AT_FDCWD, arg_direct ? NULL : final_path, /* pass NULL as target in case of direct * mode since file is already in place */ (arg_force ? INSTALL_REPLACE : 0) | (arg_read_only ? INSTALL_READ_ONLY : 0) | (arg_sync ? INSTALL_SYNCFS : 0)); if (r < 0) return log_error_errno(r, "Failed install directory as '%s': %m", final_path); temp_path = mfree(temp_path); log_info("Directory '%s successfully installed. Exiting.", final_path); return 0; } static int help(int argc, char *argv[], void *userdata) { printf("%1$s [OPTIONS...] {COMMAND} ...\n" "\n%4$sImport container images from a file system directories.%5$s\n" "\n%2$sCommands:%3$s\n" " run DIRECTORY [NAME] Import a directory\n" "\n%2$sOptions:%3$s\n" " -h --help Show this help\n" " --version Show package version\n" " --force Force creation of image\n" " --image-root=PATH Image root directory\n" " --read-only Create a read-only image\n" " --direct Import directly to specified directory\n" " --btrfs-subvol=BOOL Controls whether to create a btrfs subvolume\n" " instead of a directory\n" " --btrfs-quota=BOOL Controls whether to set up quota for btrfs\n" " subvolume\n" " --sync=BOOL Controls whether to sync() before completing\n", program_invocation_short_name, ansi_underline(), ansi_normal(), ansi_highlight(), ansi_normal()); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_VERSION = 0x100, ARG_FORCE, ARG_IMAGE_ROOT, ARG_READ_ONLY, ARG_DIRECT, ARG_BTRFS_SUBVOL, ARG_BTRFS_QUOTA, ARG_SYNC, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "force", no_argument, NULL, ARG_FORCE }, { "image-root", required_argument, NULL, ARG_IMAGE_ROOT }, { "read-only", no_argument, NULL, ARG_READ_ONLY }, { "direct", no_argument, NULL, ARG_DIRECT }, { "btrfs-subvol", required_argument, NULL, ARG_BTRFS_SUBVOL }, { "btrfs-quota", required_argument, NULL, ARG_BTRFS_QUOTA }, { "sync", required_argument, NULL, ARG_SYNC }, {} }; int c, r; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': return help(0, NULL, NULL); case ARG_VERSION: return version(); case ARG_FORCE: arg_force = true; break; case ARG_IMAGE_ROOT: arg_image_root = optarg; break; case ARG_READ_ONLY: arg_read_only = true; break; case ARG_DIRECT: arg_direct = true; break; case ARG_BTRFS_SUBVOL: r = parse_boolean_argument("--btrfs-subvol=", optarg, &arg_btrfs_subvol); if (r < 0) return r; break; case ARG_BTRFS_QUOTA: r = parse_boolean_argument("--btrfs-quota=", optarg, &arg_btrfs_quota); if (r < 0) return r; break; case ARG_SYNC: r = parse_boolean_argument("--sync=", optarg, &arg_sync); if (r < 0) return r; break; case '?': return -EINVAL; default: assert_not_reached(); } return 1; } static int import_fs_main(int argc, char *argv[]) { static const Verb verbs[] = { { "help", VERB_ANY, VERB_ANY, 0, help }, { "run", 2, 3, 0, import_fs }, {} }; return dispatch_verb(argc, argv, verbs, NULL); } static int run(int argc, char *argv[]) { int r; setlocale(LC_ALL, ""); log_parse_environment(); log_open(); r = parse_argv(argc, argv); if (r <= 0) return r; return import_fs_main(argc, argv); } DEFINE_MAIN_FUNCTION(run);
13,691
33.839695
125
c
null
systemd-main/src/import/import-raw.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-event.h" #include "import-common.h" #include "import-util.h" #include "macro.h" typedef struct RawImport RawImport; typedef void (*RawImportFinished)(RawImport *import, int error, void *userdata); int raw_import_new(RawImport **import, sd_event *event, const char *image_root, RawImportFinished on_finished, void *userdata); RawImport* raw_import_unref(RawImport *import); DEFINE_TRIVIAL_CLEANUP_FUNC(RawImport*, raw_import_unref); int raw_import_start(RawImport *i, int fd, const char *local, uint64_t offset, uint64_t size_max, ImportFlags flags);
632
30.65
127
h
null
systemd-main/src/import/import-tar.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-event.h" #include "import-common.h" #include "import-util.h" #include "macro.h" typedef struct TarImport TarImport; typedef void (*TarImportFinished)(TarImport *import, int error, void *userdata); int tar_import_new(TarImport **import, sd_event *event, const char *image_root, TarImportFinished on_finished, void *userdata); TarImport* tar_import_unref(TarImport *import); DEFINE_TRIVIAL_CLEANUP_FUNC(TarImport*, tar_import_unref); int tar_import_start(TarImport *import, int fd, const char *local, ImportFlags flags);
601
29.1
127
h
null
systemd-main/src/import/pull-job.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <sys/stat.h> #include "curl-util.h" #include "import-compress.h" #include "macro.h" #include "openssl-util.h" #include "pull-common.h" typedef struct PullJob PullJob; typedef void (*PullJobFinished)(PullJob *job); typedef int (*PullJobOpenDisk)(PullJob *job); typedef int (*PullJobHeader)(PullJob *job, const char *header, size_t sz); typedef void (*PullJobProgress)(PullJob *job); typedef int (*PullJobNotFound)(PullJob *job, char **ret_new_url); typedef enum PullJobState { PULL_JOB_INIT, PULL_JOB_ANALYZING, /* Still reading into ->payload, to figure out what we have */ PULL_JOB_RUNNING, /* Writing to destination */ PULL_JOB_DONE, PULL_JOB_FAILED, _PULL_JOB_STATE_MAX, _PULL_JOB_STATE_INVALID = -EINVAL, } PullJobState; #define PULL_JOB_IS_COMPLETE(j) (IN_SET((j)->state, PULL_JOB_DONE, PULL_JOB_FAILED)) struct PullJob { PullJobState state; int error; char *url; void *userdata; PullJobFinished on_finished; PullJobOpenDisk on_open_disk; PullJobHeader on_header; PullJobProgress on_progress; PullJobNotFound on_not_found; CurlGlue *glue; CURL *curl; struct curl_slist *request_header; char *etag; char **old_etags; bool etag_exists; uint64_t content_length; uint64_t written_compressed; uint64_t written_uncompressed; uint64_t offset; uint64_t uncompressed_max; uint64_t compressed_max; uint8_t *payload; size_t payload_size; int disk_fd; bool close_disk_fd; struct stat disk_stat; usec_t mtime; ImportCompress compress; unsigned progress_percent; usec_t start_usec; usec_t last_status_usec; bool calc_checksum; hash_context_t checksum_ctx; char *checksum; bool sync; bool force_memory; }; int pull_job_new(PullJob **job, const char *url, CurlGlue *glue, void *userdata); PullJob* pull_job_unref(PullJob *job); int pull_job_begin(PullJob *j); void pull_job_curl_on_finished(CurlGlue *g, CURL *curl, CURLcode result); void pull_job_close_disk_fd(PullJob *j); DEFINE_TRIVIAL_CLEANUP_FUNC(PullJob*, pull_job_unref);
2,361
24.12766
90
h
null
systemd-main/src/import/pull-tar.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <curl/curl.h> #include <sys/prctl.h> #include "sd-daemon.h" #include "alloc-util.h" #include "btrfs-util.h" #include "copy.h" #include "curl-util.h" #include "fd-util.h" #include "fs-util.h" #include "hostname-util.h" #include "import-common.h" #include "import-util.h" #include "install-file.h" #include "macro.h" #include "mkdir-label.h" #include "path-util.h" #include "process-util.h" #include "pull-common.h" #include "pull-job.h" #include "pull-tar.h" #include "rm-rf.h" #include "string-util.h" #include "strv.h" #include "tmpfile-util.h" #include "user-util.h" #include "utf8.h" #include "web-util.h" typedef enum TarProgress { TAR_DOWNLOADING, TAR_VERIFYING, TAR_FINALIZING, TAR_COPYING, } TarProgress; struct TarPull { sd_event *event; CurlGlue *glue; PullFlags flags; ImportVerify verify; char *image_root; PullJob *tar_job; PullJob *checksum_job; PullJob *signature_job; PullJob *settings_job; TarPullFinished on_finished; void *userdata; char *local; pid_t tar_pid; char *final_path; char *temp_path; char *settings_path; char *settings_temp_path; char *checksum; }; TarPull* tar_pull_unref(TarPull *i) { if (!i) return NULL; if (i->tar_pid > 1) sigkill_wait(i->tar_pid); pull_job_unref(i->tar_job); pull_job_unref(i->checksum_job); pull_job_unref(i->signature_job); pull_job_unref(i->settings_job); curl_glue_unref(i->glue); sd_event_unref(i->event); rm_rf_subvolume_and_free(i->temp_path); unlink_and_free(i->settings_temp_path); free(i->final_path); free(i->settings_path); free(i->image_root); free(i->local); free(i->checksum); return mfree(i); } int tar_pull_new( TarPull **ret, sd_event *event, const char *image_root, TarPullFinished on_finished, void *userdata) { _cleanup_(curl_glue_unrefp) CurlGlue *g = NULL; _cleanup_(sd_event_unrefp) sd_event *e = NULL; _cleanup_(tar_pull_unrefp) TarPull *i = NULL; _cleanup_free_ char *root = NULL; int r; assert(ret); root = strdup(image_root ?: "/var/lib/machines"); if (!root) return -ENOMEM; if (event) e = sd_event_ref(event); else { r = sd_event_default(&e); if (r < 0) return r; } r = curl_glue_new(&g, e); if (r < 0) return r; i = new(TarPull, 1); if (!i) return -ENOMEM; *i = (TarPull) { .on_finished = on_finished, .userdata = userdata, .image_root = TAKE_PTR(root), .event = TAKE_PTR(e), .glue = TAKE_PTR(g), }; i->glue->on_finished = pull_job_curl_on_finished; i->glue->userdata = i; *ret = TAKE_PTR(i); return 0; } static void tar_pull_report_progress(TarPull *i, TarProgress p) { unsigned percent; assert(i); switch (p) { case TAR_DOWNLOADING: { unsigned remain = 85; percent = 0; if (i->checksum_job) { percent += i->checksum_job->progress_percent * 5 / 100; remain -= 5; } if (i->signature_job) { percent += i->signature_job->progress_percent * 5 / 100; remain -= 5; } if (i->settings_job) { percent += i->settings_job->progress_percent * 5 / 100; remain -= 5; } if (i->tar_job) percent += i->tar_job->progress_percent * remain / 100; break; } case TAR_VERIFYING: percent = 85; break; case TAR_FINALIZING: percent = 90; break; case TAR_COPYING: percent = 95; break; default: assert_not_reached(); } sd_notifyf(false, "X_IMPORT_PROGRESS=%u", percent); log_debug("Combined progress %u%%", percent); } static int tar_pull_determine_path( TarPull *i, const char *suffix, char **field /* input + output (!) */) { int r; assert(i); assert(field); if (*field) return 0; assert(i->tar_job); r = pull_make_path(i->tar_job->url, i->tar_job->etag, i->image_root, ".tar-", suffix, field); if (r < 0) return log_oom(); return 1; } static int tar_pull_make_local_copy(TarPull *i) { _cleanup_(rm_rf_subvolume_and_freep) char *t = NULL; const char *p; int r; assert(i); assert(i->tar_job); if (!i->local) return 0; assert(i->final_path); p = prefix_roota(i->image_root, i->local); r = tempfn_random(p, NULL, &t); if (r < 0) return log_error_errno(r, "Failed to generate temporary filename for %s: %m", p); if (i->flags & PULL_BTRFS_SUBVOL) r = btrfs_subvol_snapshot_at( AT_FDCWD, i->final_path, AT_FDCWD, t, (i->flags & PULL_BTRFS_QUOTA ? BTRFS_SNAPSHOT_QUOTA : 0)| BTRFS_SNAPSHOT_FALLBACK_COPY| BTRFS_SNAPSHOT_FALLBACK_DIRECTORY| BTRFS_SNAPSHOT_RECURSIVE); else r = copy_tree(i->final_path, t, UID_INVALID, GID_INVALID, COPY_REFLINK|COPY_HARDLINKS, NULL); if (r < 0) return log_error_errno(r, "Failed to create local image: %m"); r = install_file(AT_FDCWD, t, AT_FDCWD, p, (i->flags & PULL_FORCE ? INSTALL_REPLACE : 0) | (i->flags & PULL_READ_ONLY ? INSTALL_READ_ONLY : 0) | (i->flags & PULL_SYNC ? INSTALL_SYNCFS : 0)); if (r < 0) return log_error_errno(r, "Failed to install local image '%s': %m", p); t = mfree(t); log_info("Created new local image '%s'.", i->local); if (FLAGS_SET(i->flags, PULL_SETTINGS)) { const char *local_settings; assert(i->settings_job); r = tar_pull_determine_path(i, ".nspawn", &i->settings_path); if (r < 0) return r; local_settings = strjoina(i->image_root, "/", i->local, ".nspawn"); r = copy_file_atomic( i->settings_path, local_settings, 0664, COPY_REFLINK | (FLAGS_SET(i->flags, PULL_FORCE) ? COPY_REPLACE : 0) | (FLAGS_SET(i->flags, PULL_SYNC) ? COPY_FSYNC_FULL : 0)); if (r == -EEXIST) log_warning_errno(r, "Settings file %s already exists, not replacing.", local_settings); else if (r == -ENOENT) log_debug_errno(r, "Skipping creation of settings file, since none was found."); else if (r < 0) log_warning_errno(r, "Failed to copy settings files %s, ignoring: %m", local_settings); else log_info("Created new settings file %s.", local_settings); } return 0; } static bool tar_pull_is_done(TarPull *i) { assert(i); assert(i->tar_job); if (!PULL_JOB_IS_COMPLETE(i->tar_job)) return false; if (i->checksum_job && !PULL_JOB_IS_COMPLETE(i->checksum_job)) return false; if (i->signature_job && !PULL_JOB_IS_COMPLETE(i->signature_job)) return false; if (i->settings_job && !PULL_JOB_IS_COMPLETE(i->settings_job)) return false; return true; } static void tar_pull_job_on_finished(PullJob *j) { TarPull *i; int r; assert(j); assert(j->userdata); i = j->userdata; if (j->error != 0) { if (j == i->tar_job) { if (j->error == ENOMEDIUM) /* HTTP 404 */ r = log_error_errno(j->error, "Failed to retrieve image file. (Wrong URL?)"); else r = log_error_errno(j->error, "Failed to retrieve image file."); goto finish; } else if (j == i->checksum_job) { r = log_error_errno(j->error, "Failed to retrieve SHA256 checksum, cannot verify. (Try --verify=no?)"); goto finish; } else if (j == i->signature_job) log_debug_errno(j->error, "Signature job for %s failed, proceeding for now.", j->url); else if (j == i->settings_job) log_info_errno(j->error, "Settings file could not be retrieved, proceeding without."); else assert("unexpected job"); } /* This is invoked if either the download completed successfully, or the download was skipped because * we already have the etag. */ if (!tar_pull_is_done(i)) return; if (i->signature_job && i->signature_job->error != 0) { VerificationStyle style; assert(i->checksum_job); r = verification_style_from_url(i->checksum_job->url, &style); if (r < 0) { log_error_errno(r, "Failed to determine verification style from checksum URL: %m"); goto finish; } if (style == VERIFICATION_PER_DIRECTORY) { /* A failed signature file download only matters * in per-directory verification mode, since only * then the signature is detached, and thus a file * of its own. */ r = log_error_errno(i->signature_job->error, "Failed to retrieve signature file, cannot verify. (Try --verify=no?)"); goto finish; } } pull_job_close_disk_fd(i->tar_job); pull_job_close_disk_fd(i->settings_job); if (i->tar_pid > 0) { r = wait_for_terminate_and_check("tar", TAKE_PID(i->tar_pid), WAIT_LOG); if (r < 0) goto finish; if (r != EXIT_SUCCESS) { r = -EIO; goto finish; } } if (!i->tar_job->etag_exists) { /* This is a new download, verify it, and move it into place */ tar_pull_report_progress(i, TAR_VERIFYING); r = pull_verify(i->verify, i->checksum, i->tar_job, i->checksum_job, i->signature_job, i->settings_job, /* roothash_job = */ NULL, /* roothash_signature_job = */ NULL, /* verity_job = */ NULL); if (r < 0) goto finish; } if (i->flags & PULL_DIRECT) { assert(!i->settings_job); assert(i->local); assert(!i->temp_path); tar_pull_report_progress(i, TAR_FINALIZING); r = import_mangle_os_tree(i->local); if (r < 0) goto finish; r = install_file( AT_FDCWD, i->local, AT_FDCWD, NULL, (i->flags & PULL_READ_ONLY) ? INSTALL_READ_ONLY : 0 | (i->flags & PULL_SYNC ? INSTALL_SYNCFS : 0)); if (r < 0) { log_error_errno(r, "Failed to finalize '%s': %m", i->local); goto finish; } } else { r = tar_pull_determine_path(i, NULL, &i->final_path); if (r < 0) goto finish; if (!i->tar_job->etag_exists) { /* This is a new download, verify it, and move it into place */ assert(i->temp_path); assert(i->final_path); tar_pull_report_progress(i, TAR_FINALIZING); r = import_mangle_os_tree(i->temp_path); if (r < 0) goto finish; r = install_file( AT_FDCWD, i->temp_path, AT_FDCWD, i->final_path, INSTALL_READ_ONLY| (i->flags & PULL_SYNC ? INSTALL_SYNCFS : 0)); if (r < 0) { log_error_errno(r, "Failed to rename to final image name to %s: %m", i->final_path); goto finish; } i->temp_path = mfree(i->temp_path); if (i->settings_job && i->settings_job->error == 0) { /* Also move the settings file into place, if it exists. Note that we do so only if we also * moved the tar file in place, to keep things strictly in sync. */ assert(i->settings_temp_path); /* Regenerate final name for this auxiliary file, we might know the etag of the file now, and * we should incorporate it in the file name if we can */ i->settings_path = mfree(i->settings_path); r = tar_pull_determine_path(i, ".nspawn", &i->settings_path); if (r < 0) goto finish; r = install_file( AT_FDCWD, i->settings_temp_path, AT_FDCWD, i->settings_path, INSTALL_READ_ONLY| (i->flags & PULL_SYNC ? INSTALL_FSYNC_FULL : 0)); if (r < 0) { log_error_errno(r, "Failed to rename settings file to %s: %m", i->settings_path); goto finish; } i->settings_temp_path = mfree(i->settings_temp_path); } } tar_pull_report_progress(i, TAR_COPYING); r = tar_pull_make_local_copy(i); if (r < 0) goto finish; } r = 0; finish: if (i->on_finished) i->on_finished(i, r, i->userdata); else sd_event_exit(i->event, r); } static int tar_pull_job_on_open_disk_tar(PullJob *j) { const char *where; TarPull *i; int r; assert(j); assert(j->userdata); i = j->userdata; assert(i->tar_job == j); assert(i->tar_pid <= 0); if (i->flags & PULL_DIRECT) where = i->local; else { if (!i->temp_path) { r = tempfn_random_child(i->image_root, "tar", &i->temp_path); if (r < 0) return log_oom(); } where = i->temp_path; } (void) mkdir_parents_label(where, 0700); if (FLAGS_SET(i->flags, PULL_DIRECT|PULL_FORCE)) (void) rm_rf(where, REMOVE_ROOT|REMOVE_PHYSICAL|REMOVE_SUBVOLUME); if (i->flags & PULL_BTRFS_SUBVOL) r = btrfs_subvol_make_fallback(where, 0755); else r = RET_NERRNO(mkdir(where, 0755)); if (r == -EEXIST && (i->flags & PULL_DIRECT)) /* EEXIST is OK if in direct mode, but not otherwise, * because in that case our temporary path collided */ r = 0; if (r < 0) return log_error_errno(r, "Failed to create directory/subvolume %s: %m", where); if (r > 0 && (i->flags & PULL_BTRFS_QUOTA)) { /* actually btrfs subvol */ if (!(i->flags & PULL_DIRECT)) (void) import_assign_pool_quota_and_warn(i->image_root); (void) import_assign_pool_quota_and_warn(where); } j->disk_fd = import_fork_tar_x(where, &i->tar_pid); if (j->disk_fd < 0) return j->disk_fd; return 0; } static int tar_pull_job_on_open_disk_settings(PullJob *j) { TarPull *i; int r; assert(j); assert(j->userdata); i = j->userdata; assert(i->settings_job == j); if (!i->settings_temp_path) { r = tempfn_random_child(i->image_root, "settings", &i->settings_temp_path); if (r < 0) return log_oom(); } (void) mkdir_parents_label(i->settings_temp_path, 0700); j->disk_fd = open(i->settings_temp_path, O_RDWR|O_CREAT|O_EXCL|O_NOCTTY|O_CLOEXEC, 0664); if (j->disk_fd < 0) return log_error_errno(errno, "Failed to create %s: %m", i->settings_temp_path); return 0; } static void tar_pull_job_on_progress(PullJob *j) { TarPull *i; assert(j); assert(j->userdata); i = j->userdata; tar_pull_report_progress(i, TAR_DOWNLOADING); } int tar_pull_start( TarPull *i, const char *url, const char *local, PullFlags flags, ImportVerify verify, const char *checksum) { PullJob *j; int r; assert(i); assert(verify == _IMPORT_VERIFY_INVALID || verify < _IMPORT_VERIFY_MAX); assert(verify == _IMPORT_VERIFY_INVALID || verify >= 0); assert((verify < 0) || !checksum); assert(!(flags & ~PULL_FLAGS_MASK_TAR)); assert(!(flags & PULL_SETTINGS) || !(flags & PULL_DIRECT)); assert(!(flags & PULL_SETTINGS) || !checksum); if (!http_url_is_valid(url) && !file_url_is_valid(url)) return -EINVAL; if (local && !pull_validate_local(local, flags)) return -EINVAL; if (i->tar_job) return -EBUSY; r = free_and_strdup(&i->local, local); if (r < 0) return r; r = free_and_strdup(&i->checksum, checksum); if (r < 0) return r; i->flags = flags; i->verify = verify; /* Set up download job for TAR file */ r = pull_job_new(&i->tar_job, url, i->glue, i); if (r < 0) return r; i->tar_job->on_finished = tar_pull_job_on_finished; i->tar_job->on_open_disk = tar_pull_job_on_open_disk_tar; i->tar_job->calc_checksum = checksum || IN_SET(verify, IMPORT_VERIFY_CHECKSUM, IMPORT_VERIFY_SIGNATURE); if (!FLAGS_SET(flags, PULL_DIRECT)) { r = pull_find_old_etags(url, i->image_root, DT_DIR, ".tar-", NULL, &i->tar_job->old_etags); if (r < 0) return r; } /* Set up download of checksum/signature files */ r = pull_make_verification_jobs( &i->checksum_job, &i->signature_job, verify, checksum, url, i->glue, tar_pull_job_on_finished, i); if (r < 0) return r; /* Set up download job for the settings file (.nspawn) */ if (FLAGS_SET(flags, PULL_SETTINGS)) { r = pull_make_auxiliary_job( &i->settings_job, url, tar_strip_suffixes, ".nspawn", verify, i->glue, tar_pull_job_on_open_disk_settings, tar_pull_job_on_finished, i); if (r < 0) return r; } FOREACH_POINTER(j, i->tar_job, i->checksum_job, i->signature_job, i->settings_job) { if (!j) continue; j->on_progress = tar_pull_job_on_progress; j->sync = FLAGS_SET(flags, PULL_SYNC); r = pull_job_begin(j); if (r < 0) return r; } return 0; }
22,203
31.749263
127
c
null
systemd-main/src/import/pull-tar.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-event.h" #include "import-util.h" #include "macro.h" #include "pull-common.h" typedef struct TarPull TarPull; typedef void (*TarPullFinished)(TarPull *pull, int error, void *userdata); int tar_pull_new(TarPull **pull, sd_event *event, const char *image_root, TarPullFinished on_finished, void *userdata); TarPull* tar_pull_unref(TarPull *pull); DEFINE_TRIVIAL_CLEANUP_FUNC(TarPull*, tar_pull_unref); int tar_pull_start(TarPull *pull, const char *url, const char *local, PullFlags flags, ImportVerify verify, const char *checksum);
613
29.7
130
h
null
systemd-main/src/import/qcow2-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <zlib.h> #include "alloc-util.h" #include "btrfs-util.h" #include "qcow2-util.h" #include "sparse-endian.h" #define QCOW2_MAGIC 0x514649fb #define QCOW2_COPIED (1ULL << 63) #define QCOW2_COMPRESSED (1ULL << 62) #define QCOW2_ZERO (1ULL << 0) typedef struct _packed_ Header { be32_t magic; be32_t version; be64_t backing_file_offset; be32_t backing_file_size; be32_t cluster_bits; be64_t size; be32_t crypt_method; be32_t l1_size; be64_t l1_table_offset; be64_t refcount_table_offset; be32_t refcount_table_clusters; be32_t nb_snapshots; be64_t snapshots_offset; /* The remainder is only present on QCOW3 */ be64_t incompatible_features; be64_t compatible_features; be64_t autoclear_features; be32_t refcount_order; be32_t header_length; } Header; #define HEADER_MAGIC(header) be32toh((header)->magic) #define HEADER_VERSION(header) be32toh((header)->version) #define HEADER_CLUSTER_BITS(header) be32toh((header)->cluster_bits) #define HEADER_CLUSTER_SIZE(header) (1ULL << HEADER_CLUSTER_BITS(header)) #define HEADER_L2_BITS(header) (HEADER_CLUSTER_BITS(header) - 3) #define HEADER_SIZE(header) be64toh((header)->size) #define HEADER_CRYPT_METHOD(header) be32toh((header)->crypt_method) #define HEADER_L1_SIZE(header) be32toh((header)->l1_size) #define HEADER_L2_SIZE(header) (HEADER_CLUSTER_SIZE(header)/sizeof(uint64_t)) #define HEADER_L1_TABLE_OFFSET(header) be64toh((header)->l1_table_offset) static uint32_t HEADER_HEADER_LENGTH(const Header *h) { if (HEADER_VERSION(h) < 3) return offsetof(Header, incompatible_features); return be32toh(h->header_length); } static int copy_cluster( int sfd, uint64_t soffset, int dfd, uint64_t doffset, uint64_t cluster_size, void *buffer) { ssize_t l; int r; r = reflink_range(sfd, soffset, dfd, doffset, cluster_size); if (r >= 0) return r; l = pread(sfd, buffer, cluster_size, soffset); if (l < 0) return -errno; if ((uint64_t) l != cluster_size) return -EIO; l = pwrite(dfd, buffer, cluster_size, doffset); if (l < 0) return -errno; if ((uint64_t) l != cluster_size) return -EIO; return 0; } static int decompress_cluster( int sfd, uint64_t soffset, int dfd, uint64_t doffset, uint64_t compressed_size, uint64_t cluster_size, void *buffer1, void *buffer2) { _cleanup_free_ void *large_buffer = NULL; z_stream s = {}; uint64_t sz; ssize_t l; int r; if (compressed_size > cluster_size) { /* The usual cluster buffer doesn't suffice, let's * allocate a larger one, temporarily */ large_buffer = malloc(compressed_size); if (!large_buffer) return -ENOMEM; buffer1 = large_buffer; } l = pread(sfd, buffer1, compressed_size, soffset); if (l < 0) return -errno; if ((uint64_t) l != compressed_size) return -EIO; s.next_in = buffer1; s.avail_in = compressed_size; s.next_out = buffer2; s.avail_out = cluster_size; r = inflateInit2(&s, -12); if (r != Z_OK) return -EIO; r = inflate(&s, Z_FINISH); sz = (uint8_t*) s.next_out - (uint8_t*) buffer2; inflateEnd(&s); if (r != Z_STREAM_END || sz != cluster_size) return -EIO; l = pwrite(dfd, buffer2, cluster_size, doffset); if (l < 0) return -errno; if ((uint64_t) l != cluster_size) return -EIO; return 0; } static int normalize_offset( const Header *header, uint64_t p, uint64_t *ret, bool *compressed, uint64_t *compressed_size) { uint64_t q; q = be64toh(p); if (q & QCOW2_COMPRESSED) { uint64_t sz, csize_shift, csize_mask; if (!compressed) return -EOPNOTSUPP; csize_shift = 64 - 2 - (HEADER_CLUSTER_BITS(header) - 8); csize_mask = (1ULL << (HEADER_CLUSTER_BITS(header) - 8)) - 1; sz = (((q >> csize_shift) & csize_mask) + 1) * 512 - (q & 511); q &= ((1ULL << csize_shift) - 1); if (compressed_size) *compressed_size = sz; *compressed = true; } else { if (compressed) { *compressed = false; *compressed_size = 0; } if (q & QCOW2_ZERO) { /* We make no distinction between zero blocks and holes */ *ret = 0; return 0; } q &= ~QCOW2_COPIED; } *ret = q; return q > 0; /* returns positive if not a hole */ } static int verify_header(const Header *header) { assert(header); if (HEADER_MAGIC(header) != QCOW2_MAGIC) return -EBADMSG; if (!IN_SET(HEADER_VERSION(header), 2, 3)) return -EOPNOTSUPP; if (HEADER_CRYPT_METHOD(header) != 0) return -EOPNOTSUPP; if (HEADER_CLUSTER_BITS(header) < 9) /* 512K */ return -EBADMSG; if (HEADER_CLUSTER_BITS(header) > 21) /* 2MB */ return -EBADMSG; if (HEADER_SIZE(header) % HEADER_CLUSTER_SIZE(header) != 0) return -EBADMSG; if (HEADER_L1_SIZE(header) > 32*1024*1024) /* 32MB */ return -EBADMSG; if (HEADER_VERSION(header) == 3) { if (header->incompatible_features != 0) return -EOPNOTSUPP; if (HEADER_HEADER_LENGTH(header) < sizeof(Header)) return -EBADMSG; } return 0; } int qcow2_convert(int qcow2_fd, int raw_fd) { _cleanup_free_ void *buffer1 = NULL, *buffer2 = NULL; _cleanup_free_ be64_t *l1_table = NULL, *l2_table = NULL; uint64_t sz, i; Header header; ssize_t l; int r; l = pread(qcow2_fd, &header, sizeof(header), 0); if (l < 0) return -errno; if (l != sizeof(header)) return -EIO; r = verify_header(&header); if (r < 0) return r; l1_table = new(be64_t, HEADER_L1_SIZE(&header)); if (!l1_table) return -ENOMEM; l2_table = malloc(HEADER_CLUSTER_SIZE(&header)); if (!l2_table) return -ENOMEM; buffer1 = malloc(HEADER_CLUSTER_SIZE(&header)); if (!buffer1) return -ENOMEM; buffer2 = malloc(HEADER_CLUSTER_SIZE(&header)); if (!buffer2) return -ENOMEM; /* Empty the file if it exists, we rely on zero bits */ if (ftruncate(raw_fd, 0) < 0) return -errno; if (ftruncate(raw_fd, HEADER_SIZE(&header)) < 0) return -errno; sz = sizeof(uint64_t) * HEADER_L1_SIZE(&header); l = pread(qcow2_fd, l1_table, sz, HEADER_L1_TABLE_OFFSET(&header)); if (l < 0) return -errno; if ((uint64_t) l != sz) return -EIO; for (i = 0; i < HEADER_L1_SIZE(&header); i ++) { uint64_t l2_begin, j; r = normalize_offset(&header, l1_table[i], &l2_begin, NULL, NULL); if (r < 0) return r; if (r == 0) continue; l = pread(qcow2_fd, l2_table, HEADER_CLUSTER_SIZE(&header), l2_begin); if (l < 0) return -errno; if ((uint64_t) l != HEADER_CLUSTER_SIZE(&header)) return -EIO; for (j = 0; j < HEADER_L2_SIZE(&header); j++) { uint64_t data_begin, p, compressed_size; bool compressed; p = ((i << HEADER_L2_BITS(&header)) + j) << HEADER_CLUSTER_BITS(&header); r = normalize_offset(&header, l2_table[j], &data_begin, &compressed, &compressed_size); if (r < 0) return r; if (r == 0) continue; if (compressed) r = decompress_cluster( qcow2_fd, data_begin, raw_fd, p, compressed_size, HEADER_CLUSTER_SIZE(&header), buffer1, buffer2); else r = copy_cluster( qcow2_fd, data_begin, raw_fd, p, HEADER_CLUSTER_SIZE(&header), buffer1); if (r < 0) return r; } } return 0; } int qcow2_detect(int fd) { be32_t id; ssize_t l; l = pread(fd, &id, sizeof(id), 0); if (l < 0) return -errno; if (l != sizeof(id)) return -EIO; return htobe32(QCOW2_MAGIC) == id; }
9,956
28.811377
111
c
null
systemd-main/src/import/test-qcow2.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <sys/stat.h> #include <sys/types.h> #include "fd-util.h" #include "log.h" #include "qcow2-util.h" int main(int argc, char *argv[]) { _cleanup_close_ int sfd = -EBADF, dfd = -EBADF; int r; if (argc != 3) { log_error("Needs two arguments."); return EXIT_FAILURE; } sfd = open(argv[1], O_RDONLY|O_CLOEXEC|O_NOCTTY); if (sfd < 0) { log_error_errno(errno, "Can't open source file: %m"); return EXIT_FAILURE; } dfd = open(argv[2], O_WRONLY|O_CREAT|O_CLOEXEC|O_NOCTTY, 0666); if (dfd < 0) { log_error_errno(errno, "Can't open destination file: %m"); return EXIT_FAILURE; } r = qcow2_convert(sfd, dfd); if (r < 0) { log_error_errno(r, "Failed to unpack: %m"); return EXIT_FAILURE; } return EXIT_SUCCESS; }
1,023
24.6
74
c
null
systemd-main/src/initctl/initctl.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <ctype.h> #include <errno.h> #include <stdio.h> #include <sys/epoll.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "sd-bus.h" #include "sd-daemon.h" #include "alloc-util.h" #include "bus-error.h" #include "bus-locator.h" #include "bus-util.h" #include "constants.h" #include "daemon-util.h" #include "fd-util.h" #include "format-util.h" #include "initreq.h" #include "list.h" #include "log.h" #include "main-func.h" #include "memory-util.h" #include "process-util.h" #include "reboot-util.h" #include "special.h" #define SERVER_FD_MAX 16 #define TIMEOUT_MSEC ((int) (DEFAULT_EXIT_USEC/USEC_PER_MSEC)) typedef struct Fifo Fifo; typedef struct Server { int epoll_fd; LIST_HEAD(Fifo, fifos); unsigned n_fifos; sd_bus *bus; bool quit; } Server; struct Fifo { Server *server; int fd; struct init_request buffer; size_t bytes_read; LIST_FIELDS(Fifo, fifo); }; static const char *translate_runlevel(int runlevel, bool *isolate) { static const struct { const int runlevel; const char *special; bool isolate; } table[] = { { '0', SPECIAL_POWEROFF_TARGET, false }, { '1', SPECIAL_RESCUE_TARGET, true }, { 's', SPECIAL_RESCUE_TARGET, true }, { 'S', SPECIAL_RESCUE_TARGET, true }, { '2', SPECIAL_MULTI_USER_TARGET, true }, { '3', SPECIAL_MULTI_USER_TARGET, true }, { '4', SPECIAL_MULTI_USER_TARGET, true }, { '5', SPECIAL_GRAPHICAL_TARGET, true }, { '6', SPECIAL_REBOOT_TARGET, false }, }; assert(isolate); for (size_t i = 0; i < ELEMENTSOF(table); i++) if (table[i].runlevel == runlevel) { *isolate = table[i].isolate; if (runlevel == '6' && kexec_loaded()) return SPECIAL_KEXEC_TARGET; return table[i].special; } return NULL; } static int change_runlevel(Server *s, int runlevel) { const char *target; _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL; const char *mode; bool isolate = false; int r; assert(s); target = translate_runlevel(runlevel, &isolate); if (!target) { log_warning("Got request for unknown runlevel %c, ignoring.", runlevel); return 0; } if (isolate) mode = "isolate"; else mode = "replace-irreversibly"; log_debug("Requesting %s/start/%s", target, mode); r = bus_call_method(s->bus, bus_systemd_mgr, "StartUnit", &error, NULL, "ss", target, mode); if (r < 0) return log_error_errno(r, "Failed to change runlevel: %s", bus_error_message(&error, r)); return 0; } static void request_process(Server *s, const struct init_request *req) { assert(s); assert(req); if (req->magic != INIT_MAGIC) { log_error("Got initctl request with invalid magic. Ignoring."); return; } switch (req->cmd) { case INIT_CMD_RUNLVL: if (!isprint(req->runlevel)) log_error("Got invalid runlevel. Ignoring."); else switch (req->runlevel) { /* we are async anyway, so just use kill for reexec/reload */ case 'u': case 'U': if (kill(1, SIGTERM) < 0) log_error_errno(errno, "kill() failed: %m"); /* The bus connection will be * terminated if PID 1 is reexecuted, * hence let's just exit here, and * rely on that we'll be restarted on * the next request */ s->quit = true; break; case 'q': case 'Q': if (kill(1, SIGHUP) < 0) log_error_errno(errno, "kill() failed: %m"); break; default: (void) change_runlevel(s, req->runlevel); } return; case INIT_CMD_POWERFAIL: case INIT_CMD_POWERFAILNOW: case INIT_CMD_POWEROK: log_warning("Received UPS/power initctl request. This is not implemented in systemd. Upgrade your UPS daemon!"); return; case INIT_CMD_CHANGECONS: log_warning("Received console change initctl request. This is not implemented in systemd."); return; case INIT_CMD_SETENV: case INIT_CMD_UNSETENV: log_warning("Received environment initctl request. This is not implemented in systemd."); return; default: log_warning("Received unknown initctl request. Ignoring."); return; } } static int fifo_process(Fifo *f) { ssize_t l; assert(f); errno = EIO; l = read(f->fd, ((uint8_t*) &f->buffer) + f->bytes_read, sizeof(f->buffer) - f->bytes_read); if (l <= 0) { if (errno == EAGAIN) return 0; return log_warning_errno(errno, "Failed to read from fifo: %m"); } f->bytes_read += l; assert(f->bytes_read <= sizeof(f->buffer)); if (f->bytes_read == sizeof(f->buffer)) { request_process(f->server, &f->buffer); f->bytes_read = 0; } return 0; } static Fifo* fifo_free(Fifo *f) { if (!f) return NULL; if (f->server) { assert(f->server->n_fifos > 0); f->server->n_fifos--; LIST_REMOVE(fifo, f->server->fifos, f); } if (f->fd >= 0) { if (f->server) (void) epoll_ctl(f->server->epoll_fd, EPOLL_CTL_DEL, f->fd, NULL); safe_close(f->fd); } return mfree(f); } DEFINE_TRIVIAL_CLEANUP_FUNC(Fifo*, fifo_free); static void server_done(Server *s) { assert(s); while (s->fifos) fifo_free(s->fifos); s->epoll_fd = safe_close(s->epoll_fd); s->bus = sd_bus_flush_close_unref(s->bus); } static int server_init(Server *s, unsigned n_sockets) { int r; /* This function will leave s partially initialized on failure. Caller needs to clean up. */ assert(s); assert(n_sockets > 0); s->epoll_fd = epoll_create1(EPOLL_CLOEXEC); if (s->epoll_fd < 0) return log_error_errno(errno, "Failed to create epoll object: %m"); for (unsigned i = 0; i < n_sockets; i++) { _cleanup_(fifo_freep) Fifo *f = NULL; int fd = SD_LISTEN_FDS_START + i; r = sd_is_fifo(fd, NULL); if (r < 0) return log_error_errno(r, "Failed to determine file descriptor type: %m"); if (!r) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Wrong file descriptor type."); f = new0(Fifo, 1); if (!f) return log_oom(); struct epoll_event ev = { .events = EPOLLIN, .data.ptr = f, }; if (epoll_ctl(s->epoll_fd, EPOLL_CTL_ADD, fd, &ev) < 0) return log_error_errno(errno, "Failed to add fifo fd to epoll object: %m"); f->fd = fd; f->server = s; LIST_PREPEND(fifo, s->fifos, TAKE_PTR(f)); s->n_fifos++; } r = bus_connect_system_systemd(&s->bus); if (r < 0) return log_error_errno(r, "Failed to get D-Bus connection: %m"); return 0; } static int process_event(Server *s, struct epoll_event *ev) { int r; _cleanup_(fifo_freep) Fifo *f = NULL; assert(s); assert(ev); if (!(ev->events & EPOLLIN)) return log_info_errno(SYNTHETIC_ERRNO(EIO), "Got invalid event from epoll. (3)"); f = (Fifo*) ev->data.ptr; r = fifo_process(f); if (r < 0) return log_info_errno(r, "Got error on fifo: %m"); TAKE_PTR(f); return 0; } static int run(int argc, char *argv[]) { _cleanup_(server_done) Server server = { .epoll_fd = -EBADF }; _unused_ _cleanup_(notify_on_cleanup) const char *notify_stop = NULL; int r, n; if (argc > 1) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program does not take arguments."); log_setup(); umask(0022); n = sd_listen_fds(true); if (n < 0) return log_error_errno(errno, "Failed to read listening file descriptors from environment: %m"); if (n <= 0 || n > SERVER_FD_MAX) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "No or too many file descriptors passed."); r = server_init(&server, (unsigned) n); if (r < 0) return r; notify_stop = notify_start(NOTIFY_READY, NOTIFY_STOPPING); while (!server.quit) { struct epoll_event event; int k; k = epoll_wait(server.epoll_fd, &event, 1, TIMEOUT_MSEC); if (k < 0) { if (errno == EINTR) continue; return log_error_errno(errno, "epoll_wait() failed: %m"); } if (k == 0) break; r = process_event(&server, &event); if (r < 0) return r; } return 0; } DEFINE_MAIN_FUNCTION(run);
10,603
28.786517
128
c
null
systemd-main/src/integritysetup/integrity-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "integrity-util.h" #include "extract-word.h" #include "fileio.h" #include "path-util.h" #include "percent-util.h" static int supported_integrity_algorithm(char *user_supplied) { if (!STR_IN_SET(user_supplied, "crc32", "crc32c", "sha1", "sha256", "hmac-sha256")) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unsupported integrity algorithm (%s)", user_supplied); return 0; } int parse_integrity_options( const char *options, uint32_t *ret_activate_flags, int *ret_percent, usec_t *ret_commit_time, char **ret_data_device, char **ret_integrity_alg) { int r; for (;;) { _cleanup_free_ char *word = NULL; char *val; r = extract_first_word(&options, &word, ",", EXTRACT_DONT_COALESCE_SEPARATORS | EXTRACT_UNESCAPE_SEPARATORS); if (r < 0) return log_error_errno(r, "Failed to parse options: %m"); if (r == 0) break; else if (streq(word, "allow-discards")) { if (ret_activate_flags) *ret_activate_flags |= CRYPT_ACTIVATE_ALLOW_DISCARDS; } else if ((val = startswith(word, "mode="))) { if (streq(val, "journal")) { if (ret_activate_flags) *ret_activate_flags &= ~(CRYPT_ACTIVATE_NO_JOURNAL | CRYPT_ACTIVATE_NO_JOURNAL_BITMAP); } else if (streq(val, "bitmap")) { if (ret_activate_flags) { *ret_activate_flags &= ~CRYPT_ACTIVATE_NO_JOURNAL; *ret_activate_flags |= CRYPT_ACTIVATE_NO_JOURNAL_BITMAP; } } else if (streq(val, "direct")) { if (ret_activate_flags) { *ret_activate_flags |= CRYPT_ACTIVATE_NO_JOURNAL; *ret_activate_flags &= ~CRYPT_ACTIVATE_NO_JOURNAL_BITMAP; } } else log_warning("Encountered unknown mode option '%s', ignoring.", val); } else if ((val = startswith(word, "journal-watermark="))) { r = parse_percent(val); if (r < 0) return log_error_errno(r, "Failed to parse journal-watermark value or value out of range (%s)", val); if (ret_percent) *ret_percent = r; } else if ((val = startswith(word, "journal-commit-time="))) { usec_t tmp_commit_time; r = parse_sec(val, &tmp_commit_time); if (r < 0) return log_error_errno(r, "Failed to parse journal-commit-time value (%s)", val); if (ret_commit_time) *ret_commit_time = tmp_commit_time; } else if ((val = startswith(word, "data-device="))) { if (ret_data_device) { r = free_and_strdup(ret_data_device, val); if (r < 0) return log_oom(); } } else if ((val = startswith(word, "integrity-algorithm="))) { r = supported_integrity_algorithm(val); if (r < 0) return r; if (ret_integrity_alg) { r = free_and_strdup(ret_integrity_alg, val); if (r < 0) return log_oom(); } } else log_warning("Encountered unknown option '%s', ignoring.", word); } return r; }
4,225
47.574713
133
c
null
systemd-main/src/integritysetup/integrity-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <stdint.h> #include "cryptsetup-util.h" #include "time-util.h" int parse_integrity_options( const char *options, uint32_t *ret_activate_flags, int *ret_percent, usec_t *ret_commit_time, char **ret_data_device, char **ret_integrity_alg); #define DM_HMAC_256 "hmac(sha256)" #define DM_MAX_KEY_SIZE 4096 /* Maximum size of key allowed for dm-integrity */
535
25.8
90
h
null
systemd-main/src/journal-remote/fuzz-journal-remote.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "fuzz.h" #include <sys/mman.h> #include "sd-journal.h" #include "env-util.h" #include "fd-util.h" #include "fileio.h" #include "fs-util.h" #include "journal-remote.h" #include "logs-show.h" #include "memfd-util.h" #include "path-util.h" #include "rm-rf.h" #include "strv.h" #include "tmpfile-util.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_close_ int fdin_close = -EBADF, fdout = -EBADF; _cleanup_(rm_rf_physical_and_freep) char *tmp = NULL; _cleanup_(unlink_and_freep) char *name = NULL; _cleanup_(sd_journal_closep) sd_journal *j = NULL; _cleanup_(journal_remote_server_destroy) RemoteServer s = {}; void *mem; int fdin, r; if (outside_size_range(size, 3, 65536)) return 0; if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_ERR); assert_se(mkdtemp_malloc("/tmp/fuzz-journal-remote-XXXXXX", &tmp) >= 0); assert_se(name = path_join(tmp, "fuzz-journal-remote.XXXXXX.journal")); fdin = fdin_close = memfd_new_and_map("fuzz-journal-remote", size, &mem); if (fdin < 0) return log_error_errno(fdin, "memfd_new_and_map() failed: %m"); memcpy(mem, data, size); assert_se(munmap(mem, size) == 0); fdout = mkostemps(name, STRLEN(".journal"), O_CLOEXEC); if (fdout < 0) return log_error_errno(errno, "mkostemps() failed: %m"); /* In */ r = journal_remote_server_init(&s, name, JOURNAL_WRITE_SPLIT_NONE, 0); if (r < 0) { assert_se(IN_SET(r, -ENOMEM, -EMFILE, -ENFILE)); return r; } r = journal_remote_add_source(&s, fdin, (char*) "fuzz-data", false); if (r < 0) return r; TAKE_FD(fdin_close); assert(r > 0); while (s.active) assert_se(journal_remote_handle_raw_source(NULL, fdin, 0, &s) >= 0); assert_se(close(fdin) < 0 && errno == EBADF); /* Check that the fd is closed already */ /* Out */ r = sd_journal_open_files(&j, (const char**) STRV_MAKE(name), 0); if (r < 0) { log_error_errno(r, "sd_journal_open_files([\"%s\"]) failed: %m", name); assert_se(IN_SET(r, -ENOMEM, -EMFILE, -ENFILE, -ENODATA)); return r; } _cleanup_fclose_ FILE *dev_null = NULL; if (getenv_bool("SYSTEMD_FUZZ_OUTPUT") <= 0) { dev_null = fopen("/dev/null", "we"); if (!dev_null) return log_error_errno(errno, "fopen(\"/dev/null\") failed: %m"); } for (OutputMode mode = 0; mode < _OUTPUT_MODE_MAX; mode++) { if (!dev_null) log_info("/* %s */", output_mode_to_string(mode)); r = show_journal(dev_null ?: stdout, j, mode, 0, 0, -1, 0, NULL); assert_se(r >= 0); r = sd_journal_seek_head(j); assert_se(r >= 0); } return 0; }
3,134
31.319588
95
c
null
systemd-main/src/journal-remote/journal-remote-parse.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "fd-util.h" #include "journal-remote-parse.h" #include "journald-native.h" #include "parse-util.h" #include "string-util.h" void source_free(RemoteSource *source) { if (!source) return; journal_importer_cleanup(&source->importer); log_debug("Writer ref count %u", source->writer->n_ref); writer_unref(source->writer); sd_event_source_unref(source->event); sd_event_source_unref(source->buffer_event); free(source); } /** * Initialize zero-filled source with given values. On success, takes * ownership of fd, name, and writer, otherwise does not touch them. */ RemoteSource* source_new(int fd, bool passive_fd, char *name, Writer *writer) { RemoteSource *source; log_debug("Creating source for %sfd:%d (%s)", passive_fd ? "passive " : "", fd, name); assert(fd >= 0); source = new0(RemoteSource, 1); if (!source) return NULL; source->importer = JOURNAL_IMPORTER_MAKE(fd); source->importer.passive_fd = passive_fd; source->importer.name = name; source->writer = writer; return source; } int process_source(RemoteSource *source, JournalFileFlags file_flags) { int r; assert(source); assert(source->writer); r = journal_importer_process_data(&source->importer); if (r <= 0) return r; /* We have a full event */ log_trace("Received full event from source@%p fd:%d (%s)", source, source->importer.fd, source->importer.name); if (source->importer.iovw.count == 0) { log_warning("Entry with no payload, skipping"); goto freeing; } assert(source->importer.iovw.iovec); r = writer_write(source->writer, &source->importer.iovw, &source->importer.ts, &source->importer.boot_id, file_flags); if (IN_SET(r, -EBADMSG, -EADDRNOTAVAIL)) { log_warning_errno(r, "Entry is invalid, ignoring."); r = 0; } else if (r < 0) log_error_errno(r, "Failed to write entry of %zu bytes: %m", iovw_size(&source->importer.iovw)); else r = 1; freeing: journal_importer_drop_iovw(&source->importer); return r; }
2,560
27.775281
79
c
null
systemd-main/src/journal-remote/journal-remote-parse.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-event.h" #include "journal-importer.h" #include "journal-remote-write.h" typedef struct RemoteSource { JournalImporter importer; Writer *writer; sd_event_source *event; sd_event_source *buffer_event; } RemoteSource; RemoteSource* source_new(int fd, bool passive_fd, char *name, Writer *writer); void source_free(RemoteSource *source); int process_source(RemoteSource *source, JournalFileFlags file_flags);
519
23.761905
78
h
null
systemd-main/src/journal-remote/journal-remote-write.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <libgen.h> #include "alloc-util.h" #include "journal-remote.h" #include "path-util.h" #include "stat-util.h" static int do_rotate(ManagedJournalFile **f, MMapCache *m, JournalFileFlags file_flags) { int r; r = managed_journal_file_rotate(f, m, file_flags, UINT64_MAX, NULL); if (r < 0) { if (*f) log_error_errno(r, "Failed to rotate %s: %m", (*f)->file->path); else log_error_errno(r, "Failed to create rotated journal: %m"); } return r; } int writer_new(RemoteServer *server, Writer **ret) { _cleanup_(writer_unrefp) Writer *w = NULL; int r; assert(server); assert(ret); w = new(Writer, 1); if (!w) return -ENOMEM; *w = (Writer) { .n_ref = 1, .metrics = server->metrics, .server = server, }; w->mmap = mmap_cache_new(); if (!w->mmap) return -ENOMEM; if (is_dir(server->output, /* follow = */ true) > 0) { w->output = strdup(server->output); if (!w->output) return -ENOMEM; } else { r = path_extract_directory(server->output, &w->output); if (r < 0) return r; } *ret = TAKE_PTR(w); return 0; } static Writer* writer_free(Writer *w) { if (!w) return NULL; if (w->journal) { log_debug("Closing journal file %s.", w->journal->file->path); managed_journal_file_close(w->journal); } if (w->server && w->hashmap_key) hashmap_remove(w->server->writers, w->hashmap_key); free(w->hashmap_key); if (w->mmap) mmap_cache_unref(w->mmap); free(w->output); return mfree(w); } DEFINE_TRIVIAL_REF_UNREF_FUNC(Writer, writer, writer_free); int writer_write(Writer *w, const struct iovec_wrapper *iovw, const dual_timestamp *ts, const sd_id128_t *boot_id, JournalFileFlags file_flags) { int r; assert(w); assert(iovw); assert(iovw->count > 0); if (journal_file_rotate_suggested(w->journal->file, 0, LOG_DEBUG)) { log_info("%s: Journal header limits reached or header out-of-date, rotating", w->journal->file->path); r = do_rotate(&w->journal, w->mmap, file_flags); if (r < 0) return r; r = journal_directory_vacuum(w->output, w->metrics.max_use, w->metrics.n_max_files, 0, NULL, /* verbose = */ true); if (r < 0) return r; } r = journal_file_append_entry( w->journal->file, ts, boot_id, iovw->iovec, iovw->count, &w->seqnum, /* seqnum_id= */ NULL, /* ret_object= */ NULL, /* ret_offset= */ NULL); if (r >= 0) { if (w->server) w->server->event_count += 1; return 0; } else if (r == -EBADMSG) return r; log_debug_errno(r, "%s: Write failed, rotating: %m", w->journal->file->path); r = do_rotate(&w->journal, w->mmap, file_flags); if (r < 0) return r; else log_debug("%s: Successfully rotated journal", w->journal->file->path); r = journal_directory_vacuum(w->output, w->metrics.max_use, w->metrics.n_max_files, 0, NULL, /* verbose = */ true); if (r < 0) return r; log_debug("Retrying write."); r = journal_file_append_entry( w->journal->file, ts, boot_id, iovw->iovec, iovw->count, &w->seqnum, /* seqnum_id= */ NULL, /* ret_object= */ NULL, /* ret_offset= */ NULL); if (r < 0) return r; if (w->server) w->server->event_count += 1; return 0; }
4,523
29.362416
131
c
null
systemd-main/src/journal-remote/journal-remote-write.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "journal-importer.h" #include "managed-journal-file.h" typedef struct RemoteServer RemoteServer; typedef struct Writer { ManagedJournalFile *journal; JournalMetrics metrics; char *output; /* directory where we write, for vacuuming */ MMapCache *mmap; RemoteServer *server; char *hashmap_key; uint64_t seqnum; unsigned n_ref; } Writer; int writer_new(RemoteServer *server, Writer **ret); Writer* writer_ref(Writer *w); Writer* writer_unref(Writer *w); DEFINE_TRIVIAL_CLEANUP_FUNC(Writer*, writer_unref); int writer_write(Writer *s, const struct iovec_wrapper *iovw, const dual_timestamp *ts, const sd_id128_t *boot_id, JournalFileFlags file_flags); typedef enum JournalWriteSplitMode { JOURNAL_WRITE_SPLIT_NONE, JOURNAL_WRITE_SPLIT_HOST, _JOURNAL_WRITE_SPLIT_MAX, _JOURNAL_WRITE_SPLIT_INVALID = -EINVAL, } JournalWriteSplitMode;
1,082
25.414634
76
h
null
systemd-main/src/journal-remote/journal-remote.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <stdlib.h> #include <sys/prctl.h> #include <stdint.h> #include "sd-daemon.h" #include "af-list.h" #include "alloc-util.h" #include "constants.h" #include "errno-util.h" #include "escape.h" #include "fd-util.h" #include "journal-remote-write.h" #include "journal-remote.h" #include "journald-native.h" #include "macro.h" #include "managed-journal-file.h" #include "parse-util.h" #include "parse-helpers.h" #include "process-util.h" #include "socket-util.h" #include "stdio-util.h" #include "string-util.h" #include "strv.h" #define REMOTE_JOURNAL_PATH "/var/log/journal/remote" #define filename_escape(s) xescape((s), "/ ") #if HAVE_MICROHTTPD MHDDaemonWrapper *MHDDaemonWrapper_free(MHDDaemonWrapper *d) { if (!d) return NULL; if (d->daemon) MHD_stop_daemon(d->daemon); sd_event_source_unref(d->io_event); sd_event_source_unref(d->timer_event); return mfree(d); } #endif static int open_output(RemoteServer *s, Writer *w, const char* host) { _cleanup_free_ char *_filename = NULL; const char *filename; int r; assert(s); assert(w); switch (s->split_mode) { case JOURNAL_WRITE_SPLIT_NONE: filename = s->output; break; case JOURNAL_WRITE_SPLIT_HOST: { _cleanup_free_ char *name = NULL; assert(host); name = filename_escape(host); if (!name) return log_oom(); r = asprintf(&_filename, "%s/remote-%s.journal", s->output, name); if (r < 0) return log_oom(); filename = _filename; break; } default: assert_not_reached(); } r = managed_journal_file_open_reliably( filename, O_RDWR|O_CREAT, s->file_flags, 0640, UINT64_MAX, &w->metrics, w->mmap, NULL, NULL, &w->journal); if (r < 0) return log_error_errno(r, "Failed to open output journal %s: %m", filename); log_debug("Opened output file %s", w->journal->file->path); return 0; } /********************************************************************** ********************************************************************** **********************************************************************/ static int init_writer_hashmap(RemoteServer *s) { static const struct hash_ops* const hash_ops[] = { [JOURNAL_WRITE_SPLIT_NONE] = NULL, [JOURNAL_WRITE_SPLIT_HOST] = &string_hash_ops, }; assert(s); assert(s->split_mode >= 0 && s->split_mode < (int) ELEMENTSOF(hash_ops)); s->writers = hashmap_new(hash_ops[s->split_mode]); if (!s->writers) return log_oom(); return 0; } int journal_remote_get_writer(RemoteServer *s, const char *host, Writer **writer) { _cleanup_(writer_unrefp) Writer *w = NULL; const void *key; int r; assert(s); assert(writer); switch (s->split_mode) { case JOURNAL_WRITE_SPLIT_NONE: key = "one and only"; break; case JOURNAL_WRITE_SPLIT_HOST: assert(host); key = host; break; default: assert_not_reached(); } w = hashmap_get(s->writers, key); if (w) writer_ref(w); else { r = writer_new(s, &w); if (r < 0) return r; if (s->split_mode == JOURNAL_WRITE_SPLIT_HOST) { w->hashmap_key = strdup(key); if (!w->hashmap_key) return -ENOMEM; } r = open_output(s, w, host); if (r < 0) return r; r = hashmap_put(s->writers, w->hashmap_key ?: key, w); if (r < 0) return r; } *writer = TAKE_PTR(w); return 0; } /********************************************************************** ********************************************************************** **********************************************************************/ /* This should go away as soon as μhttpd allows state to be passed around. */ RemoteServer *journal_remote_server_global; static int dispatch_raw_source_event(sd_event_source *event, int fd, uint32_t revents, void *userdata); static int dispatch_raw_source_until_block(sd_event_source *event, void *userdata); static int dispatch_blocking_source_event(sd_event_source *event, void *userdata); static int dispatch_raw_connection_event(sd_event_source *event, int fd, uint32_t revents, void *userdata); static int get_source_for_fd(RemoteServer *s, int fd, char *name, RemoteSource **source) { Writer *writer; int r; /* This takes ownership of name, but only on success. */ assert(s); assert(fd >= 0); assert(source); if (!GREEDY_REALLOC0(s->sources, fd + 1)) return log_oom(); r = journal_remote_get_writer(s, name, &writer); if (r < 0) return log_warning_errno(r, "Failed to get writer for source %s: %m", name); if (!s->sources[fd]) { s->sources[fd] = source_new(fd, false, name, writer); if (!s->sources[fd]) { writer_unref(writer); return log_oom(); } s->active++; } *source = s->sources[fd]; return 0; } static int remove_source(RemoteServer *s, int fd) { RemoteSource *source; assert(s); assert(fd >= 0 && fd < (ssize_t) MALLOC_ELEMENTSOF(s->sources)); source = s->sources[fd]; if (source) { /* this closes fd too */ source_free(source); s->sources[fd] = NULL; s->active--; } return 0; } int journal_remote_add_source(RemoteServer *s, int fd, char* name, bool own_name) { RemoteSource *source = NULL; int r; /* This takes ownership of name, even on failure, if own_name is true. */ assert(s); assert(fd >= 0); assert(name); if (!own_name) { name = strdup(name); if (!name) return log_oom(); } r = get_source_for_fd(s, fd, name, &source); if (r < 0) { log_error_errno(r, "Failed to create source for fd:%d (%s): %m", fd, name); free(name); return r; } r = sd_event_add_io(s->events, &source->event, fd, EPOLLIN|EPOLLRDHUP|EPOLLPRI, dispatch_raw_source_event, source); if (r == 0) { /* Add additional source for buffer processing. It will be * enabled later. */ r = sd_event_add_defer(s->events, &source->buffer_event, dispatch_raw_source_until_block, source); if (r == 0) r = sd_event_source_set_enabled(source->buffer_event, SD_EVENT_OFF); } else if (r == -EPERM) { log_debug("Falling back to sd_event_add_defer for fd:%d (%s)", fd, name); r = sd_event_add_defer(s->events, &source->event, dispatch_blocking_source_event, source); if (r == 0) r = sd_event_source_set_enabled(source->event, SD_EVENT_ON); } if (r < 0) { log_error_errno(r, "Failed to register event source for fd:%d: %m", fd); goto error; } r = sd_event_source_set_description(source->event, name); if (r < 0) { log_error_errno(r, "Failed to set source name for fd:%d: %m", fd); goto error; } return 1; /* work to do */ error: remove_source(s, fd); return r; } int journal_remote_add_raw_socket(RemoteServer *s, int fd) { _unused_ _cleanup_close_ int fd_ = fd; char name[STRLEN("raw-socket-") + DECIMAL_STR_MAX(int) + 1]; int r; assert(s); assert(fd >= 0); r = sd_event_add_io(s->events, &s->listen_event, fd, EPOLLIN, dispatch_raw_connection_event, s); if (r < 0) return r; xsprintf(name, "raw-socket-%d", fd); r = sd_event_source_set_description(s->listen_event, name); if (r < 0) return r; TAKE_FD(fd_); s->active++; return 0; } /********************************************************************** ********************************************************************** **********************************************************************/ int journal_remote_server_init( RemoteServer *s, const char *output, JournalWriteSplitMode split_mode, JournalFileFlags file_flags) { int r; assert(s); assert(journal_remote_server_global == NULL); journal_remote_server_global = s; s->split_mode = split_mode; s->file_flags = file_flags; if (output) s->output = output; else if (split_mode == JOURNAL_WRITE_SPLIT_NONE) s->output = REMOTE_JOURNAL_PATH "/remote.journal"; else if (split_mode == JOURNAL_WRITE_SPLIT_HOST) s->output = REMOTE_JOURNAL_PATH; else assert_not_reached(); r = sd_event_default(&s->events); if (r < 0) return log_error_errno(r, "Failed to allocate event loop: %m"); r = init_writer_hashmap(s); if (r < 0) return r; return 0; } void journal_remote_server_destroy(RemoteServer *s) { size_t i; if (!s) return; #if HAVE_MICROHTTPD hashmap_free_with_destructor(s->daemons, MHDDaemonWrapper_free); #endif for (i = 0; i < MALLOC_ELEMENTSOF(s->sources); i++) remove_source(s, i); free(s->sources); writer_unref(s->_single_writer); hashmap_free(s->writers); sd_event_source_unref(s->sigterm_event); sd_event_source_unref(s->sigint_event); sd_event_source_unref(s->listen_event); sd_event_unref(s->events); if (s == journal_remote_server_global) journal_remote_server_global = NULL; /* fds that we're listening on remain open... */ } /********************************************************************** ********************************************************************** **********************************************************************/ int journal_remote_handle_raw_source( sd_event_source *event, int fd, uint32_t revents, RemoteServer *s) { RemoteSource *source; int r; /* Returns 1 if there might be more data pending, * 0 if data is currently exhausted, negative on error. */ assert(s); assert(fd >= 0 && fd < (ssize_t) MALLOC_ELEMENTSOF(s->sources)); source = s->sources[fd]; assert(source->importer.fd == fd); r = process_source(source, s->file_flags); if (journal_importer_eof(&source->importer)) { size_t remaining; log_debug("EOF reached with source %s (fd=%d)", source->importer.name, source->importer.fd); remaining = journal_importer_bytes_remaining(&source->importer); if (remaining > 0) log_notice("Premature EOF. %zu bytes lost.", remaining); remove_source(s, source->importer.fd); log_debug("%zu active sources remaining", s->active); return 0; } else if (r == -E2BIG) { log_notice("Entry with too many fields, skipped"); return 1; } else if (r == -ENOBUFS) { log_notice("Entry too big, skipped"); return 1; } else if (r == -EAGAIN) { return 0; } else if (r < 0) { log_debug_errno(r, "Closing connection: %m"); remove_source(s, fd); return 0; } else return 1; } static int dispatch_raw_source_until_block(sd_event_source *event, void *userdata) { RemoteSource *source = ASSERT_PTR(userdata); int r; assert(event); /* Make sure event stays around even if source is destroyed */ sd_event_source_ref(event); r = journal_remote_handle_raw_source(event, source->importer.fd, EPOLLIN, journal_remote_server_global); if (r != 1) { int k; /* No more data for now */ k = sd_event_source_set_enabled(event, SD_EVENT_OFF); if (k < 0) r = k; } sd_event_source_unref(event); return r; } static int dispatch_raw_source_event(sd_event_source *event, int fd, uint32_t revents, void *userdata) { RemoteSource *source = ASSERT_PTR(userdata); int r; assert(source->event); assert(source->buffer_event); r = journal_remote_handle_raw_source(event, fd, EPOLLIN, journal_remote_server_global); if (r == 1) { int k; /* Might have more data. We need to rerun the handler * until we are sure the buffer is exhausted. */ k = sd_event_source_set_enabled(source->buffer_event, SD_EVENT_ON); if (k < 0) r = k; } return r; } static int dispatch_blocking_source_event(sd_event_source *event, void *userdata) { RemoteSource *source = ASSERT_PTR(userdata); return journal_remote_handle_raw_source(event, source->importer.fd, EPOLLIN, journal_remote_server_global); } static int accept_connection( const char* type, int fd, SocketAddress *addr, char **hostname) { _cleanup_close_ int fd2 = -EBADF; int r; assert(addr); assert(hostname); log_debug("Accepting new %s connection on fd:%d", type, fd); fd2 = accept4(fd, &addr->sockaddr.sa, &addr->size, SOCK_NONBLOCK|SOCK_CLOEXEC); if (fd2 < 0) { if (ERRNO_IS_ACCEPT_AGAIN(errno)) return -EAGAIN; return log_error_errno(errno, "accept() on fd:%d failed: %m", fd); } switch (socket_address_family(addr)) { case AF_INET: case AF_INET6: { _cleanup_free_ char *a = NULL; char *b; r = socket_address_print(addr, &a); if (r < 0) return log_error_errno(r, "socket_address_print(): %m"); r = socknameinfo_pretty(&addr->sockaddr, addr->size, &b); if (r < 0) return log_error_errno(r, "Resolving hostname failed: %m"); log_debug("Accepted %s %s connection from %s", type, af_to_ipv4_ipv6(socket_address_family(addr)), a); *hostname = b; return TAKE_FD(fd2); } default: return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Rejected %s connection with unsupported family %d", type, socket_address_family(addr)); } } static int dispatch_raw_connection_event( sd_event_source *event, int fd, uint32_t revents, void *userdata) { RemoteServer *s = ASSERT_PTR(userdata); int fd2; SocketAddress addr = { .size = sizeof(union sockaddr_union), .type = SOCK_STREAM, }; char *hostname = NULL; fd2 = accept_connection("raw", fd, &addr, &hostname); if (fd2 == -EAGAIN) return 0; if (fd2 < 0) return fd2; return journal_remote_add_source(s, fd2, hostname, true); }
17,684
29.917832
115
c
null
systemd-main/src/journal-remote/journal-remote.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-event.h" #include "hashmap.h" #include "journal-remote-parse.h" #include "journal-remote-write.h" #include "journal-vacuum.h" #if HAVE_MICROHTTPD #include "microhttpd-util.h" typedef struct MHDDaemonWrapper MHDDaemonWrapper; struct MHDDaemonWrapper { uint64_t fd; struct MHD_Daemon *daemon; sd_event_source *io_event; sd_event_source *timer_event; }; MHDDaemonWrapper *MHDDaemonWrapper_free(MHDDaemonWrapper *d); DEFINE_TRIVIAL_CLEANUP_FUNC(MHDDaemonWrapper*, MHDDaemonWrapper_free); #endif struct RemoteServer { RemoteSource **sources; size_t active; sd_event *events; sd_event_source *sigterm_event, *sigint_event, *listen_event; Hashmap *writers; Writer *_single_writer; uint64_t event_count; #if HAVE_MICROHTTPD Hashmap *daemons; #endif const char *output; /* either the output file or directory */ JournalWriteSplitMode split_mode; JournalFileFlags file_flags; bool check_trust; JournalMetrics metrics; }; extern RemoteServer *journal_remote_server_global; int journal_remote_server_init( RemoteServer *s, const char *output, JournalWriteSplitMode split_mode, JournalFileFlags file_flags); int journal_remote_get_writer(RemoteServer *s, const char *host, Writer **writer); int journal_remote_add_source(RemoteServer *s, int fd, char* name, bool own_name); int journal_remote_add_raw_socket(RemoteServer *s, int fd); int journal_remote_handle_raw_source( sd_event_source *event, int fd, uint32_t revents, RemoteServer *s); void journal_remote_server_destroy(RemoteServer *s);
1,854
26.279412
88
h
null
systemd-main/src/journal-remote/journal-upload-journal.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <curl/curl.h> #include <stdbool.h> #include "sd-daemon.h" #include "alloc-util.h" #include "journal-upload.h" #include "log.h" #include "string-util.h" #include "utf8.h" /** * Write up to size bytes to buf. Return negative on error, and number of * bytes written otherwise. The last case is a kind of an error too. */ static ssize_t write_entry(char *buf, size_t size, Uploader *u) { int r; size_t pos = 0; assert(size <= SSIZE_MAX); for (;;) { switch (u->entry_state) { case ENTRY_CURSOR: { u->current_cursor = mfree(u->current_cursor); r = sd_journal_get_cursor(u->journal, &u->current_cursor); if (r < 0) return log_error_errno(r, "Failed to get cursor: %m"); r = snprintf(buf + pos, size - pos, "__CURSOR=%s\n", u->current_cursor); assert(r >= 0); if ((size_t) r > size - pos) /* not enough space */ return pos; u->entry_state++; if (pos + r == size) { /* exactly one character short, but we don't need it */ buf[size - 1] = '\n'; return size; } pos += r; } _fallthrough_; case ENTRY_REALTIME: { usec_t realtime; r = sd_journal_get_realtime_usec(u->journal, &realtime); if (r < 0) return log_error_errno(r, "Failed to get realtime timestamp: %m"); r = snprintf(buf + pos, size - pos, "__REALTIME_TIMESTAMP="USEC_FMT"\n", realtime); assert(r >= 0); if ((size_t) r > size - pos) /* not enough space */ return pos; u->entry_state++; if (r + pos == size) { /* exactly one character short, but we don't need it */ buf[size - 1] = '\n'; return size; } pos += r; } _fallthrough_; case ENTRY_MONOTONIC: { usec_t monotonic; sd_id128_t boot_id; r = sd_journal_get_monotonic_usec(u->journal, &monotonic, &boot_id); if (r < 0) return log_error_errno(r, "Failed to get monotonic timestamp: %m"); r = snprintf(buf + pos, size - pos, "__MONOTONIC_TIMESTAMP="USEC_FMT"\n", monotonic); assert(r >= 0); if ((size_t) r > size - pos) /* not enough space */ return pos; u->entry_state++; if (r + pos == size) { /* exactly one character short, but we don't need it */ buf[size - 1] = '\n'; return size; } pos += r; } _fallthrough_; case ENTRY_BOOT_ID: { sd_id128_t boot_id; r = sd_journal_get_monotonic_usec(u->journal, NULL, &boot_id); if (r < 0) return log_error_errno(r, "Failed to get monotonic timestamp: %m"); r = snprintf(buf + pos, size - pos, "_BOOT_ID=%s\n", SD_ID128_TO_STRING(boot_id)); assert(r >= 0); if ((size_t) r > size - pos) /* not enough space */ return pos; u->entry_state++; if (r + pos == size) { /* exactly one character short, but we don't need it */ buf[size - 1] = '\n'; return size; } pos += r; } _fallthrough_; case ENTRY_NEW_FIELD: { u->field_pos = 0; r = sd_journal_enumerate_data(u->journal, &u->field_data, &u->field_length); if (r < 0) return log_error_errno(r, "Failed to move to next field in entry: %m"); else if (r == 0) { u->entry_state = ENTRY_OUTRO; continue; } /* We already printed the boot id from the data in * the header, hence let's suppress it here */ if (memory_startswith(u->field_data, u->field_length, "_BOOT_ID=")) continue; if (!utf8_is_printable_newline(u->field_data, u->field_length, false)) { u->entry_state = ENTRY_BINARY_FIELD_START; continue; } u->entry_state++; } _fallthrough_; case ENTRY_TEXT_FIELD: case ENTRY_BINARY_FIELD: { bool done; size_t tocopy; done = size - pos > u->field_length - u->field_pos; if (done) tocopy = u->field_length - u->field_pos; else tocopy = size - pos; memcpy(buf + pos, (char*) u->field_data + u->field_pos, tocopy); if (done) { buf[pos + tocopy] = '\n'; pos += tocopy + 1; u->entry_state = ENTRY_NEW_FIELD; continue; } else { u->field_pos += tocopy; return size; } } case ENTRY_BINARY_FIELD_START: { const char *c; size_t len; c = memchr(u->field_data, '=', u->field_length); if (!c || c == u->field_data) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid field."); len = c - (const char*)u->field_data; /* need space for label + '\n' */ if (size - pos < len + 1) return pos; memcpy(buf + pos, u->field_data, len); buf[pos + len] = '\n'; pos += len + 1; u->field_pos = len + 1; u->entry_state++; } _fallthrough_; case ENTRY_BINARY_FIELD_SIZE: { uint64_t le64; /* need space for uint64_t */ if (size - pos < 8) return pos; le64 = htole64(u->field_length - u->field_pos); memcpy(buf + pos, &le64, 8); pos += 8; u->entry_state++; continue; } case ENTRY_OUTRO: /* need space for '\n' */ if (size - pos < 1) return pos; buf[pos++] = '\n'; u->entry_state++; u->entries_sent++; return pos; default: assert_not_reached(); } } assert_not_reached(); } static void check_update_watchdog(Uploader *u) { usec_t after; usec_t elapsed_time; if (u->watchdog_usec <= 0) return; after = now(CLOCK_MONOTONIC); elapsed_time = usec_sub_unsigned(after, u->watchdog_timestamp); if (elapsed_time > u->watchdog_usec / 2) { log_debug("Update watchdog timer"); sd_notify(false, "WATCHDOG=1"); u->watchdog_timestamp = after; } } static size_t journal_input_callback(void *buf, size_t size, size_t nmemb, void *userp) { Uploader *u = ASSERT_PTR(userp); int r; sd_journal *j; size_t filled = 0; ssize_t w; assert(nmemb <= SSIZE_MAX / size); check_update_watchdog(u); j = u->journal; while (j && filled < size * nmemb) { if (u->entry_state == ENTRY_DONE) { r = sd_journal_next(j); if (r < 0) { log_error_errno(r, "Failed to move to next entry in journal: %m"); return CURL_READFUNC_ABORT; } else if (r == 0) { if (u->input_event) log_debug("No more entries, waiting for journal."); else { log_info("No more entries, closing journal."); close_journal_input(u); } u->uploading = false; break; } u->entry_state = ENTRY_CURSOR; } w = write_entry((char*)buf + filled, size * nmemb - filled, u); if (w < 0) return CURL_READFUNC_ABORT; filled += w; if (filled == 0) { log_error("Buffer space is too small to write entry."); return CURL_READFUNC_ABORT; } else if (u->entry_state != ENTRY_DONE) /* This means that all available space was used up */ break; log_debug("Entry %zu (%s) has been uploaded.", u->entries_sent, u->current_cursor); } return filled; } void close_journal_input(Uploader *u) { assert(u); if (u->journal) { log_debug("Closing journal input."); sd_journal_close(u->journal); u->journal = NULL; } u->timeout = 0; } static int process_journal_input(Uploader *u, int skip) { int r; if (u->uploading) return 0; r = sd_journal_next_skip(u->journal, skip); if (r < 0) return log_error_errno(r, "Failed to skip to next entry: %m"); else if (r < skip) return 0; /* have data */ u->entry_state = ENTRY_CURSOR; return start_upload(u, journal_input_callback, u); } int check_journal_input(Uploader *u) { if (u->input_event) { int r; r = sd_journal_process(u->journal); if (r < 0) { log_error_errno(r, "Failed to process journal: %m"); close_journal_input(u); return r; } if (r == SD_JOURNAL_NOP) return 0; } return process_journal_input(u, 1); } static int dispatch_journal_input(sd_event_source *event, int fd, uint32_t revents, void *userp) { Uploader *u = ASSERT_PTR(userp); if (u->uploading) return 0; log_debug("Detected journal input, checking for new data."); return check_journal_input(u); } int open_journal_for_upload(Uploader *u, sd_journal *j, const char *cursor, bool after_cursor, bool follow) { int fd, r, events; u->journal = j; sd_journal_set_data_threshold(j, 0); if (follow) { fd = sd_journal_get_fd(j); if (fd < 0) return log_error_errno(fd, "sd_journal_get_fd failed: %m"); events = sd_journal_get_events(j); r = sd_journal_reliable_fd(j); assert(r >= 0); if (r > 0) u->timeout = -1; else u->timeout = JOURNAL_UPLOAD_POLL_TIMEOUT; r = sd_event_add_io(u->events, &u->input_event, fd, events, dispatch_journal_input, u); if (r < 0) return log_error_errno(r, "Failed to register input event: %m"); log_debug("Listening for journal events on fd:%d, timeout %d", fd, u->timeout == UINT64_MAX ? -1 : (int) u->timeout); } else log_debug("Not listening for journal events."); if (cursor) { r = sd_journal_seek_cursor(j, cursor); if (r < 0) return log_error_errno(r, "Failed to seek to cursor %s: %m", cursor); } return process_journal_input(u, !!after_cursor); }
14,535
34.453659
103
c
null
systemd-main/src/journal-remote/journal-upload.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <inttypes.h> #include "sd-event.h" #include "sd-journal.h" #include "time-util.h" typedef enum { ENTRY_CURSOR = 0, /* Nothing actually written yet. */ ENTRY_REALTIME, ENTRY_MONOTONIC, ENTRY_BOOT_ID, ENTRY_NEW_FIELD, /* In between fields. */ ENTRY_TEXT_FIELD, /* In the middle of a text field. */ ENTRY_BINARY_FIELD_START, /* Writing the name of a binary field. */ ENTRY_BINARY_FIELD_SIZE, /* Writing the size of a binary field. */ ENTRY_BINARY_FIELD, /* In the middle of a binary field. */ ENTRY_OUTRO, /* Writing '\n' */ ENTRY_DONE, /* Need to move to a new field. */ } entry_state; typedef struct Uploader { sd_event *events; sd_event_source *sigint_event, *sigterm_event; char *url; CURL *easy; bool uploading; char error[CURL_ERROR_SIZE]; struct curl_slist *header; char *answer; sd_event_source *input_event; uint64_t timeout; /* fd stuff */ int input; /* journal stuff */ sd_journal* journal; entry_state entry_state; const void *field_data; size_t field_pos, field_length; /* general metrics */ const char *state_file; size_t entries_sent; char *last_cursor, *current_cursor; usec_t watchdog_timestamp; usec_t watchdog_usec; } Uploader; #define JOURNAL_UPLOAD_POLL_TIMEOUT (10 * USEC_PER_SEC) int start_upload(Uploader *u, size_t (*input_callback)(void *ptr, size_t size, size_t nmemb, void *userdata), void *data); int open_journal_for_upload(Uploader *u, sd_journal *j, const char *cursor, bool after_cursor, bool follow); void close_journal_input(Uploader *u); int check_journal_input(Uploader *u);
2,215
28.546667
77
h
null
systemd-main/src/journal-remote/microhttpd-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <microhttpd.h> #include <stdarg.h> #include "macro.h" /* Those defines are added when options are renamed. If the old names * are not '#define'd, then they are not deprecated yet and there are * enum elements with the same name. Hence let's check for the *old* name, * and define the new name by the value of the old name. */ /* Renamed in μhttpd 0.9.51 */ #ifndef MHD_USE_PIPE_FOR_SHUTDOWN # define MHD_USE_ITC MHD_USE_PIPE_FOR_SHUTDOWN #endif /* Renamed in μhttpd 0.9.52 */ #ifndef MHD_USE_EPOLL_LINUX_ONLY # define MHD_USE_EPOLL MHD_USE_EPOLL_LINUX_ONLY #endif /* Renamed in μhttpd 0.9.52 */ #ifndef MHD_USE_SSL # define MHD_USE_TLS MHD_USE_SSL #endif /* Renamed in μhttpd 0.9.53 */ #ifndef MHD_USE_POLL_INTERNALLY # define MHD_USE_POLL_INTERNAL_THREAD MHD_USE_POLL_INTERNALLY #endif /* Both the old and new names are defines, check for the new one. */ /* Compatibility with libmicrohttpd < 0.9.38 */ #ifndef MHD_HTTP_NOT_ACCEPTABLE # define MHD_HTTP_NOT_ACCEPTABLE MHD_HTTP_METHOD_NOT_ACCEPTABLE #endif /* Renamed in μhttpd 0.9.74 (8c644fc1f4d498ea489add8d40a68f5d3e5899fa) */ #ifndef MHD_HTTP_CONTENT_TOO_LARGE # ifdef MHD_HTTP_PAYLOAD_TOO_LARGE # define MHD_HTTP_CONTENT_TOO_LARGE MHD_HTTP_PAYLOAD_TOO_LARGE /* 0.9.53 or newer */ # else # define MHD_HTTP_CONTENT_TOO_LARGE MHD_HTTP_REQUEST_ENTITY_TOO_LARGE # endif #endif #if MHD_VERSION < 0x00094203 # define MHD_create_response_from_fd_at_offset64 MHD_create_response_from_fd_at_offset #endif #if MHD_VERSION >= 0x00097002 # define mhd_result enum MHD_Result #else # define mhd_result int #endif void microhttpd_logger(void *arg, const char *fmt, va_list ap) _printf_(2, 0); /* respond_oom() must be usable with return, hence this form. */ #define respond_oom(connection) log_oom(), mhd_respond_oom(connection) int mhd_respondf(struct MHD_Connection *connection, int error, enum MHD_RequestTerminationCode code, const char *format, ...) _printf_(4,5); int mhd_respond(struct MHD_Connection *connection, enum MHD_RequestTerminationCode code, const char *message); int mhd_respond_oom(struct MHD_Connection *connection); int check_permissions(struct MHD_Connection *connection, int *code, char **hostname); /* Set gnutls internal logging function to a callback which uses our * own logging framework. * * gnutls categories are additionally filtered by our internal log * level, so it should be set fairly high to capture all potentially * interesting events without overwhelming detail. */ int setup_gnutls_logger(char **categories); DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct MHD_Daemon*, MHD_stop_daemon, NULL); DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(struct MHD_Response*, MHD_destroy_response, NULL);
2,851
31.044944
87
h
null
systemd-main/src/journal/cat.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include <unistd.h> #include "sd-journal.h" #include "alloc-util.h" #include "build.h" #include "fd-util.h" #include "format-util.h" #include "main-func.h" #include "parse-argument.h" #include "parse-util.h" #include "pretty-print.h" #include "string-util.h" #include "syslog-util.h" #include "terminal-util.h" static const char *arg_identifier = NULL; static int arg_priority = LOG_INFO; static int arg_stderr_priority = -1; static bool arg_level_prefix = true; static int help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("systemd-cat", "1", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...] COMMAND ...\n" "\n%sExecute process with stdout/stderr connected to the journal.%s\n\n" " -h --help Show this help\n" " --version Show package version\n" " -t --identifier=STRING Set syslog identifier\n" " -p --priority=PRIORITY Set priority value (0..7)\n" " --stderr-priority=PRIORITY Set priority value (0..7) used for stderr\n" " --level-prefix=BOOL Control whether level prefix shall be parsed\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_VERSION = 0x100, ARG_STDERR_PRIORITY, ARG_LEVEL_PREFIX }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "identifier", required_argument, NULL, 't' }, { "priority", required_argument, NULL, 'p' }, { "stderr-priority", required_argument, NULL, ARG_STDERR_PRIORITY }, { "level-prefix", required_argument, NULL, ARG_LEVEL_PREFIX }, {} }; int c, r; assert(argc >= 0); assert(argv); /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long() * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */ optind = 0; while ((c = getopt_long(argc, argv, "+ht:p:", options, NULL)) >= 0) switch (c) { case 'h': help(); return 0; case ARG_VERSION: return version(); case 't': if (isempty(optarg)) arg_identifier = NULL; else arg_identifier = optarg; break; case 'p': arg_priority = log_level_from_string(optarg); if (arg_priority < 0) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse priority value."); break; case ARG_STDERR_PRIORITY: arg_stderr_priority = log_level_from_string(optarg); if (arg_stderr_priority < 0) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse stderr priority value."); break; case ARG_LEVEL_PREFIX: r = parse_boolean_argument("--level-prefix=", optarg, &arg_level_prefix); if (r < 0) return r; break; case '?': return -EINVAL; default: assert_not_reached(); } return 1; } static int run(int argc, char *argv[]) { _cleanup_close_ int outfd = -EBADF, errfd = -EBADF, saved_stderr = -EBADF; int r; log_setup(); r = parse_argv(argc, argv); if (r <= 0) return r; outfd = sd_journal_stream_fd(arg_identifier, arg_priority, arg_level_prefix); if (outfd < 0) return log_error_errno(outfd, "Failed to create stream fd: %m"); if (arg_stderr_priority >= 0 && arg_stderr_priority != arg_priority) { errfd = sd_journal_stream_fd(arg_identifier, arg_stderr_priority, arg_level_prefix); if (errfd < 0) return log_error_errno(errfd, "Failed to create stream fd: %m"); } saved_stderr = fcntl(STDERR_FILENO, F_DUPFD_CLOEXEC, 3); r = rearrange_stdio(STDIN_FILENO, outfd, errfd < 0 ? outfd : errfd); /* Invalidates fd on success + error! */ TAKE_FD(outfd); TAKE_FD(errfd); if (r < 0) return log_error_errno(r, "Failed to rearrange stdout/stderr: %m"); if (argc <= optind) (void) execl("/bin/cat", "/bin/cat", NULL); else { _cleanup_free_ char *s = NULL; struct stat st; if (fstat(STDERR_FILENO, &st) < 0) return log_error_errno(errno, "Failed to fstat(%s): %m", FORMAT_PROC_FD_PATH(STDERR_FILENO)); if (asprintf(&s, DEV_FMT ":" INO_FMT, (dev_t)st.st_dev, st.st_ino) < 0) return log_oom(); if (setenv("JOURNAL_STREAM", s, /* overwrite = */ true) < 0) return log_error_errno(errno, "Failed to set environment variable JOURNAL_STREAM: %m"); (void) execvp(argv[optind], argv + optind); } r = -errno; /* Let's try to restore a working stderr, so we can print the error message */ if (saved_stderr >= 0) (void) dup3(saved_stderr, STDERR_FILENO, 0); return log_error_errno(r, "Failed to execute process: %m"); } DEFINE_MAIN_FUNCTION(run);
6,595
34.462366
117
c
null
systemd-main/src/journal/fuzz-journald-kmsg.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "fuzz.h" #include "fuzz-journald.h" #include "journald-kmsg.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { Server s; if (size == 0) return 0; /* We don't want to fill the logs with assert warnings. * Disable most logging if not running standalone */ if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); dummy_server_init(&s, data, size); dev_kmsg_record(&s, s.buffer, size); server_done(&s); return 0; }
602
24.125
63
c
null
systemd-main/src/journal/fuzz-journald-native-fd.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "fd-util.h" #include "fs-util.h" #include "fuzz-journald.h" #include "fuzz.h" #include "journald-native.h" #include "memfd-util.h" #include "process-util.h" #include "tmpfile-util.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { Server s; _cleanup_close_ int sealed_fd = -EBADF, unsealed_fd = -EBADF; _cleanup_(unlink_tempfilep) char name[] = "/tmp/fuzz-journald-native-fd.XXXXXX"; char *label = NULL; size_t label_len = 0; struct ucred ucred; struct timeval *tv = NULL; if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); dummy_server_init(&s, NULL, 0); sealed_fd = memfd_new_and_seal(NULL, data, size); assert_se(sealed_fd >= 0); ucred = (struct ucred) { .pid = getpid_cached(), .uid = geteuid(), .gid = getegid(), }; server_process_native_file(&s, sealed_fd, &ucred, tv, label, label_len); unsealed_fd = mkostemp_safe(name); assert_se(unsealed_fd >= 0); assert_se(write(unsealed_fd, data, size) == (ssize_t) size); assert_se(lseek(unsealed_fd, 0, SEEK_SET) == 0); server_process_native_file(&s, unsealed_fd, &ucred, tv, label, label_len); server_done(&s); return 0; }
1,397
30.066667
88
c
null
systemd-main/src/journal/fuzz-journald-stream.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <linux/sockios.h> #include <sys/ioctl.h> #include <unistd.h> #include "fd-util.h" #include "fuzz.h" #include "fuzz-journald.h" #include "journald-stream.h" static int stream_fds[2] = PIPE_EBADF; int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { Server s; StdoutStream *stream; int v; if (outside_size_range(size, 1, 65536)) return 0; if (!getenv("SYSTEMD_LOG_LEVEL")) log_set_max_level(LOG_CRIT); assert_se(socketpair(AF_UNIX, SOCK_STREAM|SOCK_CLOEXEC|SOCK_NONBLOCK, 0, stream_fds) >= 0); dummy_server_init(&s, NULL, 0); assert_se(stdout_stream_install(&s, stream_fds[0], &stream) >= 0); assert_se(write(stream_fds[1], data, size) == (ssize_t) size); while (ioctl(stream_fds[0], SIOCINQ, &v) == 0 && v) sd_event_run(s.event, UINT64_MAX); if (s.n_stdout_streams) stdout_stream_destroy(stream); server_done(&s); stream_fds[1] = safe_close(stream_fds[1]); return 0; }
1,120
28.5
99
c
null
systemd-main/src/journal/journald-audit.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <malloc.h> #include "alloc-util.h" #include "audit-type.h" #include "errno-util.h" #include "fd-util.h" #include "hexdecoct.h" #include "io-util.h" #include "journal-internal.h" #include "journald-audit.h" #include "missing_audit.h" #include "string-util.h" typedef struct MapField { const char *audit_field; const char *journal_field; int (*map)(const char *field, const char **p, struct iovec *iovec, size_t *n); } MapField; static int map_simple_field( const char *field, const char **p, struct iovec *iovec, size_t *n) { _cleanup_free_ char *c = NULL; size_t l = 0; const char *e; assert(field); assert(p); assert(iovec); assert(n); l = strlen(field); c = malloc(l + 1); if (!c) return -ENOMEM; memcpy(c, field, l); for (e = *p; !IN_SET(*e, 0, ' '); e++) { if (!GREEDY_REALLOC(c, l+2)) return -ENOMEM; c[l++] = *e; } c[l] = 0; iovec[(*n)++] = IOVEC_MAKE(c, l); *p = e; c = NULL; return 1; } static int map_string_field_internal( const char *field, const char **p, struct iovec *iovec, size_t *n, bool filter_printable) { _cleanup_free_ char *c = NULL; const char *s, *e; size_t l; assert(field); assert(p); assert(iovec); assert(n); /* The kernel formats string fields in one of two formats. */ if (**p == '"') { /* Normal quoted syntax */ s = *p + 1; e = strchr(s, '"'); if (!e) return 0; l = strlen(field) + (e - s); c = malloc(l+1); if (!c) return -ENOMEM; *((char*) mempcpy(stpcpy(c, field), s, e - s)) = 0; e += 1; } else if (unhexchar(**p) >= 0) { /* Hexadecimal escaping */ l = strlen(field); c = malloc(l + 2); if (!c) return -ENOMEM; memcpy(c, field, l); for (e = *p; !IN_SET(*e, 0, ' '); e += 2) { int a, b; uint8_t x; a = unhexchar(e[0]); if (a < 0) return 0; b = unhexchar(e[1]); if (b < 0) return 0; x = ((uint8_t) a << 4 | (uint8_t) b); if (filter_printable && x < (uint8_t) ' ') x = (uint8_t) ' '; if (!GREEDY_REALLOC(c, l+2)) return -ENOMEM; c[l++] = (char) x; } c[l] = 0; } else return 0; iovec[(*n)++] = IOVEC_MAKE(c, l); *p = e; c = NULL; return 1; } static int map_string_field(const char *field, const char **p, struct iovec *iovec, size_t *n) { return map_string_field_internal(field, p, iovec, n, false); } static int map_string_field_printable(const char *field, const char **p, struct iovec *iovec, size_t *n) { return map_string_field_internal(field, p, iovec, n, true); } static int map_generic_field( const char *prefix, const char **p, struct iovec *iovec, size_t *n) { const char *e, *f; char *c, *t; int r; /* Implements fallback mappings for all fields we don't know */ for (e = *p; e < *p + 16; e++) { if (IN_SET(*e, 0, ' ')) return 0; if (*e == '=') break; if (!(ascii_isalpha(*e) || ascii_isdigit(*e) || IN_SET(*e, '_', '-'))) return 0; } if (e <= *p || e >= *p + 16) return 0; c = newa(char, strlen(prefix) + (e - *p) + 2); t = stpcpy(c, prefix); for (f = *p; f < e; f++) { char x; if (*f >= 'a' && *f <= 'z') x = (*f - 'a') + 'A'; /* uppercase */ else if (*f == '-') x = '_'; /* dashes → underscores */ else x = *f; *(t++) = x; } strcpy(t, "="); e++; r = map_simple_field(c, &e, iovec, n); if (r < 0) return r; *p = e; return r; } /* Kernel fields are those occurring in the audit string before * msg='. All of these fields are trusted, hence carry the "_" prefix. * We try to translate the fields we know into our native names. The * other's are generically mapped to _AUDIT_FIELD_XYZ= */ static const MapField map_fields_kernel[] = { /* First, we map certain well-known audit fields into native * well-known fields */ { "pid=", "_PID=", map_simple_field }, { "ppid=", "_PPID=", map_simple_field }, { "uid=", "_UID=", map_simple_field }, { "euid=", "_EUID=", map_simple_field }, { "fsuid=", "_FSUID=", map_simple_field }, { "gid=", "_GID=", map_simple_field }, { "egid=", "_EGID=", map_simple_field }, { "fsgid=", "_FSGID=", map_simple_field }, { "tty=", "_TTY=", map_simple_field }, { "ses=", "_AUDIT_SESSION=", map_simple_field }, { "auid=", "_AUDIT_LOGINUID=", map_simple_field }, { "subj=", "_SELINUX_CONTEXT=", map_simple_field }, { "comm=", "_COMM=", map_string_field }, { "exe=", "_EXE=", map_string_field }, { "proctitle=", "_CMDLINE=", map_string_field_printable }, /* Some fields don't map to native well-known fields. However, * we know that they are string fields, hence let's undo * string field escaping for them, though we stick to the * generic field names. */ { "path=", "_AUDIT_FIELD_PATH=", map_string_field }, { "dev=", "_AUDIT_FIELD_DEV=", map_string_field }, { "name=", "_AUDIT_FIELD_NAME=", map_string_field }, {} }; /* Userspace fields are those occurring in the audit string after * msg='. All of these fields are untrusted, hence carry no "_" * prefix. We map the fields we don't know to AUDIT_FIELD_XYZ= */ static const MapField map_fields_userspace[] = { { "cwd=", "AUDIT_FIELD_CWD=", map_string_field }, { "cmd=", "AUDIT_FIELD_CMD=", map_string_field }, { "acct=", "AUDIT_FIELD_ACCT=", map_string_field }, { "exe=", "AUDIT_FIELD_EXE=", map_string_field }, { "comm=", "AUDIT_FIELD_COMM=", map_string_field }, {} }; static int map_all_fields( const char *p, const MapField map_fields[], const char *prefix, bool handle_msg, struct iovec *iovec, size_t *n, size_t m) { int r; assert(p); assert(iovec); assert(n); for (;;) { bool mapped = false; const MapField *mf; const char *v; if (*n >= m) { log_debug( "More fields in audit message than audit field limit (%i), skipping remaining fields", N_IOVEC_AUDIT_FIELDS); return 0; } p += strspn(p, WHITESPACE); if (*p == 0) return 0; if (handle_msg) { v = startswith(p, "msg='"); if (v) { _cleanup_free_ char *c = NULL; const char *e; /* Userspace message. It's enclosed in simple quotation marks, is not escaped, but the last field in the line, hence let's remove the quotation mark, and apply the userspace mapping instead of the kernel mapping. */ e = endswith(v, "'"); if (!e) return 0; /* don't continue splitting up if the final quotation mark is missing */ c = strndup(v, e - v); if (!c) return -ENOMEM; return map_all_fields(c, map_fields_userspace, "AUDIT_FIELD_", false, iovec, n, m); } } /* Try to map the kernel fields to our own names */ for (mf = map_fields; mf->audit_field; mf++) { v = startswith(p, mf->audit_field); if (!v) continue; r = mf->map(mf->journal_field, &v, iovec, n); if (r < 0) return log_debug_errno(r, "Failed to parse audit array: %m"); if (r > 0) { mapped = true; p = v; break; } } if (!mapped) { r = map_generic_field(prefix, &p, iovec, n); if (r < 0) return log_debug_errno(r, "Failed to parse audit array: %m"); if (r == 0) /* Couldn't process as generic field, let's just skip over it */ p += strcspn(p, WHITESPACE); } } } void process_audit_string(Server *s, int type, const char *data, size_t size) { size_t n = 0, z; uint64_t seconds, msec, id; const char *p, *type_name; char id_field[sizeof("_AUDIT_ID=") + DECIMAL_STR_MAX(uint64_t)], type_field[sizeof("_AUDIT_TYPE=") + DECIMAL_STR_MAX(int)], source_time_field[sizeof("_SOURCE_REALTIME_TIMESTAMP=") + DECIMAL_STR_MAX(usec_t)]; struct iovec iovec[N_IOVEC_META_FIELDS + 8 + N_IOVEC_AUDIT_FIELDS]; char *m, *type_field_name; int k; assert(s); if (size <= 0) return; if (!data) return; /* Note that the input buffer is NUL terminated, but let's * check whether there is a spurious NUL byte */ if (memchr(data, 0, size)) return; p = startswith(data, "audit"); if (!p) return; k = 0; if (sscanf(p, "(%" PRIu64 ".%" PRIu64 ":%" PRIu64 "):%n", &seconds, &msec, &id, &k) != 3 || k == 0) return; p += k; p += strspn(p, WHITESPACE); if (isempty(p)) return; iovec[n++] = IOVEC_MAKE_STRING("_TRANSPORT=audit"); sprintf(source_time_field, "_SOURCE_REALTIME_TIMESTAMP=%" PRIu64, (usec_t) seconds * USEC_PER_SEC + (usec_t) msec * USEC_PER_MSEC); iovec[n++] = IOVEC_MAKE_STRING(source_time_field); sprintf(type_field, "_AUDIT_TYPE=%i", type); iovec[n++] = IOVEC_MAKE_STRING(type_field); sprintf(id_field, "_AUDIT_ID=%" PRIu64, id); iovec[n++] = IOVEC_MAKE_STRING(id_field); assert_cc(4 == LOG_FAC(LOG_AUTH)); iovec[n++] = IOVEC_MAKE_STRING("SYSLOG_FACILITY=4"); iovec[n++] = IOVEC_MAKE_STRING("SYSLOG_IDENTIFIER=audit"); type_name = audit_type_name_alloca(type); type_field_name = strjoina("_AUDIT_TYPE_NAME=", type_name); iovec[n++] = IOVEC_MAKE_STRING(type_field_name); m = strjoina("MESSAGE=", type_name, " ", p); iovec[n++] = IOVEC_MAKE_STRING(m); z = n; map_all_fields(p, map_fields_kernel, "_AUDIT_FIELD_", true, iovec, &n, n + N_IOVEC_AUDIT_FIELDS); server_dispatch_message(s, iovec, n, ELEMENTSOF(iovec), NULL, NULL, LOG_NOTICE, 0); /* free() all entries that map_all_fields() added. All others * are allocated on the stack or are constant. */ for (; z < n; z++) free(iovec[z].iov_base); } void server_process_audit_message( Server *s, const void *buffer, size_t buffer_size, const struct ucred *ucred, const union sockaddr_union *sa, socklen_t salen) { const struct nlmsghdr *nl = buffer; assert(s); if (buffer_size < ALIGN(sizeof(struct nlmsghdr))) return; assert(buffer); /* Filter out fake data */ if (!sa || salen != sizeof(struct sockaddr_nl) || sa->nl.nl_family != AF_NETLINK || sa->nl.nl_pid != 0) { log_debug("Audit netlink message from invalid sender."); return; } if (!ucred || ucred->pid != 0) { log_debug("Audit netlink message with invalid credentials."); return; } if (!NLMSG_OK(nl, buffer_size)) { log_ratelimit_error(JOURNAL_LOG_RATELIMIT, "Audit netlink message truncated."); return; } /* Ignore special Netlink messages */ if (IN_SET(nl->nlmsg_type, NLMSG_NOOP, NLMSG_ERROR)) return; /* Except AUDIT_USER, all messages below AUDIT_FIRST_USER_MSG are control messages, let's ignore those */ if (nl->nlmsg_type < AUDIT_FIRST_USER_MSG && nl->nlmsg_type != AUDIT_USER) return; process_audit_string(s, nl->nlmsg_type, NLMSG_DATA(nl), nl->nlmsg_len - ALIGN(sizeof(struct nlmsghdr))); } static int enable_audit(int fd, bool b) { struct { union { struct nlmsghdr header; uint8_t header_space[NLMSG_HDRLEN]; }; struct audit_status body; } _packed_ request = { .header.nlmsg_len = NLMSG_LENGTH(sizeof(struct audit_status)), .header.nlmsg_type = AUDIT_SET, .header.nlmsg_flags = NLM_F_REQUEST, .header.nlmsg_seq = 1, .header.nlmsg_pid = 0, .body.mask = AUDIT_STATUS_ENABLED, .body.enabled = b, }; union sockaddr_union sa = { .nl.nl_family = AF_NETLINK, .nl.nl_pid = 0, }; struct iovec iovec = { .iov_base = &request, .iov_len = NLMSG_LENGTH(sizeof(struct audit_status)), }; struct msghdr mh = { .msg_iov = &iovec, .msg_iovlen = 1, .msg_name = &sa.sa, .msg_namelen = sizeof(sa.nl), }; ssize_t n; n = sendmsg(fd, &mh, MSG_NOSIGNAL); if (n < 0) return -errno; if (n != NLMSG_LENGTH(sizeof(struct audit_status))) return -EIO; /* We don't wait for the result here, we can't do anything * about it anyway */ return 0; } int server_open_audit(Server *s) { int r; if (s->audit_fd < 0) { static const union sockaddr_union sa = { .nl.nl_family = AF_NETLINK, .nl.nl_pid = 0, .nl.nl_groups = AUDIT_NLGRP_READLOG, }; s->audit_fd = socket(AF_NETLINK, SOCK_RAW|SOCK_CLOEXEC|SOCK_NONBLOCK, NETLINK_AUDIT); if (s->audit_fd < 0) { if (ERRNO_IS_NOT_SUPPORTED(errno)) log_debug("Audit not supported in the kernel."); else log_warning_errno(errno, "Failed to create audit socket, ignoring: %m"); return 0; } if (bind(s->audit_fd, &sa.sa, sizeof(sa.nl)) < 0) { log_warning_errno(errno, "Failed to join audit multicast group. " "The kernel is probably too old or multicast reading is not supported. " "Ignoring: %m"); s->audit_fd = safe_close(s->audit_fd); return 0; } } else (void) fd_nonblock(s->audit_fd, true); r = setsockopt_int(s->audit_fd, SOL_SOCKET, SO_PASSCRED, true); if (r < 0) return log_error_errno(r, "Failed to set SO_PASSCRED on audit socket: %m"); r = sd_event_add_io(s->event, &s->audit_event_source, s->audit_fd, EPOLLIN, server_process_datagram, s); if (r < 0) return log_error_errno(r, "Failed to add audit fd to event loop: %m"); if (s->set_audit >= 0) { /* We are listening now, try to enable audit if configured so */ r = enable_audit(s->audit_fd, s->set_audit); if (r < 0) log_warning_errno(r, "Failed to issue audit enable call: %m"); else if (s->set_audit > 0) log_debug("Auditing in kernel turned on."); else log_debug("Auditing in kernel turned off."); } return 0; }
18,459
32.141831
122
c
null
systemd-main/src/journal/journald-console.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <sys/socket.h> #include <time.h> #include "alloc-util.h" #include "fd-util.h" #include "fileio.h" #include "format-util.h" #include "io-util.h" #include "journald-console.h" #include "journald-server.h" #include "parse-util.h" #include "process-util.h" #include "stdio-util.h" #include "terminal-util.h" static bool prefix_timestamp(void) { static int cached_printk_time = -1; if (_unlikely_(cached_printk_time < 0)) { _cleanup_free_ char *p = NULL; cached_printk_time = read_one_line_file("/sys/module/printk/parameters/time", &p) >= 0 && parse_boolean(p) > 0; } return cached_printk_time; } void server_forward_console( Server *s, int priority, const char *identifier, const char *message, const struct ucred *ucred) { struct iovec iovec[7]; struct timespec ts; char tbuf[STRLEN("[] ") + DECIMAL_STR_MAX(ts.tv_sec) + DECIMAL_STR_MAX(ts.tv_nsec)-3 + 1]; char header_pid[STRLEN("[]: ") + DECIMAL_STR_MAX(pid_t)]; _cleanup_free_ char *ident_buf = NULL; _cleanup_close_ int fd = -EBADF; const char *tty, *color_on = "", *color_off = ""; int n = 0; assert(s); assert(message); if (LOG_PRI(priority) > s->max_level_console) return; /* First: timestamp */ if (prefix_timestamp()) { assert_se(clock_gettime(CLOCK_MONOTONIC, &ts) == 0); xsprintf(tbuf, "[%5"PRI_TIME".%06"PRI_NSEC"] ", ts.tv_sec, (nsec_t)ts.tv_nsec / 1000); iovec[n++] = IOVEC_MAKE_STRING(tbuf); } /* Second: identifier and PID */ if (ucred) { if (!identifier) { (void) get_process_comm(ucred->pid, &ident_buf); identifier = ident_buf; } xsprintf(header_pid, "["PID_FMT"]: ", ucred->pid); if (identifier) iovec[n++] = IOVEC_MAKE_STRING(identifier); iovec[n++] = IOVEC_MAKE_STRING(header_pid); } else if (identifier) { iovec[n++] = IOVEC_MAKE_STRING(identifier); iovec[n++] = IOVEC_MAKE_STRING(": "); } get_log_colors(LOG_PRI(priority), &color_on, &color_off, NULL); /* Fourth: message */ iovec[n++] = IOVEC_MAKE_STRING(color_on); iovec[n++] = IOVEC_MAKE_STRING(message); iovec[n++] = IOVEC_MAKE_STRING(color_off); iovec[n++] = IOVEC_MAKE_STRING("\n"); tty = s->tty_path ?: "/dev/console"; /* Before you ask: yes, on purpose we open/close the console for each log line we write individually. This is a * good strategy to avoid journald getting killed by the kernel's SAK concept (it doesn't fix this entirely, * but minimizes the time window the kernel might end up killing journald due to SAK). It also makes things * easier for us so that we don't have to recover from hangups and suchlike triggered on the console. */ fd = open_terminal(tty, O_WRONLY|O_NOCTTY|O_CLOEXEC); if (fd < 0) { log_debug_errno(fd, "Failed to open %s for logging: %m", tty); return; } if (writev(fd, iovec, n) < 0) log_debug_errno(errno, "Failed to write to %s for logging: %m", tty); }
3,627
32.592593
119
c
null
systemd-main/src/journal/journald-context.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <inttypes.h> #include <sys/socket.h> #include <sys/types.h> #include "sd-id128.h" #include "set.h" #include "time-util.h" typedef struct ClientContext ClientContext; #include "journald-server.h" struct ClientContext { unsigned n_ref; unsigned lru_index; usec_t timestamp; bool in_lru; pid_t pid; uid_t uid; gid_t gid; char *comm; char *exe; char *cmdline; char *capeff; uint32_t auditid; uid_t loginuid; char *cgroup; char *session; uid_t owner_uid; char *unit; char *user_unit; char *slice; char *user_slice; sd_id128_t invocation_id; char *label; size_t label_size; int log_level_max; struct iovec *extra_fields_iovec; size_t extra_fields_n_iovec; void *extra_fields_data; nsec_t extra_fields_mtime; usec_t log_ratelimit_interval; unsigned log_ratelimit_burst; Set *log_filter_allowed_patterns; Set *log_filter_denied_patterns; }; int client_context_get( Server *s, pid_t pid, const struct ucred *ucred, const char *label, size_t label_len, const char *unit_id, ClientContext **ret); int client_context_acquire( Server *s, pid_t pid, const struct ucred *ucred, const char *label, size_t label_len, const char *unit_id, ClientContext **ret); ClientContext* client_context_release(Server *s, ClientContext *c); void client_context_maybe_refresh( Server *s, ClientContext *c, const struct ucred *ucred, const char *label, size_t label_size, const char *unit_id, usec_t tstamp); void client_context_acquire_default(Server *s); void client_context_flush_all(Server *s); void client_context_flush_regular(Server *s); static inline size_t client_context_extra_fields_n_iovec(const ClientContext *c) { return c ? c->extra_fields_n_iovec : 0; } static inline bool client_context_test_priority(const ClientContext *c, int priority) { if (!c) return true; if (c->log_level_max < 0) return true; return LOG_PRI(priority) <= c->log_level_max; }
2,540
22.747664
87
h
null
systemd-main/src/journal/journald-native.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "journald-server.h" void server_process_native_message( Server *s, const char *buffer, size_t buffer_size, const struct ucred *ucred, const struct timeval *tv, const char *label, size_t label_len); void server_process_native_file( Server *s, int fd, const struct ucred *ucred, const struct timeval *tv, const char *label, size_t label_len); int server_open_native_socket(Server *s, const char *native_socket);
693
27.916667
68
h
null
systemd-main/src/journal/journald-wall.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "format-util.h" #include "journald-server.h" #include "journald-wall.h" #include "process-util.h" #include "string-util.h" #include "utmp-wtmp.h" void server_forward_wall( Server *s, int priority, const char *identifier, const char *message, const struct ucred *ucred) { _cleanup_free_ char *ident_buf = NULL, *l_buf = NULL; const char *l; int r; assert(s); assert(message); if (LOG_PRI(priority) > s->max_level_wall) return; if (ucred) { if (!identifier) { (void) get_process_comm(ucred->pid, &ident_buf); identifier = ident_buf; } if (asprintf(&l_buf, "%s["PID_FMT"]: %s", strempty(identifier), ucred->pid, message) < 0) { log_oom(); return; } l = l_buf; } else if (identifier) { l = l_buf = strjoin(identifier, ": ", message); if (!l_buf) { log_oom(); return; } } else l = message; r = utmp_wall(l, "systemd-journald", NULL, NULL, NULL); if (r < 0) log_debug_errno(r, "Failed to send wall message: %m"); }
1,490
26.109091
107
c
null
systemd-main/src/journal/journald.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include "sd-daemon.h" #include "sd-messages.h" #include "format-util.h" #include "journal-authenticate.h" #include "journald-kmsg.h" #include "journald-server.h" #include "journald-syslog.h" #include "process-util.h" #include "sigbus.h" int main(int argc, char *argv[]) { const char *namespace; LogTarget log_target; Server server; int r; if (argc > 2) { log_error("This program takes one or no arguments."); return EXIT_FAILURE; } namespace = argc > 1 ? empty_to_null(argv[1]) : NULL; log_set_facility(LOG_SYSLOG); if (namespace) /* If we run for a log namespace, then we ourselves can log to the main journald. */ log_setup(); else { /* So here's the deal if we run as the main journald: we can't be considered as regular * daemon when it comes to logging hence LOG_TARGET_AUTO won't do the right thing for * us. Hence explicitly log to the console if we're started from a console or to kmsg * otherwise. */ log_target = isatty(STDERR_FILENO) > 0 ? LOG_TARGET_CONSOLE : LOG_TARGET_KMSG; log_set_prohibit_ipc(true); /* better safe than sorry */ log_set_target(log_target); log_parse_environment(); log_open(); } umask(0022); sigbus_install(); r = server_init(&server, namespace); if (r < 0) goto finish; server_vacuum(&server, false); server_flush_to_var(&server, true); server_flush_dev_kmsg(&server); if (server.namespace) log_debug("systemd-journald running as PID "PID_FMT" for namespace '%s'.", getpid_cached(), server.namespace); else log_debug("systemd-journald running as PID "PID_FMT" for the system.", getpid_cached()); server_driver_message(&server, 0, "MESSAGE_ID=" SD_MESSAGE_JOURNAL_START_STR, LOG_MESSAGE("Journal started"), NULL); /* Make sure to send the usage message *after* flushing the * journal so entries from the runtime journals are ordered * before this message. See #4190 for some details. */ server_space_usage_message(&server, NULL); for (;;) { usec_t t = USEC_INFINITY, n; r = sd_event_get_state(server.event); if (r < 0) { log_error_errno(r, "Failed to get event loop state: %m"); goto finish; } if (r == SD_EVENT_FINISHED) break; n = now(CLOCK_REALTIME); if (server.max_retention_usec > 0 && server.oldest_file_usec > 0) { /* The retention time is reached, so let's vacuum! */ if (server.oldest_file_usec + server.max_retention_usec < n) { log_info("Retention time reached, rotating."); server_rotate(&server); server_vacuum(&server, false); continue; } /* Calculate when to rotate the next time */ t = server.oldest_file_usec + server.max_retention_usec - n; } #if HAVE_GCRYPT if (server.system_journal) { usec_t u; if (journal_file_next_evolve_usec(server.system_journal->file, &u)) { if (n >= u) t = 0; else t = MIN(t, u - n); } } #endif r = sd_event_run(server.event, t); if (r < 0) { log_error_errno(r, "Failed to run event loop: %m"); goto finish; } server_maybe_append_tags(&server); server_maybe_warn_forward_syslog_missed(&server); } if (server.namespace) log_debug("systemd-journald stopped as PID "PID_FMT" for namespace '%s'.", getpid_cached(), server.namespace); else log_debug("systemd-journald stopped as PID "PID_FMT" for the system.", getpid_cached()); server_driver_message(&server, 0, "MESSAGE_ID=" SD_MESSAGE_JOURNAL_STOP_STR, LOG_MESSAGE("Journal stopped"), NULL); finish: server_done(&server); return r < 0 ? EXIT_FAILURE : EXIT_SUCCESS; }
4,948
34.604317
126
c
null
systemd-main/src/journal/managed-journal-file.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <pthread.h> #include <unistd.h> #include "chattr-util.h" #include "copy.h" #include "errno-util.h" #include "fd-util.h" #include "format-util.h" #include "journal-authenticate.h" #include "managed-journal-file.h" #include "path-util.h" #include "random-util.h" #include "set.h" #include "stat-util.h" #include "sync-util.h" #define PAYLOAD_BUFFER_SIZE (16U * 1024U) #define MINIMUM_HOLE_SIZE (1U * 1024U * 1024U / 2U) static int managed_journal_file_truncate(JournalFile *f) { uint64_t p; int r; /* truncate excess from the end of archives */ r = journal_file_tail_end_by_pread(f, &p); if (r < 0) return log_debug_errno(r, "Failed to determine end of tail object: %m"); /* arena_size can't exceed the file size, ensure it's updated before truncating */ f->header->arena_size = htole64(p - le64toh(f->header->header_size)); if (ftruncate(f->fd, p) < 0) return log_debug_errno(errno, "Failed to truncate %s: %m", f->path); return journal_file_fstat(f); } static int managed_journal_file_entry_array_punch_hole(JournalFile *f, uint64_t p, uint64_t n_entries) { Object o; uint64_t offset, sz, n_items = 0, n_unused; int r; if (n_entries == 0) return 0; for (uint64_t q = p; q != 0; q = le64toh(o.entry_array.next_entry_array_offset)) { r = journal_file_read_object_header(f, OBJECT_ENTRY_ARRAY, q, &o); if (r < 0) return r; n_items += journal_file_entry_array_n_items(f, &o); p = q; } if (p == 0) return 0; if (n_entries > n_items) return -EBADMSG; /* Amount of unused items in the final entry array. */ n_unused = n_items - n_entries; if (n_unused == 0) return 0; offset = p + offsetof(Object, entry_array.items) + (journal_file_entry_array_n_items(f, &o) - n_unused) * journal_file_entry_array_item_size(f); sz = p + le64toh(o.object.size) - offset; if (sz < MINIMUM_HOLE_SIZE) return 0; if (p == le64toh(f->header->tail_object_offset) && !JOURNAL_HEADER_SEALED(f->header)) { ssize_t n; o.object.size = htole64(offset - p); n = pwrite(f->fd, &o, sizeof(EntryArrayObject), p); if (n < 0) return log_debug_errno(errno, "Failed to modify entry array object size: %m"); if ((size_t) n != sizeof(EntryArrayObject)) return log_debug_errno(SYNTHETIC_ERRNO(EIO), "Short pwrite() while modifying entry array object size."); f->header->arena_size = htole64(ALIGN64(offset) - le64toh(f->header->header_size)); if (ftruncate(f->fd, ALIGN64(offset)) < 0) return log_debug_errno(errno, "Failed to truncate %s: %m", f->path); return 0; } if (fallocate(f->fd, FALLOC_FL_PUNCH_HOLE | FALLOC_FL_KEEP_SIZE, offset, sz) < 0) { if (ERRNO_IS_NOT_SUPPORTED(errno)) return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), /* Make recognizable */ "Hole punching not supported by backing file system, skipping."); return log_debug_errno(errno, "Failed to punch hole in entry array of %s: %m", f->path); } return 0; } static int managed_journal_file_punch_holes(JournalFile *f) { HashItem items[PAYLOAD_BUFFER_SIZE / sizeof(HashItem)]; uint64_t p, sz; ssize_t n = SSIZE_MAX; int r; r = managed_journal_file_entry_array_punch_hole( f, le64toh(f->header->entry_array_offset), le64toh(f->header->n_entries)); if (r < 0) return r; p = le64toh(f->header->data_hash_table_offset); sz = le64toh(f->header->data_hash_table_size); for (uint64_t i = p; i < p + sz && n > 0; i += n) { size_t m = MIN(sizeof(items), p + sz - i); n = pread(f->fd, items, m, i); if (n < 0) return log_debug_errno(errno, "Failed to read hash table items: %m"); /* Let's ignore any partial hash items by rounding down to the nearest multiple of HashItem. */ n -= n % sizeof(HashItem); for (size_t j = 0; j < (size_t) n / sizeof(HashItem); j++) { Object o; for (uint64_t q = le64toh(items[j].head_hash_offset); q != 0; q = le64toh(o.data.next_hash_offset)) { r = journal_file_read_object_header(f, OBJECT_DATA, q, &o); if (r < 0) { log_debug_errno(r, "Invalid data object: %m, ignoring"); break; } if (le64toh(o.data.n_entries) == 0) continue; r = managed_journal_file_entry_array_punch_hole( f, le64toh(o.data.entry_array_offset), le64toh(o.data.n_entries) - 1); if (r == -EOPNOTSUPP) return -EOPNOTSUPP; /* Ignore other errors */ } } } return 0; } /* This may be called from a separate thread to prevent blocking the caller for the duration of fsync(). * As a result we use atomic operations on f->offline_state for inter-thread communications with * journal_file_set_offline() and journal_file_set_online(). */ static void managed_journal_file_set_offline_internal(ManagedJournalFile *f) { int r; assert(f); assert(f->file->fd >= 0); assert(f->file->header); for (;;) { switch (f->file->offline_state) { case OFFLINE_CANCEL: { OfflineState tmp_state = OFFLINE_CANCEL; if (!__atomic_compare_exchange_n(&f->file->offline_state, &tmp_state, OFFLINE_DONE, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) continue; } return; case OFFLINE_AGAIN_FROM_SYNCING: { OfflineState tmp_state = OFFLINE_AGAIN_FROM_SYNCING; if (!__atomic_compare_exchange_n(&f->file->offline_state, &tmp_state, OFFLINE_SYNCING, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) continue; } break; case OFFLINE_AGAIN_FROM_OFFLINING: { OfflineState tmp_state = OFFLINE_AGAIN_FROM_OFFLINING; if (!__atomic_compare_exchange_n(&f->file->offline_state, &tmp_state, OFFLINE_SYNCING, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) continue; } break; case OFFLINE_SYNCING: if (f->file->archive) { (void) managed_journal_file_truncate(f->file); (void) managed_journal_file_punch_holes(f->file); } (void) fsync(f->file->fd); { OfflineState tmp_state = OFFLINE_SYNCING; if (!__atomic_compare_exchange_n(&f->file->offline_state, &tmp_state, OFFLINE_OFFLINING, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) continue; } f->file->header->state = f->file->archive ? STATE_ARCHIVED : STATE_OFFLINE; (void) fsync(f->file->fd); /* If we've archived the journal file, first try to re-enable COW on the file. If the * FS_NOCOW_FL flag was never set or we successfully removed it, continue. If we fail * to remove the flag on the archived file, rewrite the file without the NOCOW flag. * We need this fallback because on some filesystems (BTRFS), the NOCOW flag cannot * be removed after data has been written to a file. The only way to remove it is to * copy all data to a new file without the NOCOW flag set. */ if (f->file->archive) { r = chattr_fd(f->file->fd, 0, FS_NOCOW_FL, NULL); if (r >= 0) continue; log_debug_errno(r, "Failed to re-enable copy-on-write for %s: %m, rewriting file", f->file->path); r = copy_file_atomic_full(FORMAT_PROC_FD_PATH(f->file->fd), f->file->path, f->file->mode, 0, FS_NOCOW_FL, COPY_REPLACE | COPY_FSYNC | COPY_HOLES | COPY_ALL_XATTRS, NULL, NULL); if (r < 0) { log_debug_errno(r, "Failed to rewrite %s: %m", f->file->path); continue; } } break; case OFFLINE_OFFLINING: { OfflineState tmp_state = OFFLINE_OFFLINING; if (!__atomic_compare_exchange_n(&f->file->offline_state, &tmp_state, OFFLINE_DONE, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) continue; } _fallthrough_; case OFFLINE_DONE: return; case OFFLINE_JOINED: log_debug("OFFLINE_JOINED unexpected offline state for journal_file_set_offline_internal()"); return; } } } static void * managed_journal_file_set_offline_thread(void *arg) { ManagedJournalFile *f = arg; (void) pthread_setname_np(pthread_self(), "journal-offline"); managed_journal_file_set_offline_internal(f); return NULL; } /* Trigger a restart if the offline thread is mid-flight in a restartable state. */ static bool managed_journal_file_set_offline_try_restart(ManagedJournalFile *f) { for (;;) { switch (f->file->offline_state) { case OFFLINE_AGAIN_FROM_SYNCING: case OFFLINE_AGAIN_FROM_OFFLINING: return true; case OFFLINE_CANCEL: { OfflineState tmp_state = OFFLINE_CANCEL; if (!__atomic_compare_exchange_n(&f->file->offline_state, &tmp_state, OFFLINE_AGAIN_FROM_SYNCING, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) continue; } return true; case OFFLINE_SYNCING: { OfflineState tmp_state = OFFLINE_SYNCING; if (!__atomic_compare_exchange_n(&f->file->offline_state, &tmp_state, OFFLINE_AGAIN_FROM_SYNCING, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) continue; } return true; case OFFLINE_OFFLINING: { OfflineState tmp_state = OFFLINE_OFFLINING; if (!__atomic_compare_exchange_n(&f->file->offline_state, &tmp_state, OFFLINE_AGAIN_FROM_OFFLINING, false, __ATOMIC_SEQ_CST, __ATOMIC_SEQ_CST)) continue; } return true; default: return false; } } } /* Sets a journal offline. * * If wait is false then an offline is dispatched in a separate thread for a * subsequent journal_file_set_offline() or journal_file_set_online() of the * same journal to synchronize with. * * If wait is true, then either an existing offline thread will be restarted * and joined, or if none exists the offline is simply performed in this * context without involving another thread. */ int managed_journal_file_set_offline(ManagedJournalFile *f, bool wait) { int target_state; bool restarted; int r; assert(f); if (!journal_file_writable(f->file)) return -EPERM; if (f->file->fd < 0 || !f->file->header) return -EINVAL; target_state = f->file->archive ? STATE_ARCHIVED : STATE_OFFLINE; /* An offlining journal is implicitly online and may modify f->header->state, * we must also join any potentially lingering offline thread when already in * the desired offline state. */ if (!managed_journal_file_is_offlining(f) && f->file->header->state == target_state) return journal_file_set_offline_thread_join(f->file); /* Restart an in-flight offline thread and wait if needed, or join a lingering done one. */ restarted = managed_journal_file_set_offline_try_restart(f); if ((restarted && wait) || !restarted) { r = journal_file_set_offline_thread_join(f->file); if (r < 0) return r; } if (restarted) return 0; /* Initiate a new offline. */ f->file->offline_state = OFFLINE_SYNCING; if (wait) /* Without using a thread if waiting. */ managed_journal_file_set_offline_internal(f); else { sigset_t ss, saved_ss; int k; assert_se(sigfillset(&ss) >= 0); /* Don't block SIGBUS since the offlining thread accesses a memory mapped file. * Asynchronous SIGBUS signals can safely be handled by either thread. */ assert_se(sigdelset(&ss, SIGBUS) >= 0); r = pthread_sigmask(SIG_BLOCK, &ss, &saved_ss); if (r > 0) return -r; r = pthread_create(&f->file->offline_thread, NULL, managed_journal_file_set_offline_thread, f); k = pthread_sigmask(SIG_SETMASK, &saved_ss, NULL); if (r > 0) { f->file->offline_state = OFFLINE_JOINED; return -r; } if (k > 0) return -k; } return 0; } bool managed_journal_file_is_offlining(ManagedJournalFile *f) { assert(f); __atomic_thread_fence(__ATOMIC_SEQ_CST); if (IN_SET(f->file->offline_state, OFFLINE_DONE, OFFLINE_JOINED)) return false; return true; } ManagedJournalFile* managed_journal_file_close(ManagedJournalFile *f) { if (!f) return NULL; #if HAVE_GCRYPT /* Write the final tag */ if (JOURNAL_HEADER_SEALED(f->file->header) && journal_file_writable(f->file)) { int r; r = journal_file_append_tag(f->file); if (r < 0) log_error_errno(r, "Failed to append tag when closing journal: %m"); } #endif if (sd_event_source_get_enabled(f->file->post_change_timer, NULL) > 0) journal_file_post_change(f->file); sd_event_source_disable_unref(f->file->post_change_timer); managed_journal_file_set_offline(f, true); journal_file_close(f->file); return mfree(f); } int managed_journal_file_open( int fd, const char *fname, int open_flags, JournalFileFlags file_flags, mode_t mode, uint64_t compress_threshold_bytes, JournalMetrics *metrics, MMapCache *mmap_cache, Set *deferred_closes, ManagedJournalFile *template, ManagedJournalFile **ret) { _cleanup_free_ ManagedJournalFile *f = NULL; int r; set_clear_with_destructor(deferred_closes, managed_journal_file_close); f = new0(ManagedJournalFile, 1); if (!f) return -ENOMEM; r = journal_file_open( fd, fname, open_flags, file_flags, mode, compress_threshold_bytes, metrics, mmap_cache, template ? template->file : NULL, &f->file); if (r < 0) return r; *ret = TAKE_PTR(f); return 0; } ManagedJournalFile* managed_journal_file_initiate_close(ManagedJournalFile *f, Set *deferred_closes) { int r; assert(f); if (deferred_closes) { r = set_put(deferred_closes, f); if (r < 0) log_debug_errno(r, "Failed to add file to deferred close set, closing immediately."); else { (void) managed_journal_file_set_offline(f, false); return NULL; } } return managed_journal_file_close(f); } int managed_journal_file_rotate( ManagedJournalFile **f, MMapCache *mmap_cache, JournalFileFlags file_flags, uint64_t compress_threshold_bytes, Set *deferred_closes) { _cleanup_free_ char *path = NULL; ManagedJournalFile *new_file = NULL; int r; assert(f); assert(*f); r = journal_file_archive((*f)->file, &path); if (r < 0) return r; r = managed_journal_file_open( /* fd= */ -1, path, (*f)->file->open_flags, file_flags, (*f)->file->mode, compress_threshold_bytes, /* metrics= */ NULL, mmap_cache, deferred_closes, /* template= */ *f, &new_file); managed_journal_file_initiate_close(*f, deferred_closes); *f = new_file; return r; } int managed_journal_file_open_reliably( const char *fname, int open_flags, JournalFileFlags file_flags, mode_t mode, uint64_t compress_threshold_bytes, JournalMetrics *metrics, MMapCache *mmap_cache, Set *deferred_closes, ManagedJournalFile *template, ManagedJournalFile **ret) { _cleanup_(managed_journal_file_closep) ManagedJournalFile *old_file = NULL; int r; r = managed_journal_file_open( /* fd= */ -1, fname, open_flags, file_flags, mode, compress_threshold_bytes, metrics, mmap_cache, deferred_closes, template, ret); if (!IN_SET(r, -EBADMSG, /* Corrupted */ -EADDRNOTAVAIL, /* Referenced object offset out of bounds */ -ENODATA, /* Truncated */ -EHOSTDOWN, /* Other machine */ -EPROTONOSUPPORT, /* Incompatible feature */ -EBUSY, /* Unclean shutdown */ -ESHUTDOWN, /* Already archived */ -EIO, /* IO error, including SIGBUS on mmap */ -EIDRM)) /* File has been deleted */ return r; if ((open_flags & O_ACCMODE) == O_RDONLY) return r; if (!(open_flags & O_CREAT)) return r; if (!endswith(fname, ".journal")) return r; /* The file is corrupted. Rotate it away and try it again (but only once) */ log_warning_errno(r, "File %s corrupted or uncleanly shut down, renaming and replacing.", fname); if (!template) { /* The file is corrupted and no template is specified. Try opening it read-only as the * template before rotating to inherit its sequence number and ID. */ r = managed_journal_file_open(-1, fname, (open_flags & ~(O_ACCMODE|O_CREAT|O_EXCL)) | O_RDONLY, file_flags, 0, compress_threshold_bytes, NULL, mmap_cache, deferred_closes, NULL, &old_file); if (r < 0) log_debug_errno(r, "Failed to continue sequence from file %s, ignoring: %m", fname); else template = old_file; } r = journal_file_dispose(AT_FDCWD, fname); if (r < 0) return r; return managed_journal_file_open(-1, fname, open_flags, file_flags, mode, compress_threshold_bytes, metrics, mmap_cache, deferred_closes, template, ret); }
22,618
37.864261
130
c
null
systemd-main/src/journal/test-journal-append.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <getopt.h> #include <stdio.h> #include <unistd.h> #include "chattr-util.h" #include "fd-util.h" #include "fs-util.h" #include "io-util.h" #include "log.h" #include "managed-journal-file.h" #include "mmap-cache.h" #include "parse-util.h" #include "random-util.h" #include "rm-rf.h" #include "strv.h" #include "terminal-util.h" #include "tests.h" #include "tmpfile-util.h" static int journal_append_message(ManagedJournalFile *mj, const char *message) { struct iovec iovec; struct dual_timestamp ts; assert(mj); assert(message); dual_timestamp_get(&ts); iovec = IOVEC_MAKE_STRING(message); return journal_file_append_entry( mj->file, &ts, /* boot_id= */ NULL, &iovec, /* n_iovec= */ 1, /* seqnum= */ NULL, /* seqnum_id= */ NULL, /* ret_object= */ NULL, /* ret_offset= */ NULL); } static int journal_corrupt_and_append(uint64_t start_offset, uint64_t step) { _cleanup_(mmap_cache_unrefp) MMapCache *mmap_cache = NULL; _cleanup_(rm_rf_physical_and_freep) char *tempdir = NULL; _cleanup_(managed_journal_file_closep) ManagedJournalFile *mj = NULL; uint64_t start, end; int r; mmap_cache = mmap_cache_new(); assert_se(mmap_cache); /* managed_journal_file_open() requires a valid machine id */ if (sd_id128_get_machine(NULL) < 0) return log_tests_skipped("No valid machine ID found"); assert_se(mkdtemp_malloc("/tmp/journal-append-XXXXXX", &tempdir) >= 0); assert_se(chdir(tempdir) >= 0); (void) chattr_path(tempdir, FS_NOCOW_FL, FS_NOCOW_FL, NULL); log_debug("Opening journal %s/system.journal", tempdir); r = managed_journal_file_open( /* fd= */ -1, "system.journal", O_RDWR|O_CREAT, JOURNAL_COMPRESS, 0644, /* compress_threshold_bytes= */ UINT64_MAX, /* metrics= */ NULL, mmap_cache, /* deferred_closes= */ NULL, /* template= */ NULL, &mj); if (r < 0) return log_error_errno(r, "Failed to open the journal: %m"); assert_se(mj); assert_se(mj->file); /* Add a couple of initial messages */ for (int i = 0; i < 10; i++) { _cleanup_free_ char *message = NULL; assert_se(asprintf(&message, "MESSAGE=Initial message %d", i) >= 0); r = journal_append_message(mj, message); if (r < 0) return log_error_errno(r, "Failed to write to the journal: %m"); } start = start_offset == UINT64_MAX ? random_u64() % mj->file->last_stat.st_size : start_offset; end = (uint64_t) mj->file->last_stat.st_size; /* Print the initial offset at which we start flipping bits, which can be * later used to reproduce a potential fail */ log_info("Start offset: %" PRIu64 ", corrupt-step: %" PRIu64, start, step); fflush(stdout); if (start >= end) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Start offset >= journal size, can't continue"); for (uint64_t offset = start; offset < end; offset += step) { _cleanup_free_ char *message = NULL; uint8_t b; /* Flip a bit in the journal file */ r = pread(mj->file->fd, &b, 1, offset); assert_se(r == 1); b |= 0x1; r = pwrite(mj->file->fd, &b, 1, offset); assert_se(r == 1); /* Close and reopen the journal to flush all caches and remap * the corrupted journal */ mj = managed_journal_file_close(mj); r = managed_journal_file_open( /* fd= */ -1, "system.journal", O_RDWR|O_CREAT, JOURNAL_COMPRESS, 0644, /* compress_threshold_bytes= */ UINT64_MAX, /* metrics= */ NULL, mmap_cache, /* deferred_closes= */ NULL, /* template= */ NULL, &mj); if (r < 0) { /* The corrupted journal might get rejected during reopening * if it's corrupted enough (especially its header), so * treat this as a success if it doesn't crash */ log_info_errno(r, "Failed to reopen the journal: %m"); break; } /* Try to write something to the (possibly corrupted) journal */ assert_se(asprintf(&message, "MESSAGE=Hello world %" PRIu64, offset) >= 0); r = journal_append_message(mj, message); if (r < 0) { /* We care only about crashes or sanitizer errors, * failed write without any crash is a success */ log_info_errno(r, "Failed to write to the journal: %m"); break; } } return 0; } int main(int argc, char *argv[]) { uint64_t start_offset = UINT64_MAX; uint64_t iterations = 100; uint64_t iteration_step = 1; uint64_t corrupt_step = 31; bool sequential = false, run_one = false; int c, r; test_setup_logging(LOG_DEBUG); enum { ARG_START_OFFSET = 0x1000, ARG_ITERATIONS, ARG_ITERATION_STEP, ARG_CORRUPT_STEP, ARG_SEQUENTIAL, ARG_RUN_ONE, }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "start-offset", required_argument, NULL, ARG_START_OFFSET }, { "iterations", required_argument, NULL, ARG_ITERATIONS }, { "iteration-step", required_argument, NULL, ARG_ITERATION_STEP }, { "corrupt-step", required_argument, NULL, ARG_CORRUPT_STEP }, { "sequential", no_argument, NULL, ARG_SEQUENTIAL }, { "run-one", required_argument, NULL, ARG_RUN_ONE }, {} }; assert_se(argc >= 0); assert_se(argv); while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': printf("Syntax:\n" " %s [OPTION...]\n" "Options:\n" " --start-offset=OFFSET Offset at which to start corrupting the journal\n" " (default: random offset is picked, unless\n" " --sequential is used - in that case we use 0 + iteration)\n" " --iterations=ITER Number of iterations to perform before exiting\n" " (default: 100)\n" " --iteration-step=STEP Iteration step (default: 1)\n" " --corrupt-step=STEP Corrupt every n-th byte starting from OFFSET (default: 31)\n" " --sequential Go through offsets sequentially instead of picking\n" " a random one on each iteration. If set, we go through\n" " offsets <0; ITER), or <OFFSET, ITER) if --start-offset=\n" " is set (default: false)\n" " --run-one=OFFSET Single shot mode for reproducing issues. Takes the same\n" " offset as --start-offset= and does only one iteration\n" , program_invocation_short_name); return 0; case ARG_START_OFFSET: r = safe_atou64(optarg, &start_offset); if (r < 0) return log_error_errno(r, "Invalid starting offset: %m"); break; case ARG_ITERATIONS: r = safe_atou64(optarg, &iterations); if (r < 0) return log_error_errno(r, "Invalid value for iterations: %m"); break; case ARG_CORRUPT_STEP: r = safe_atou64(optarg, &corrupt_step); if (r < 0) return log_error_errno(r, "Invalid value for corrupt-step: %m"); break; case ARG_ITERATION_STEP: r = safe_atou64(optarg, &iteration_step); if (r < 0) return log_error_errno(r, "Invalid value for iteration-step: %m"); break; case ARG_SEQUENTIAL: sequential = true; break; case ARG_RUN_ONE: r = safe_atou64(optarg, &start_offset); if (r < 0) return log_error_errno(r, "Invalid offset: %m"); run_one = true; break; case '?': return -EINVAL; default: assert_not_reached(); } if (run_one) /* Reproducer mode */ return journal_corrupt_and_append(start_offset, corrupt_step); for (uint64_t i = 0; i < iterations; i++) { uint64_t offset = UINT64_MAX; log_info("Iteration #%" PRIu64 ", step: %" PRIu64, i, iteration_step); if (sequential) offset = (start_offset == UINT64_MAX ? 0 : start_offset) + i * iteration_step; r = journal_corrupt_and_append(offset, corrupt_step); if (r < 0) return EXIT_FAILURE; if (r > 0) /* Reached the end of the journal file */ break; } return EXIT_SUCCESS; }
11,513
41.175824
121
c
null
systemd-main/src/journal/test-journal-config.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdbool.h> #include "journald-server.h" #include "tests.h" #define _COMPRESS_PARSE_CHECK(str, enab, thresh, varname) \ do { \ JournalCompressOptions varname = {true, 111}; \ config_parse_compress("", "", 0, "", 0, "", 0, str, \ &varname, NULL); \ assert_se((enab) == varname.enabled); \ if (varname.enabled) \ assert_se((thresh) == varname.threshold_bytes); \ } while (0) #define COMPRESS_PARSE_CHECK(str, enabled, threshold) \ _COMPRESS_PARSE_CHECK(str, enabled, threshold, conf##__COUNTER__) TEST(config_compress) { COMPRESS_PARSE_CHECK("yes", true, 111); COMPRESS_PARSE_CHECK("no", false, 111); COMPRESS_PARSE_CHECK("y", true, 111); COMPRESS_PARSE_CHECK("n", false, 111); COMPRESS_PARSE_CHECK("true", true, 111); COMPRESS_PARSE_CHECK("false", false, 111); COMPRESS_PARSE_CHECK("t", true, 111); COMPRESS_PARSE_CHECK("f", false, 111); COMPRESS_PARSE_CHECK("on", true, 111); COMPRESS_PARSE_CHECK("off", false, 111); /* Weird size/bool overlapping case. We preserve backward compatibility instead of assuming these are byte * counts. */ COMPRESS_PARSE_CHECK("1", true, 111); COMPRESS_PARSE_CHECK("0", false, 111); /* IEC sizing */ COMPRESS_PARSE_CHECK("1B", true, 1); COMPRESS_PARSE_CHECK("1K", true, 1024); COMPRESS_PARSE_CHECK("1M", true, 1024 * 1024); COMPRESS_PARSE_CHECK("1G", true, 1024 * 1024 * 1024); /* Invalid Case */ COMPRESS_PARSE_CHECK("-1", true, 111); COMPRESS_PARSE_CHECK("blah blah", true, 111); COMPRESS_PARSE_CHECK("", true, UINT64_MAX); } DEFINE_TEST_MAIN(LOG_INFO);
2,064
39.490196
114
c
null
systemd-main/src/journal/test-journal-flush.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <unistd.h> #include "sd-journal.h" #include "alloc-util.h" #include "chattr-util.h" #include "journal-internal.h" #include "macro.h" #include "managed-journal-file.h" #include "path-util.h" #include "rm-rf.h" #include "string-util.h" #include "tmpfile-util.h" static void test_journal_flush(int argc, char *argv[]) { _cleanup_(mmap_cache_unrefp) MMapCache *m = NULL; _cleanup_free_ char *fn = NULL; _cleanup_(rm_rf_physical_and_freep) char *dn = NULL; ManagedJournalFile *new_journal = NULL; sd_journal *j = NULL; unsigned n = 0; int r; assert_se(m = mmap_cache_new()); assert_se(mkdtemp_malloc("/var/tmp/test-journal-flush.XXXXXX", &dn) >= 0); (void) chattr_path(dn, FS_NOCOW_FL, FS_NOCOW_FL, NULL); assert_se(fn = path_join(dn, "test.journal")); r = managed_journal_file_open(-1, fn, O_CREAT|O_RDWR, 0, 0644, 0, NULL, m, NULL, NULL, &new_journal); assert_se(r >= 0); if (argc > 1) r = sd_journal_open_files(&j, (const char **) strv_skip(argv, 1), 0); else r = sd_journal_open(&j, 0); assert_se(r == 0); sd_journal_set_data_threshold(j, 0); SD_JOURNAL_FOREACH(j) { Object *o; JournalFile *f; f = j->current_file; assert_se(f && f->current_offset > 0); r = journal_file_move_to_object(f, OBJECT_ENTRY, f->current_offset, &o); if (r < 0) log_error_errno(r, "journal_file_move_to_object failed: %m"); assert_se(r >= 0); r = journal_file_copy_entry(f, new_journal->file, o, f->current_offset, NULL, NULL); if (r < 0) log_warning_errno(r, "journal_file_copy_entry failed: %m"); assert_se(r >= 0 || IN_SET(r, -EBADMSG, /* corrupted file */ -EPROTONOSUPPORT, /* unsupported compression */ -EIO, /* file rotated */ -EREMCHG)); /* clock rollback */ if (++n >= 10000) break; } sd_journal_close(j); (void) managed_journal_file_close(new_journal); } int main(int argc, char *argv[]) { assert_se(setenv("SYSTEMD_JOURNAL_COMPACT", "0", 1) >= 0); test_journal_flush(argc, argv); assert_se(setenv("SYSTEMD_JOURNAL_COMPACT", "1", 1) >= 0); test_journal_flush(argc, argv); return 0; }
2,712
31.686747
109
c
null
systemd-main/src/journal/test-journal-interleaving.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <unistd.h> #include "sd-id128.h" #include "sd-journal.h" #include "alloc-util.h" #include "chattr-util.h" #include "io-util.h" #include "journal-vacuum.h" #include "log.h" #include "managed-journal-file.h" #include "parse-util.h" #include "rm-rf.h" #include "tests.h" /* This program tests skipping around in a multi-file journal. */ static bool arg_keep = false; _noreturn_ static void log_assert_errno(const char *text, int error, const char *file, unsigned line, const char *func) { log_internal(LOG_CRIT, error, file, line, func, "'%s' failed at %s:%u (%s): %m", text, file, line, func); abort(); } #define assert_ret(expr) \ do { \ int _r_ = (expr); \ if (_unlikely_(_r_ < 0)) \ log_assert_errno(#expr, -_r_, PROJECT_FILE, __LINE__, __func__); \ } while (false) static ManagedJournalFile *test_open(const char *name) { _cleanup_(mmap_cache_unrefp) MMapCache *m = NULL; ManagedJournalFile *f; m = mmap_cache_new(); assert_se(m != NULL); assert_ret(managed_journal_file_open(-1, name, O_RDWR|O_CREAT, JOURNAL_COMPRESS, 0644, UINT64_MAX, NULL, m, NULL, NULL, &f)); return f; } static void test_close(ManagedJournalFile *f) { (void) managed_journal_file_close(f); } static void append_number(ManagedJournalFile *f, int n, uint64_t *seqnum) { char *p; dual_timestamp ts; static dual_timestamp previous_ts = {}; struct iovec iovec[1]; dual_timestamp_get(&ts); if (ts.monotonic <= previous_ts.monotonic) ts.monotonic = previous_ts.monotonic + 1; if (ts.realtime <= previous_ts.realtime) ts.realtime = previous_ts.realtime + 1; previous_ts = ts; assert_se(asprintf(&p, "NUMBER=%d", n) >= 0); iovec[0] = IOVEC_MAKE_STRING(p); assert_ret(journal_file_append_entry(f->file, &ts, NULL, iovec, 1, seqnum, NULL, NULL, NULL)); free(p); } static void test_check_number(sd_journal *j, int n) { const void *d; _cleanup_free_ char *k = NULL; size_t l; int x; assert_ret(sd_journal_get_data(j, "NUMBER", &d, &l)); assert_se(k = strndup(d, l)); printf("%s (expected=%i)\n", k, n); assert_se(safe_atoi(k + STRLEN("NUMBER="), &x) >= 0); assert_se(n == x); } static void test_check_numbers_down(sd_journal *j, int count) { int i; for (i = 1; i <= count; i++) { int r; test_check_number(j, i); assert_ret(r = sd_journal_next(j)); if (i == count) assert_se(r == 0); else assert_se(r == 1); } } static void test_check_numbers_up(sd_journal *j, int count) { for (int i = count; i >= 1; i--) { int r; test_check_number(j, i); assert_ret(r = sd_journal_previous(j)); if (i == 1) assert_se(r == 0); else assert_se(r == 1); } } static void setup_sequential(void) { ManagedJournalFile *f1, *f2, *f3; f1 = test_open("one.journal"); f2 = test_open("two.journal"); f3 = test_open("three.journal"); append_number(f1, 1, NULL); append_number(f1, 2, NULL); append_number(f1, 3, NULL); append_number(f2, 4, NULL); append_number(f2, 5, NULL); append_number(f2, 6, NULL); append_number(f3, 7, NULL); append_number(f3, 8, NULL); append_number(f3, 9, NULL); test_close(f1); test_close(f2); test_close(f3); } static void setup_interleaved(void) { ManagedJournalFile *f1, *f2, *f3; f1 = test_open("one.journal"); f2 = test_open("two.journal"); f3 = test_open("three.journal"); append_number(f1, 1, NULL); append_number(f2, 2, NULL); append_number(f3, 3, NULL); append_number(f1, 4, NULL); append_number(f2, 5, NULL); append_number(f3, 6, NULL); append_number(f1, 7, NULL); append_number(f2, 8, NULL); append_number(f3, 9, NULL); test_close(f1); test_close(f2); test_close(f3); } static void mkdtemp_chdir_chattr(char *path) { assert_se(mkdtemp(path)); assert_se(chdir(path) >= 0); /* Speed up things a bit on btrfs, ensuring that CoW is turned off for all files created in our * directory during the test run */ (void) chattr_path(path, FS_NOCOW_FL, FS_NOCOW_FL, NULL); } static void test_skip_one(void (*setup)(void)) { char t[] = "/var/tmp/journal-skip-XXXXXX"; sd_journal *j; int r; mkdtemp_chdir_chattr(t); setup(); /* Seek to head, iterate down. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_head(j)); assert_ret(sd_journal_next(j)); /* pointing the first entry */ test_check_numbers_down(j, 9); sd_journal_close(j); /* Seek to head, iterate down. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_head(j)); assert_ret(sd_journal_next(j)); /* pointing the first entry */ assert_ret(sd_journal_previous(j)); /* no-op */ test_check_numbers_down(j, 9); sd_journal_close(j); /* Seek to head, move to previous, then iterate down. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_head(j)); assert_ret(sd_journal_previous(j)); /* no-op */ assert_ret(sd_journal_next(j)); /* pointing the first entry */ test_check_numbers_down(j, 9); sd_journal_close(j); /* Seek to head, walk several steps, then iterate down. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_head(j)); assert_ret(sd_journal_previous(j)); /* no-op */ assert_ret(sd_journal_previous(j)); /* no-op */ assert_ret(sd_journal_previous(j)); /* no-op */ assert_ret(sd_journal_next(j)); /* pointing the first entry */ assert_ret(sd_journal_previous(j)); /* no-op */ assert_ret(sd_journal_previous(j)); /* no-op */ test_check_numbers_down(j, 9); sd_journal_close(j); /* Seek to tail, iterate up. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_tail(j)); assert_ret(sd_journal_previous(j)); test_check_numbers_up(j, 9); sd_journal_close(j); /* Seek to tail, move to next, then iterate up. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_tail(j)); assert_ret(sd_journal_next(j)); /* no-op */ assert_ret(sd_journal_previous(j)); /* pointing the first entry */ test_check_numbers_up(j, 9); sd_journal_close(j); /* Seek to tail, walk several steps, then iterate up. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_tail(j)); assert_ret(sd_journal_next(j)); /* no-op */ assert_ret(sd_journal_next(j)); /* no-op */ assert_ret(sd_journal_next(j)); /* no-op */ assert_ret(sd_journal_previous(j)); /* pointing the last entry. */ assert_ret(sd_journal_next(j)); /* no-op */ assert_ret(sd_journal_next(j)); /* no-op */ test_check_numbers_up(j, 9); sd_journal_close(j); /* Seek to tail, skip to head, iterate down. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_tail(j)); assert_ret(r = sd_journal_previous_skip(j, 9)); assert_se(r == 9); test_check_numbers_down(j, 9); sd_journal_close(j); /* Seek to tail, skip to head in a more complex way, then iterate down. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_tail(j)); assert_ret(sd_journal_next(j)); /* no-op */ assert_ret(r = sd_journal_previous_skip(j, 4)); assert_se(r == 4); assert_ret(r = sd_journal_previous_skip(j, 5)); assert_se(r == 5); assert_ret(sd_journal_previous(j)); /* no-op */ assert_ret(r = sd_journal_previous_skip(j, 5)); assert_se(r == 0); assert_ret(sd_journal_next(j)); assert_ret(r = sd_journal_previous_skip(j, 5)); assert_se(r == 1); assert_ret(sd_journal_next(j)); assert_ret(sd_journal_next(j)); assert_ret(sd_journal_previous(j)); assert_ret(sd_journal_next(j)); assert_ret(sd_journal_next(j)); assert_ret(r = sd_journal_previous_skip(j, 5)); assert_se(r == 3); test_check_numbers_down(j, 9); sd_journal_close(j); /* Seek to head, skip to tail, iterate up. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_head(j)); assert_ret(r = sd_journal_next_skip(j, 9)); assert_se(r == 9); test_check_numbers_up(j, 9); sd_journal_close(j); /* Seek to head, skip to tail in a more complex way, then iterate up. */ assert_ret(sd_journal_open_directory(&j, t, 0)); assert_ret(sd_journal_seek_head(j)); assert_ret(sd_journal_previous(j)); /* no-op */ assert_ret(r = sd_journal_next_skip(j, 4)); assert_se(r == 4); assert_ret(r = sd_journal_next_skip(j, 5)); assert_se(r == 5); assert_ret(sd_journal_next(j)); /* no-op */ assert_ret(r = sd_journal_next_skip(j, 5)); assert_se(r == 0); assert_ret(sd_journal_previous(j)); assert_ret(r = sd_journal_next_skip(j, 5)); assert_se(r == 1); assert_ret(sd_journal_previous(j)); assert_ret(sd_journal_previous(j)); assert_ret(sd_journal_next(j)); assert_ret(sd_journal_previous(j)); assert_ret(sd_journal_previous(j)); assert_ret(r = sd_journal_next_skip(j, 5)); assert_se(r == 3); test_check_numbers_up(j, 9); sd_journal_close(j); log_info("Done..."); if (arg_keep) log_info("Not removing %s", t); else { journal_directory_vacuum(".", 3000000, 0, 0, NULL, true); assert_se(rm_rf(t, REMOVE_ROOT|REMOVE_PHYSICAL) >= 0); } puts("------------------------------------------------------------"); } TEST(skip) { test_skip_one(setup_sequential); test_skip_one(setup_interleaved); } static void test_sequence_numbers_one(void) { _cleanup_(mmap_cache_unrefp) MMapCache *m = NULL; char t[] = "/var/tmp/journal-seq-XXXXXX"; ManagedJournalFile *one, *two; uint64_t seqnum = 0; sd_id128_t seqnum_id; m = mmap_cache_new(); assert_se(m != NULL); mkdtemp_chdir_chattr(t); assert_se(managed_journal_file_open(-1, "one.journal", O_RDWR|O_CREAT, JOURNAL_COMPRESS, 0644, UINT64_MAX, NULL, m, NULL, NULL, &one) == 0); append_number(one, 1, &seqnum); printf("seqnum=%"PRIu64"\n", seqnum); assert_se(seqnum == 1); append_number(one, 2, &seqnum); printf("seqnum=%"PRIu64"\n", seqnum); assert_se(seqnum == 2); assert_se(one->file->header->state == STATE_ONLINE); assert_se(!sd_id128_equal(one->file->header->file_id, one->file->header->machine_id)); assert_se(!sd_id128_equal(one->file->header->file_id, one->file->header->tail_entry_boot_id)); assert_se(sd_id128_equal(one->file->header->file_id, one->file->header->seqnum_id)); memcpy(&seqnum_id, &one->file->header->seqnum_id, sizeof(sd_id128_t)); assert_se(managed_journal_file_open(-1, "two.journal", O_RDWR|O_CREAT, JOURNAL_COMPRESS, 0644, UINT64_MAX, NULL, m, NULL, one, &two) == 0); assert_se(two->file->header->state == STATE_ONLINE); assert_se(!sd_id128_equal(two->file->header->file_id, one->file->header->file_id)); assert_se(sd_id128_equal(one->file->header->machine_id, one->file->header->machine_id)); assert_se(sd_id128_equal(one->file->header->tail_entry_boot_id, one->file->header->tail_entry_boot_id)); assert_se(sd_id128_equal(one->file->header->seqnum_id, one->file->header->seqnum_id)); append_number(two, 3, &seqnum); printf("seqnum=%"PRIu64"\n", seqnum); assert_se(seqnum == 3); append_number(two, 4, &seqnum); printf("seqnum=%"PRIu64"\n", seqnum); assert_se(seqnum == 4); test_close(two); append_number(one, 5, &seqnum); printf("seqnum=%"PRIu64"\n", seqnum); assert_se(seqnum == 5); append_number(one, 6, &seqnum); printf("seqnum=%"PRIu64"\n", seqnum); assert_se(seqnum == 6); test_close(one); /* If the machine-id is not initialized, the header file verification * (which happens when re-opening a journal file) will fail. */ if (sd_id128_get_machine(NULL) >= 0) { /* restart server */ seqnum = 0; assert_se(managed_journal_file_open(-1, "two.journal", O_RDWR, JOURNAL_COMPRESS, 0, UINT64_MAX, NULL, m, NULL, NULL, &two) == 0); assert_se(sd_id128_equal(two->file->header->seqnum_id, seqnum_id)); append_number(two, 7, &seqnum); printf("seqnum=%"PRIu64"\n", seqnum); assert_se(seqnum == 5); /* So..., here we have the same seqnum in two files with the * same seqnum_id. */ test_close(two); } log_info("Done..."); if (arg_keep) log_info("Not removing %s", t); else { journal_directory_vacuum(".", 3000000, 0, 0, NULL, true); assert_se(rm_rf(t, REMOVE_ROOT|REMOVE_PHYSICAL) >= 0); } } TEST(sequence_numbers) { assert_se(setenv("SYSTEMD_JOURNAL_COMPACT", "0", 1) >= 0); test_sequence_numbers_one(); assert_se(setenv("SYSTEMD_JOURNAL_COMPACT", "1", 1) >= 0); test_sequence_numbers_one(); } static int intro(void) { /* managed_journal_file_open requires a valid machine id */ if (access("/etc/machine-id", F_OK) != 0) return log_tests_skipped("/etc/machine-id not found"); arg_keep = saved_argc > 1; return EXIT_SUCCESS; } DEFINE_TEST_MAIN_WITH_INTRO(LOG_DEBUG, intro);
15,140
34.625882
133
c
null
systemd-main/src/journal/test-journal-syslog.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "journald-syslog.h" #include "macro.h" #include "string-util.h" #include "syslog-util.h" #include "tests.h" static void test_syslog_parse_identifier_one(const char *str, const char *ident, const char *pid, const char *rest, int ret) { const char *buf = str; _cleanup_free_ char *ident2 = NULL, *pid2 = NULL; int ret2; ret2 = syslog_parse_identifier(&buf, &ident2, &pid2); assert_se(ret == ret2); assert_se(ident == ident2 || streq_ptr(ident, ident2)); assert_se(pid == pid2 || streq_ptr(pid, pid2)); assert_se(streq(buf, rest)); } static void test_syslog_parse_priority_one(const char *str, bool with_facility, int priority, int ret) { int priority2 = 0, ret2; ret2 = syslog_parse_priority(&str, &priority2, with_facility); assert_se(ret == ret2); if (ret2 == 1) assert_se(priority == priority2); } TEST(syslog_parse_identifier) { test_syslog_parse_identifier_one("pidu[111]: xxx", "pidu", "111", "xxx", 11); test_syslog_parse_identifier_one("pidu: xxx", "pidu", NULL, "xxx", 6); test_syslog_parse_identifier_one("pidu: xxx", "pidu", NULL, " xxx", 6); test_syslog_parse_identifier_one("pidu xxx", NULL, NULL, "pidu xxx", 0); test_syslog_parse_identifier_one(" pidu xxx", NULL, NULL, " pidu xxx", 0); test_syslog_parse_identifier_one("", NULL, NULL, "", 0); test_syslog_parse_identifier_one(" ", NULL, NULL, " ", 0); test_syslog_parse_identifier_one(":", "", NULL, "", 1); test_syslog_parse_identifier_one(": ", "", NULL, " ", 2); test_syslog_parse_identifier_one(" :", "", NULL, "", 2); test_syslog_parse_identifier_one(" pidu:", "pidu", NULL, "", 8); test_syslog_parse_identifier_one("pidu:", "pidu", NULL, "", 5); test_syslog_parse_identifier_one("pidu: ", "pidu", NULL, "", 6); test_syslog_parse_identifier_one("pidu : ", NULL, NULL, "pidu : ", 0); } TEST(syslog_parse_priority) { test_syslog_parse_priority_one("", false, 0, 0); test_syslog_parse_priority_one("<>", false, 0, 0); test_syslog_parse_priority_one("<>aaa", false, 0, 0); test_syslog_parse_priority_one("<aaaa>", false, 0, 0); test_syslog_parse_priority_one("<aaaa>aaa", false, 0, 0); test_syslog_parse_priority_one(" <aaaa>", false, 0, 0); test_syslog_parse_priority_one(" <aaaa>aaa", false, 0, 0); test_syslog_parse_priority_one(" <aaaa>aaa", false, 0, 0); test_syslog_parse_priority_one(" <1>", false, 0, 0); test_syslog_parse_priority_one("<1>", false, 1, 1); test_syslog_parse_priority_one("<7>", false, 7, 1); test_syslog_parse_priority_one("<8>", false, 0, 0); test_syslog_parse_priority_one("<9>", true, 9, 1); test_syslog_parse_priority_one("<22>", true, 22, 1); test_syslog_parse_priority_one("<111>", false, 0, 0); test_syslog_parse_priority_one("<111>", true, 111, 1); } DEFINE_TEST_MAIN(LOG_INFO);
3,172
43.690141
105
c
null
systemd-main/src/libsystemd-network/arp-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright © 2014 Axis Communications AB. All rights reserved. ***/ #include <arpa/inet.h> #include <linux/filter.h> #include <netinet/if_ether.h> #include "arp-util.h" #include "ether-addr-util.h" #include "fd-util.h" #include "in-addr-util.h" #include "unaligned.h" int arp_update_filter(int fd, const struct in_addr *a, const struct ether_addr *mac) { struct sock_filter filter[] = { BPF_STMT(BPF_LD + BPF_W + BPF_LEN, 0), /* A <- packet length */ BPF_JUMP(BPF_JMP + BPF_JGE + BPF_K, sizeof(struct ether_arp), 1, 0), /* packet >= arp packet ? */ BPF_STMT(BPF_RET + BPF_K, 0), /* ignore */ BPF_STMT(BPF_LD + BPF_H + BPF_ABS, offsetof(struct ether_arp, ea_hdr.ar_hrd)), /* A <- header */ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ARPHRD_ETHER, 1, 0), /* header == ethernet ? */ BPF_STMT(BPF_RET + BPF_K, 0), /* ignore */ BPF_STMT(BPF_LD + BPF_H + BPF_ABS, offsetof(struct ether_arp, ea_hdr.ar_pro)), /* A <- protocol */ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ETHERTYPE_IP, 1, 0), /* protocol == IP ? */ BPF_STMT(BPF_RET + BPF_K, 0), /* ignore */ BPF_STMT(BPF_LD + BPF_B + BPF_ABS, offsetof(struct ether_arp, ea_hdr.ar_hln)), /* A <- hardware address length */ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, sizeof(struct ether_addr), 1, 0), /* length == sizeof(ether_addr)? */ BPF_STMT(BPF_RET + BPF_K, 0), /* ignore */ BPF_STMT(BPF_LD + BPF_B + BPF_ABS, offsetof(struct ether_arp, ea_hdr.ar_pln)), /* A <- protocol address length */ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, sizeof(struct in_addr), 1, 0), /* length == sizeof(in_addr) ? */ BPF_STMT(BPF_RET + BPF_K, 0), /* ignore */ BPF_STMT(BPF_LD + BPF_H + BPF_ABS, offsetof(struct ether_arp, ea_hdr.ar_op)), /* A <- operation */ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ARPOP_REQUEST, 2, 0), /* protocol == request ? */ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_K, ARPOP_REPLY, 1, 0), /* protocol == reply ? */ BPF_STMT(BPF_RET + BPF_K, 0), /* ignore */ /* Sender Hardware Address must be different from our own */ BPF_STMT(BPF_LDX + BPF_IMM, unaligned_read_be32(&mac->ether_addr_octet[0])), /* X <- 4 bytes of client's MAC */ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct ether_arp, arp_sha)), /* A <- 4 bytes of SHA */ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_X, 0, 0, 4), /* A == X ? */ BPF_STMT(BPF_LDX + BPF_IMM, unaligned_read_be16(&mac->ether_addr_octet[4])), /* X <- remainder of client's MAC */ BPF_STMT(BPF_LD + BPF_H + BPF_ABS, offsetof(struct ether_arp, arp_sha) + 4), /* A <- remainder of SHA */ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_X, 0, 0, 1), /* A == X ? */ BPF_STMT(BPF_RET + BPF_K, 0), /* ignore */ /* Sender Protocol Address or Target Protocol Address must be equal to the one we care about */ BPF_STMT(BPF_LDX + BPF_IMM, htobe32(a->s_addr)), /* X <- clients IP */ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct ether_arp, arp_spa)), /* A <- SPA */ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_X, 0, 0, 1), /* A == X ? */ BPF_STMT(BPF_RET + BPF_K, UINT32_MAX), /* accept */ BPF_STMT(BPF_LD + BPF_W + BPF_ABS, offsetof(struct ether_arp, arp_tpa)), /* A <- TPA */ BPF_JUMP(BPF_JMP + BPF_JEQ + BPF_X, 0, 0, 1), /* A == 0 ? */ BPF_STMT(BPF_RET + BPF_K, UINT32_MAX), /* accept */ BPF_STMT(BPF_RET + BPF_K, 0), /* ignore */ }; struct sock_fprog fprog = { .len = ELEMENTSOF(filter), .filter = (struct sock_filter*) filter, }; assert(fd >= 0); if (setsockopt(fd, SOL_SOCKET, SO_ATTACH_FILTER, &fprog, sizeof(fprog)) < 0) return -errno; return 0; } int arp_network_bind_raw_socket(int ifindex, const struct in_addr *a, const struct ether_addr *mac) { union sockaddr_union link = { .ll.sll_family = AF_PACKET, .ll.sll_protocol = htobe16(ETH_P_ARP), .ll.sll_ifindex = ifindex, .ll.sll_halen = ETH_ALEN, .ll.sll_addr = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, }; _cleanup_close_ int s = -EBADF; int r; assert(ifindex > 0); assert(mac); s = socket(AF_PACKET, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, 0); if (s < 0) return -errno; r = arp_update_filter(s, a, mac); if (r < 0) return r; if (bind(s, &link.sa, sizeof(link.ll)) < 0) return -errno; return TAKE_FD(s); } int arp_send_packet( int fd, int ifindex, const struct in_addr *pa, const struct ether_addr *ha, bool announce) { union sockaddr_union link = { .ll.sll_family = AF_PACKET, .ll.sll_protocol = htobe16(ETH_P_ARP), .ll.sll_ifindex = ifindex, .ll.sll_halen = ETH_ALEN, .ll.sll_addr = { 0xff, 0xff, 0xff, 0xff, 0xff, 0xff }, }; struct ether_arp arp = { .ea_hdr.ar_hrd = htobe16(ARPHRD_ETHER), /* HTYPE */ .ea_hdr.ar_pro = htobe16(ETHERTYPE_IP), /* PTYPE */ .ea_hdr.ar_hln = ETH_ALEN, /* HLEN */ .ea_hdr.ar_pln = sizeof(struct in_addr), /* PLEN */ .ea_hdr.ar_op = htobe16(ARPOP_REQUEST), /* REQUEST */ }; ssize_t n; assert(fd >= 0); assert(ifindex > 0); assert(pa); assert(in4_addr_is_set(pa)); assert(ha); assert(!ether_addr_is_null(ha)); memcpy(&arp.arp_sha, ha, ETH_ALEN); memcpy(&arp.arp_tpa, pa, sizeof(struct in_addr)); if (announce) memcpy(&arp.arp_spa, pa, sizeof(struct in_addr)); n = sendto(fd, &arp, sizeof(struct ether_arp), 0, &link.sa, sizeof(link.ll)); if (n < 0) return -errno; if (n != sizeof(struct ether_arp)) return -EIO; return 0; }
7,287
51.057143
131
c
null
systemd-main/src/libsystemd-network/arp-util.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /*** Copyright © 2014 Axis Communications AB. All rights reserved. ***/ #include <net/ethernet.h> #include <netinet/in.h> #include "socket-util.h" #include "sparse-endian.h" int arp_update_filter(int fd, const struct in_addr *a, const struct ether_addr *mac); int arp_network_bind_raw_socket(int ifindex, const struct in_addr *a, const struct ether_addr *mac); int arp_send_packet( int fd, int ifindex, const struct in_addr *pa, const struct ether_addr *ha, bool announce); static inline int arp_send_probe( int fd, int ifindex, const struct in_addr *pa, const struct ether_addr *ha) { return arp_send_packet(fd, ifindex, pa, ha, false); } static inline int arp_send_announcement( int fd, int ifindex, const struct in_addr *pa, const struct ether_addr *ha) { return arp_send_packet(fd, ifindex, pa, ha, true); }
1,105
28.891892
100
h
null
systemd-main/src/libsystemd-network/dhcp-identifier.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-device.h" #include "sd-id128.h" #include "ether-addr-util.h" #include "macro.h" #include "sparse-endian.h" #include "time-util.h" #include "unaligned.h" #define SYSTEMD_PEN 43793 typedef enum DUIDType { DUID_TYPE_LLT = 1, DUID_TYPE_EN = 2, DUID_TYPE_LL = 3, DUID_TYPE_UUID = 4, _DUID_TYPE_MAX, _DUID_TYPE_INVALID = -EINVAL, } DUIDType; /* RFC 3315 section 9.1: * A DUID can be no more than 128 octets long (not including the type code). */ #define MAX_DUID_LEN 128 /* https://tools.ietf.org/html/rfc3315#section-9.1 */ struct duid { be16_t type; union { struct { /* DUID_TYPE_LLT */ be16_t htype; be32_t time; uint8_t haddr[0]; } _packed_ llt; struct { /* DUID_TYPE_EN */ be32_t pen; uint8_t id[8]; } _packed_ en; struct { /* DUID_TYPE_LL */ be16_t htype; uint8_t haddr[0]; } _packed_ ll; struct { /* DUID_TYPE_UUID */ sd_id128_t uuid; } _packed_ uuid; struct { uint8_t data[MAX_DUID_LEN]; } _packed_ raw; }; } _packed_; int dhcp_validate_duid_len(DUIDType duid_type, size_t duid_len, bool strict); int dhcp_identifier_set_duid_en(bool test_mode, struct duid *ret_duid, size_t *ret_len); int dhcp_identifier_set_duid( DUIDType duid_type, const struct hw_addr_data *hw_addr, uint16_t arp_type, usec_t llt_time, bool test_mode, struct duid *ret_duid, size_t *ret_len); int dhcp_identifier_set_iaid( sd_device *dev, const struct hw_addr_data *hw_addr, bool legacy_unstable_byteorder, void *ret); const char *duid_type_to_string(DUIDType t) _const_;
2,285
29.078947
88
h
null
systemd-main/src/libsystemd-network/dhcp-internal.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /*** Copyright © 2013 Intel Corporation. All rights reserved. ***/ #include <linux/if_packet.h> #include <net/ethernet.h> #include <stdint.h> #include "sd-dhcp-client.h" #include "dhcp-protocol.h" #include "ether-addr-util.h" #include "network-common.h" #include "socket-util.h" typedef struct sd_dhcp_option { unsigned n_ref; uint8_t option; void *data; size_t length; } sd_dhcp_option; typedef struct DHCPServerData { struct in_addr *addr; size_t size; } DHCPServerData; extern const struct hash_ops dhcp_option_hash_ops; typedef struct sd_dhcp_client sd_dhcp_client; int dhcp_network_bind_raw_socket( int ifindex, union sockaddr_union *link, uint32_t xid, const struct hw_addr_data *hw_addr, const struct hw_addr_data *bcast_addr, uint16_t arp_type, uint16_t port, bool so_priority_set, int so_priority); int dhcp_network_bind_udp_socket(int ifindex, be32_t address, uint16_t port, int ip_service_type); int dhcp_network_send_raw_socket(int s, const union sockaddr_union *link, const void *packet, size_t len); int dhcp_network_send_udp_socket(int s, be32_t address, uint16_t port, const void *packet, size_t len); int dhcp_option_append(DHCPMessage *message, size_t size, size_t *offset, uint8_t overload, uint8_t code, size_t optlen, const void *optval); int dhcp_option_find_option(uint8_t *options, size_t length, uint8_t wanted_code, size_t *ret_offset); int dhcp_option_remove_option(uint8_t *options, size_t buflen, uint8_t option_code); typedef int (*dhcp_option_callback_t)(uint8_t code, uint8_t len, const void *option, void *userdata); int dhcp_option_parse(DHCPMessage *message, size_t len, dhcp_option_callback_t cb, void *userdata, char **error_message); int dhcp_option_parse_string(const uint8_t *option, size_t len, char **ret); int dhcp_message_init(DHCPMessage *message, uint8_t op, uint32_t xid, uint8_t type, uint16_t arp_type, uint8_t hlen, const uint8_t *chaddr, size_t optlen, size_t *optoffset); uint16_t dhcp_packet_checksum(uint8_t *buf, size_t len); void dhcp_packet_append_ip_headers(DHCPPacket *packet, be32_t source_addr, uint16_t source, be32_t destination_addr, uint16_t destination, uint16_t len, int ip_service_type); int dhcp_packet_verify_headers(DHCPPacket *packet, size_t len, bool checksum, uint16_t port); void dhcp_client_set_test_mode(sd_dhcp_client *client, bool test_mode); /* If we are invoking callbacks of a dhcp-client, ensure unreffing the * client from the callback doesn't destroy the object we are working * on */ #define DHCP_CLIENT_DONT_DESTROY(client) \ _cleanup_(sd_dhcp_client_unrefp) _unused_ sd_dhcp_client *_dont_destroy_##client = sd_dhcp_client_ref(client) #define log_dhcp_client_errno(client, error, fmt, ...) \ log_interface_prefix_full_errno( \ "DHCPv4 client: ", \ sd_dhcp_client, client, \ error, fmt, ##__VA_ARGS__) #define log_dhcp_client(client, fmt, ...) \ log_interface_prefix_full_errno_zerook( \ "DHCPv4 client: ", \ sd_dhcp_client, client, \ 0, fmt, ##__VA_ARGS__)
3,755
38.957447
121
h
null
systemd-main/src/libsystemd-network/dhcp-lease-internal.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /*** Copyright © 2013 Intel Corporation. All rights reserved. ***/ #include "sd-dhcp-client.h" #include "dhcp-internal.h" #include "dhcp-protocol.h" #include "list.h" struct sd_dhcp_route { struct in_addr dst_addr; struct in_addr gw_addr; unsigned char dst_prefixlen; }; struct sd_dhcp_raw_option { LIST_FIELDS(struct sd_dhcp_raw_option, options); uint8_t tag; uint8_t length; void *data; }; struct sd_dhcp_lease { unsigned n_ref; /* each 0 if unset */ uint32_t t1; uint32_t t2; uint32_t lifetime; /* each 0 if unset */ be32_t address; be32_t server_address; be32_t next_server; bool have_subnet_mask; be32_t subnet_mask; bool have_broadcast; be32_t broadcast; struct in_addr *router; size_t router_size; DHCPServerData servers[_SD_DHCP_LEASE_SERVER_TYPE_MAX]; struct sd_dhcp_route *static_routes; size_t n_static_routes; struct sd_dhcp_route *classless_routes; size_t n_classless_routes; uint16_t mtu; /* 0 if unset */ char *domainname; char **search_domains; char *hostname; char *root_path; char *captive_portal; void *client_id; size_t client_id_len; void *vendor_specific; size_t vendor_specific_len; char *timezone; uint8_t sixrd_ipv4masklen; uint8_t sixrd_prefixlen; struct in6_addr sixrd_prefix; struct in_addr *sixrd_br_addresses; size_t sixrd_n_br_addresses; LIST_HEAD(struct sd_dhcp_raw_option, private_options); }; int dhcp_lease_new(sd_dhcp_lease **ret); int dhcp_lease_parse_options(uint8_t code, uint8_t len, const void *option, void *userdata); int dhcp_lease_parse_search_domains(const uint8_t *option, size_t len, char ***domains); int dhcp_lease_insert_private_option(sd_dhcp_lease *lease, uint8_t tag, const void *data, uint8_t len); int dhcp_lease_set_default_subnet_mask(sd_dhcp_lease *lease); int dhcp_lease_set_client_id(sd_dhcp_lease *lease, const void *client_id, size_t client_id_len);
2,254
23.78022
103
h
null
systemd-main/src/libsystemd-network/dhcp-packet.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright © 2013 Intel Corporation. All rights reserved. ***/ #include <errno.h> #include <net/ethernet.h> #include <net/if_arp.h> #include <string.h> #include "dhcp-internal.h" #include "dhcp-protocol.h" #include "memory-util.h" #define DHCP_CLIENT_MIN_OPTIONS_SIZE 312 int dhcp_message_init( DHCPMessage *message, uint8_t op, uint32_t xid, uint8_t type, uint16_t arp_type, uint8_t hlen, const uint8_t *chaddr, size_t optlen, size_t *optoffset) { size_t offset = 0; int r; assert(IN_SET(op, BOOTREQUEST, BOOTREPLY)); assert(chaddr || hlen == 0); message->op = op; message->htype = arp_type; /* RFC2131 section 4.1.1: The client MUST include its hardware address in the ’chaddr’ field, if necessary for delivery of DHCP reply messages. RFC 4390 section 2.1: A DHCP client, when working over an IPoIB interface, MUST follow the following rules: "htype" (hardware address type) MUST be 32 [ARPPARAM]. "hlen" (hardware address length) MUST be 0. "chaddr" (client hardware address) field MUST be zeroed. */ message->hlen = arp_type == ARPHRD_INFINIBAND ? 0 : hlen; memcpy_safe(message->chaddr, chaddr, message->hlen); message->xid = htobe32(xid); message->magic = htobe32(DHCP_MAGIC_COOKIE); r = dhcp_option_append(message, optlen, &offset, 0, SD_DHCP_OPTION_MESSAGE_TYPE, 1, &type); if (r < 0) return r; *optoffset = offset; return 0; } uint16_t dhcp_packet_checksum(uint8_t *buf, size_t len) { uint64_t *buf_64 = (uint64_t*)buf; uint64_t *end_64 = buf_64 + (len / sizeof(uint64_t)); uint64_t sum = 0; /* See RFC1071 */ while (buf_64 < end_64) { sum += *buf_64; if (sum < *buf_64) /* wrap around in one's complement */ sum++; buf_64++; } if (len % sizeof(uint64_t)) { /* If the buffer is not aligned to 64-bit, we need to zero-pad the last few bytes and add them in */ uint64_t buf_tail = 0; memcpy(&buf_tail, buf_64, len % sizeof(uint64_t)); sum += buf_tail; if (sum < buf_tail) /* wrap around */ sum++; } while (sum >> 16) sum = (sum & 0xffff) + (sum >> 16); return ~sum; } void dhcp_packet_append_ip_headers(DHCPPacket *packet, be32_t source_addr, uint16_t source_port, be32_t destination_addr, uint16_t destination_port, uint16_t len, int ip_service_type) { packet->ip.version = IPVERSION; packet->ip.ihl = DHCP_IP_SIZE / 4; packet->ip.tot_len = htobe16(len); if (ip_service_type >= 0) packet->ip.tos = ip_service_type; else packet->ip.tos = IPTOS_CLASS_CS6; packet->ip.protocol = IPPROTO_UDP; packet->ip.saddr = source_addr; packet->ip.daddr = destination_addr; packet->udp.source = htobe16(source_port); packet->udp.dest = htobe16(destination_port); packet->udp.len = htobe16(len - DHCP_IP_SIZE); packet->ip.check = packet->udp.len; packet->udp.check = dhcp_packet_checksum((uint8_t*)&packet->ip.ttl, len - 8); packet->ip.ttl = IPDEFTTL; packet->ip.check = 0; packet->ip.check = dhcp_packet_checksum((uint8_t*)&packet->ip, DHCP_IP_SIZE); } int dhcp_packet_verify_headers(DHCPPacket *packet, size_t len, bool checksum, uint16_t port) { size_t hdrlen; assert(packet); assert(len >= sizeof(DHCPPacket)); /* IP */ if (packet->ip.version != IPVERSION) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "ignoring packet: not IPv4"); if (packet->ip.ihl < 5) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "ignoring packet: IPv4 IHL (%i words) invalid", packet->ip.ihl); hdrlen = packet->ip.ihl * 4; if (hdrlen < 20) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "ignoring packet: IPv4 IHL (%zu bytes) smaller than minimum (20 bytes)", hdrlen); if (len < hdrlen) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "ignoring packet: packet (%zu bytes) smaller than expected (%zu) by IP header", len, hdrlen); /* UDP */ if (packet->ip.protocol != IPPROTO_UDP) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "ignoring packet: not UDP"); if (len < hdrlen + be16toh(packet->udp.len)) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "ignoring packet: packet (%zu bytes) smaller than expected (%zu) by UDP header", len, hdrlen + be16toh(packet->udp.len)); if (be16toh(packet->udp.dest) != port) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "ignoring packet: to port %u, which is not the DHCP client port (%u)", be16toh(packet->udp.dest), port); /* checksums - computing these is relatively expensive, so only do it if all the other checks have passed */ if (dhcp_packet_checksum((uint8_t*)&packet->ip, hdrlen)) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "ignoring packet: invalid IP checksum"); if (checksum && packet->udp.check) { packet->ip.check = packet->udp.len; packet->ip.ttl = 0; if (dhcp_packet_checksum((uint8_t*)&packet->ip.ttl, be16toh(packet->udp.len) + 12)) return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "ignoring packet: invalid UDP checksum"); } return 0; }
6,712
33.963542
119
c
null
systemd-main/src/libsystemd-network/dhcp-protocol.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /*** Copyright © 2013 Intel Corporation. All rights reserved. ***/ #include <netinet/ip.h> #include <netinet/udp.h> #include <stdint.h> #include "macro.h" #include "sparse-endian.h" struct DHCPMessage { uint8_t op; uint8_t htype; uint8_t hlen; uint8_t hops; be32_t xid; be16_t secs; be16_t flags; be32_t ciaddr; be32_t yiaddr; be32_t siaddr; be32_t giaddr; uint8_t chaddr[16]; uint8_t sname[64]; uint8_t file[128]; be32_t magic; uint8_t options[]; } _packed_; typedef struct DHCPMessage DHCPMessage; struct DHCPPacket { struct iphdr ip; struct udphdr udp; DHCPMessage dhcp; } _packed_; typedef struct DHCPPacket DHCPPacket; #define DHCP_IP_SIZE (int32_t)(sizeof(struct iphdr)) #define DHCP_IP_UDP_SIZE (int32_t)(sizeof(struct udphdr) + DHCP_IP_SIZE) #define DHCP_HEADER_SIZE (int32_t)(sizeof(DHCPMessage)) #define DHCP_MIN_MESSAGE_SIZE 576 /* the minimum internet hosts must be able to receive, see RFC 2132 Section 9.10 */ #define DHCP_MIN_OPTIONS_SIZE (DHCP_MIN_MESSAGE_SIZE - DHCP_HEADER_SIZE) #define DHCP_MIN_PACKET_SIZE (DHCP_MIN_MESSAGE_SIZE + DHCP_IP_UDP_SIZE) #define DHCP_MAGIC_COOKIE (uint32_t)(0x63825363) enum { DHCP_PORT_SERVER = 67, DHCP_PORT_CLIENT = 68, }; enum DHCPState { DHCP_STATE_INIT = 0, DHCP_STATE_SELECTING = 1, DHCP_STATE_INIT_REBOOT = 2, DHCP_STATE_REBOOTING = 3, DHCP_STATE_REQUESTING = 4, DHCP_STATE_BOUND = 5, DHCP_STATE_RENEWING = 6, DHCP_STATE_REBINDING = 7, DHCP_STATE_STOPPED = 8, }; typedef enum DHCPState DHCPState; enum { BOOTREQUEST = 1, BOOTREPLY = 2, }; enum { DHCP_DISCOVER = 1, /* [RFC2132] */ DHCP_OFFER = 2, /* [RFC2132] */ DHCP_REQUEST = 3, /* [RFC2132] */ DHCP_DECLINE = 4, /* [RFC2132] */ DHCP_ACK = 5, /* [RFC2132] */ DHCP_NAK = 6, /* [RFC2132] */ DHCP_RELEASE = 7, /* [RFC2132] */ DHCP_INFORM = 8, /* [RFC2132] */ DHCP_FORCERENEW = 9, /* [RFC3203] */ DHCPLEASEQUERY = 10, /* [RFC4388] */ DHCPLEASEUNASSIGNED = 11, /* [RFC4388] */ DHCPLEASEUNKNOWN = 12, /* [RFC4388] */ DHCPLEASEACTIVE = 13, /* [RFC4388] */ DHCPBULKLEASEQUERY = 14, /* [RFC6926] */ DHCPLEASEQUERYDONE = 15, /* [RFC6926] */ DHCPACTIVELEASEQUERY = 16, /* [RFC7724] */ DHCPLEASEQUERYSTATUS = 17, /* [RFC7724] */ DHCPTLS = 18, /* [RFC7724] */ }; enum { DHCP_OVERLOAD_FILE = 1, DHCP_OVERLOAD_SNAME = 2, }; #define DHCP_MAX_FQDN_LENGTH 255 enum { DHCP_FQDN_FLAG_S = (1 << 0), DHCP_FQDN_FLAG_O = (1 << 1), DHCP_FQDN_FLAG_E = (1 << 2), DHCP_FQDN_FLAG_N = (1 << 3), };
3,730
32.918182
119
h
null
systemd-main/src/libsystemd-network/dhcp-server-internal.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /*** Copyright © 2013 Intel Corporation. All rights reserved. ***/ #include "sd-dhcp-server.h" #include "sd-event.h" #include "dhcp-internal.h" #include "network-common.h" #include "ordered-set.h" #include "time-util.h" typedef enum DHCPRawOption { DHCP_RAW_OPTION_DATA_UINT8, DHCP_RAW_OPTION_DATA_UINT16, DHCP_RAW_OPTION_DATA_UINT32, DHCP_RAW_OPTION_DATA_STRING, DHCP_RAW_OPTION_DATA_IPV4ADDRESS, DHCP_RAW_OPTION_DATA_IPV6ADDRESS, _DHCP_RAW_OPTION_DATA_MAX, _DHCP_RAW_OPTION_DATA_INVALID, } DHCPRawOption; typedef struct DHCPClientId { size_t length; uint8_t *data; } DHCPClientId; typedef struct DHCPLease { sd_dhcp_server *server; DHCPClientId client_id; uint8_t htype; /* e.g. ARPHRD_ETHER */ uint8_t hlen; /* e.g. ETH_ALEN */ be32_t address; be32_t gateway; uint8_t chaddr[16]; usec_t expiration; char *hostname; } DHCPLease; struct sd_dhcp_server { unsigned n_ref; sd_event *event; int event_priority; sd_event_source *receive_message; sd_event_source *receive_broadcast; int fd; int fd_raw; int fd_broadcast; int ifindex; char *ifname; bool bind_to_interface; be32_t address; be32_t netmask; be32_t subnet; uint32_t pool_offset; uint32_t pool_size; char *timezone; DHCPServerData servers[_SD_DHCP_LEASE_SERVER_TYPE_MAX]; struct in_addr boot_server_address; char *boot_server_name; char *boot_filename; OrderedSet *extra_options; OrderedSet *vendor_options; bool emit_router; struct in_addr router_address; Hashmap *bound_leases_by_client_id; Hashmap *bound_leases_by_address; Hashmap *static_leases_by_client_id; Hashmap *static_leases_by_address; uint32_t max_lease_time, default_lease_time; sd_dhcp_server_callback_t callback; void *callback_userdata; struct in_addr relay_target; char *agent_circuit_id; char *agent_remote_id; }; typedef struct DHCPRequest { /* received message */ DHCPMessage *message; /* options */ DHCPClientId client_id; size_t max_optlen; be32_t server_id; be32_t requested_ip; uint32_t lifetime; const uint8_t *agent_info_option; char *hostname; } DHCPRequest; extern const struct hash_ops dhcp_lease_hash_ops; int dhcp_server_handle_message(sd_dhcp_server *server, DHCPMessage *message, size_t length); int dhcp_server_send_packet(sd_dhcp_server *server, DHCPRequest *req, DHCPPacket *packet, int type, size_t optoffset); void client_id_hash_func(const DHCPClientId *p, struct siphash *state); int client_id_compare_func(const DHCPClientId *a, const DHCPClientId *b); DHCPLease *dhcp_lease_free(DHCPLease *lease); DEFINE_TRIVIAL_CLEANUP_FUNC(DHCPLease*, dhcp_lease_free); #define log_dhcp_server_errno(server, error, fmt, ...) \ log_interface_prefix_full_errno( \ "DHCPv4 server: ", \ sd_dhcp_server, server, \ error, fmt, ##__VA_ARGS__) #define log_dhcp_server(server, fmt, ...) \ log_interface_prefix_full_errno_zerook( \ "DHCPv4 server: ", \ sd_dhcp_server, server, \ 0, fmt, ##__VA_ARGS__)
3,807
27.631579
76
h
null
systemd-main/src/libsystemd-network/dhcp6-internal.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /*** Copyright © 2014-2015 Intel Corporation. All rights reserved. ***/ #include <net/ethernet.h> #include <netinet/in.h> #include "sd-event.h" #include "sd-dhcp6-client.h" #include "dhcp-identifier.h" #include "dhcp6-option.h" #include "dhcp6-protocol.h" #include "ether-addr-util.h" #include "hashmap.h" #include "macro.h" #include "network-common.h" #include "ordered-set.h" #include "sparse-endian.h" #include "time-util.h" /* what to request from the server, addresses (IA_NA) and/or prefixes (IA_PD) */ typedef enum DHCP6RequestIA { DHCP6_REQUEST_IA_NA = 1 << 0, DHCP6_REQUEST_IA_TA = 1 << 1, /* currently not used */ DHCP6_REQUEST_IA_PD = 1 << 2, } DHCP6RequestIA; struct sd_dhcp6_client { unsigned n_ref; int ifindex; char *ifname; struct in6_addr local_address; struct hw_addr_data hw_addr; uint16_t arp_type; sd_event *event; sd_event_source *receive_message; sd_event_source *timeout_resend; sd_event_source *timeout_expire; sd_event_source *timeout_t1; sd_event_source *timeout_t2; int event_priority; int fd; sd_device *dev; DHCP6State state; bool information_request; usec_t information_request_time_usec; usec_t information_refresh_time_usec; be32_t transaction_id; usec_t transaction_start; usec_t retransmit_time; uint8_t retransmit_count; bool iaid_set; DHCP6IA ia_na; DHCP6IA ia_pd; DHCP6RequestIA request_ia; struct duid duid; size_t duid_len; be16_t *req_opts; size_t n_req_opts; char *fqdn; char *mudurl; char **user_class; char **vendor_class; OrderedHashmap *extra_options; OrderedSet *vendor_options; bool rapid_commit; struct sd_dhcp6_lease *lease; sd_dhcp6_client_callback_t callback; void *userdata; bool send_release; /* Ignore machine-ID when generating DUID. See dhcp_identifier_set_duid_en(). */ bool test_mode; }; int dhcp6_network_bind_udp_socket(int ifindex, struct in6_addr *address); int dhcp6_network_send_udp_socket(int s, struct in6_addr *address, const void *packet, size_t len); int dhcp6_client_send_message(sd_dhcp6_client *client); void dhcp6_client_set_test_mode(sd_dhcp6_client *client, bool test_mode); int dhcp6_client_set_transaction_id(sd_dhcp6_client *client, uint32_t transaction_id); #define log_dhcp6_client_errno(client, error, fmt, ...) \ log_interface_prefix_full_errno( \ "DHCPv6 client: ", \ sd_dhcp6_client, client, \ error, fmt, ##__VA_ARGS__) #define log_dhcp6_client(client, fmt, ...) \ log_interface_prefix_full_errno_zerook( \ "DHCPv6 client: ", \ sd_dhcp6_client, client, \ 0, fmt, ##__VA_ARGS__)
3,240
29.575472
88
h
null
systemd-main/src/libsystemd-network/dhcp6-lease-internal.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once /*** Copyright © 2014-2015 Intel Corporation. All rights reserved. ***/ #include <inttypes.h> #include "sd-dhcp6-lease.h" #include "dhcp6-option.h" #include "macro.h" #include "time-util.h" struct sd_dhcp6_lease { unsigned n_ref; uint8_t *clientid; size_t clientid_len; uint8_t *serverid; size_t serverid_len; uint8_t preference; bool rapid_commit; triple_timestamp timestamp; usec_t lifetime_t1; usec_t lifetime_t2; usec_t lifetime_valid; struct in6_addr server_address; DHCP6IA *ia_na; /* Identity association non-temporary addresses */ DHCP6IA *ia_pd; /* Identity association prefix delegation */ DHCP6Address *addr_iter; DHCP6Address *prefix_iter; struct in6_addr *dns; size_t dns_count; char **domains; struct in6_addr *ntp; size_t ntp_count; char **ntp_fqdn; struct in6_addr *sntp; size_t sntp_count; char *fqdn; char *captive_portal; }; int dhcp6_lease_get_lifetime(sd_dhcp6_lease *lease, usec_t *ret_t1, usec_t *ret_t2, usec_t *ret_valid); int dhcp6_lease_set_clientid(sd_dhcp6_lease *lease, const uint8_t *id, size_t len); int dhcp6_lease_get_clientid(sd_dhcp6_lease *lease, uint8_t **ret_id, size_t *ret_len); int dhcp6_lease_set_serverid(sd_dhcp6_lease *lease, const uint8_t *id, size_t len); int dhcp6_lease_get_serverid(sd_dhcp6_lease *lease, uint8_t **ret_id, size_t *ret_len); int dhcp6_lease_set_preference(sd_dhcp6_lease *lease, uint8_t preference); int dhcp6_lease_get_preference(sd_dhcp6_lease *lease, uint8_t *ret); int dhcp6_lease_set_rapid_commit(sd_dhcp6_lease *lease); int dhcp6_lease_get_rapid_commit(sd_dhcp6_lease *lease, bool *ret); int dhcp6_lease_add_dns(sd_dhcp6_lease *lease, const uint8_t *optval, size_t optlen); int dhcp6_lease_add_domains(sd_dhcp6_lease *lease, const uint8_t *optval, size_t optlen); int dhcp6_lease_add_ntp(sd_dhcp6_lease *lease, const uint8_t *optval, size_t optlen); int dhcp6_lease_add_sntp(sd_dhcp6_lease *lease, const uint8_t *optval, size_t optlen); int dhcp6_lease_set_fqdn(sd_dhcp6_lease *lease, const uint8_t *optval, size_t optlen); int dhcp6_lease_set_captive_portal(sd_dhcp6_lease *lease, const uint8_t *optval, size_t optlen); int dhcp6_lease_new(sd_dhcp6_lease **ret); int dhcp6_lease_new_from_message( sd_dhcp6_client *client, const DHCP6Message *message, size_t len, const triple_timestamp *timestamp, const struct in6_addr *server_address, sd_dhcp6_lease **ret);
2,714
35.689189
103
h
null
systemd-main/src/libsystemd-network/dhcp6-network.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright © 2014 Intel Corporation. All rights reserved. ***/ #include <errno.h> #include <netinet/in.h> #include <netinet/ip6.h> #include <stdio.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <linux/if_packet.h> #include "dhcp6-internal.h" #include "dhcp6-protocol.h" #include "fd-util.h" #include "socket-util.h" int dhcp6_network_bind_udp_socket(int ifindex, struct in6_addr *local_address) { union sockaddr_union src = { .in6.sin6_family = AF_INET6, .in6.sin6_port = htobe16(DHCP6_PORT_CLIENT), .in6.sin6_scope_id = ifindex, }; _cleanup_close_ int s = -EBADF; int r; assert(ifindex > 0); assert(local_address); src.in6.sin6_addr = *local_address; s = socket(AF_INET6, SOCK_DGRAM | SOCK_CLOEXEC | SOCK_NONBLOCK, IPPROTO_UDP); if (s < 0) return -errno; r = setsockopt_int(s, IPPROTO_IPV6, IPV6_V6ONLY, true); if (r < 0) return r; r = setsockopt_int(s, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, false); if (r < 0) return r; r = setsockopt_int(s, SOL_SOCKET, SO_REUSEADDR, true); if (r < 0) return r; r = setsockopt_int(s, SOL_SOCKET, SO_TIMESTAMP, true); if (r < 0) return r; r = bind(s, &src.sa, sizeof(src.in6)); if (r < 0) return -errno; return TAKE_FD(s); } int dhcp6_network_send_udp_socket(int s, struct in6_addr *server_address, const void *packet, size_t len) { union sockaddr_union dest = { .in6.sin6_family = AF_INET6, .in6.sin6_port = htobe16(DHCP6_PORT_SERVER), }; int r; assert(server_address); memcpy(&dest.in6.sin6_addr, server_address, sizeof(dest.in6.sin6_addr)); r = sendto(s, packet, len, 0, &dest.sa, sizeof(dest.in6)); if (r < 0) return -errno; return 0; }
2,123
25.886076
85
c
null
systemd-main/src/libsystemd-network/dhcp6-option.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sd-dhcp6-client.h" #include "hash-funcs.h" #include "list.h" #include "macro.h" #include "ordered-set.h" #include "sparse-endian.h" typedef struct sd_dhcp6_option { unsigned n_ref; uint32_t enterprise_identifier; uint16_t option; void *data; size_t length; } sd_dhcp6_option; extern const struct hash_ops dhcp6_option_hash_ops; /* Common option header */ typedef struct DHCP6Option { be16_t code; be16_t len; uint8_t data[]; } _packed_ DHCP6Option; /* Address option */ struct iaaddr { struct in6_addr address; be32_t lifetime_preferred; be32_t lifetime_valid; } _packed_; /* Prefix Delegation Prefix option */ struct iapdprefix { be32_t lifetime_preferred; be32_t lifetime_valid; uint8_t prefixlen; struct in6_addr address; } _packed_; typedef struct DHCP6Address DHCP6Address; struct DHCP6Address { LIST_FIELDS(DHCP6Address, addresses); union { struct iaaddr iaaddr; struct iapdprefix iapdprefix; }; }; struct ia_header { be32_t id; be32_t lifetime_t1; be32_t lifetime_t2; } _packed_; typedef struct DHCP6IA { uint16_t type; struct ia_header header; LIST_HEAD(DHCP6Address, addresses); } DHCP6IA; void dhcp6_ia_clear_addresses(DHCP6IA *ia); DHCP6IA *dhcp6_ia_free(DHCP6IA *ia); DEFINE_TRIVIAL_CLEANUP_FUNC(DHCP6IA*, dhcp6_ia_free); bool dhcp6_option_can_request(uint16_t option); int dhcp6_option_append(uint8_t **buf, size_t *offset, uint16_t code, size_t optlen, const void *optval); int dhcp6_option_append_ia(uint8_t **buf, size_t *offset, const DHCP6IA *ia); int dhcp6_option_append_fqdn(uint8_t **buf, size_t *offset, const char *fqdn); int dhcp6_option_append_user_class(uint8_t **buf, size_t *offset, char * const *user_class); int dhcp6_option_append_vendor_class(uint8_t **buf, size_t *offset, char * const *vendor_class); int dhcp6_option_append_vendor_option(uint8_t **buf, size_t *offset, OrderedSet *vendor_options); int dhcp6_option_parse( const uint8_t *buf, size_t buflen, size_t *offset, uint16_t *ret_option_code, size_t *ret_option_data_len, const uint8_t **ret_option_data); int dhcp6_option_parse_status(const uint8_t *data, size_t data_len, char **ret_status_message); int dhcp6_option_parse_string(const uint8_t *data, size_t data_len, char **ret); int dhcp6_option_parse_ia( sd_dhcp6_client *client, be32_t iaid, uint16_t option_code, size_t option_data_len, const uint8_t *option_data, DHCP6IA **ret); int dhcp6_option_parse_addresses( const uint8_t *optval, size_t optlen, struct in6_addr **addrs, size_t *count); int dhcp6_option_parse_domainname_list(const uint8_t *optval, size_t optlen, char ***ret); int dhcp6_option_parse_domainname(const uint8_t *optval, size_t optlen, char **ret);
3,213
29.320755
97
h
null
systemd-main/src/libsystemd-network/dhcp6-protocol.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "dhcp6-protocol.h" #include "string-table.h" static const char * const dhcp6_state_table[_DHCP6_STATE_MAX] = { [DHCP6_STATE_STOPPED] = "stopped", [DHCP6_STATE_INFORMATION_REQUEST] = "information-request", [DHCP6_STATE_SOLICITATION] = "solicitation", [DHCP6_STATE_REQUEST] = "request", [DHCP6_STATE_BOUND] = "bound", [DHCP6_STATE_RENEW] = "renew", [DHCP6_STATE_REBIND] = "rebind", [DHCP6_STATE_STOPPING] = "stopping", }; DEFINE_STRING_TABLE_LOOKUP_TO_STRING(dhcp6_state, DHCP6State); static const char * const dhcp6_message_type_table[_DHCP6_MESSAGE_TYPE_MAX] = { [DHCP6_MESSAGE_SOLICIT] = "Solicit", [DHCP6_MESSAGE_ADVERTISE] = "Advertise", [DHCP6_MESSAGE_REQUEST] = "Request", [DHCP6_MESSAGE_CONFIRM] = "Confirm", [DHCP6_MESSAGE_RENEW] = "Renew", [DHCP6_MESSAGE_REBIND] = "Rebind", [DHCP6_MESSAGE_REPLY] = "Reply", [DHCP6_MESSAGE_RELEASE] = "Release", [DHCP6_MESSAGE_DECLINE] = "Decline", [DHCP6_MESSAGE_RECONFIGURE] = "Reconfigure", [DHCP6_MESSAGE_INFORMATION_REQUEST] = "Information Request", [DHCP6_MESSAGE_RELAY_FORWARD] = "Relay Forward", [DHCP6_MESSAGE_RELAY_REPLY] = "Relay Reply", [DHCP6_MESSAGE_LEASE_QUERY] = "Lease Query", [DHCP6_MESSAGE_LEASE_QUERY_REPLY] = "Lease Query Reply", [DHCP6_MESSAGE_LEASE_QUERY_DONE] = "Lease Query Done", [DHCP6_MESSAGE_LEASE_QUERY_DATA] = "Lease Query Data", [DHCP6_MESSAGE_RECONFIGURE_REQUEST] = "Reconfigure Request", [DHCP6_MESSAGE_RECONFIGURE_REPLY] = "Reconfigure Reply", [DHCP6_MESSAGE_DHCPV4_QUERY] = "DHCPv4 Query", [DHCP6_MESSAGE_DHCPV4_RESPONSE] = "DHCPv4 Response", [DHCP6_MESSAGE_ACTIVE_LEASE_QUERY] = "Active Lease Query", [DHCP6_MESSAGE_START_TLS] = "Start TLS", [DHCP6_MESSAGE_BINDING_UPDATE] = "Binding Update", [DHCP6_MESSAGE_BINDING_REPLY] = "Binding Reply", [DHCP6_MESSAGE_POOL_REQUEST] = "Pool Request", [DHCP6_MESSAGE_POOL_RESPONSE] = "Pool Response", [DHCP6_MESSAGE_UPDATE_REQUEST] = "Update Request", [DHCP6_MESSAGE_UPDATE_REQUEST_ALL] = "Update Request All", [DHCP6_MESSAGE_UPDATE_DONE] = "Update Done", [DHCP6_MESSAGE_CONNECT] = "Connect", [DHCP6_MESSAGE_CONNECT_REPLY] = "Connect Reply", [DHCP6_MESSAGE_DISCONNECT] = "Disconnect", [DHCP6_MESSAGE_STATE] = "State", [DHCP6_MESSAGE_CONTACT] = "Contact", }; DEFINE_STRING_TABLE_LOOKUP(dhcp6_message_type, DHCP6MessageType); static const char * const dhcp6_message_status_table[_DHCP6_STATUS_MAX] = { [DHCP6_STATUS_SUCCESS] = "Success", [DHCP6_STATUS_UNSPEC_FAIL] = "Unspecified failure", [DHCP6_STATUS_NO_ADDRS_AVAIL] = "No addresses available", [DHCP6_STATUS_NO_BINDING] = "Binding unavailable", [DHCP6_STATUS_NOT_ON_LINK] = "Not on link", [DHCP6_STATUS_USE_MULTICAST] = "Use multicast", [DHCP6_STATUS_NO_PREFIX_AVAIL] = "No prefix available", [DHCP6_STATUS_UNKNOWN_QUERY_TYPE] = "Unknown query type", [DHCP6_STATUS_MALFORMED_QUERY] = "Malformed query", [DHCP6_STATUS_NOT_CONFIGURED] = "Not configured", [DHCP6_STATUS_NOT_ALLOWED] = "Not allowed", [DHCP6_STATUS_QUERY_TERMINATED] = "Query terminated", [DHCP6_STATUS_DATA_MISSING] = "Data missing", [DHCP6_STATUS_CATCHUP_COMPLETE] = "Catch up complete", [DHCP6_STATUS_NOT_SUPPORTED] = "Not supported", [DHCP6_STATUS_TLS_CONNECTION_REFUSED] = "TLS connection refused", [DHCP6_STATUS_ADDRESS_IN_USE] = "Address in use", [DHCP6_STATUS_CONFIGURATION_CONFLICT] = "Configuration conflict", [DHCP6_STATUS_MISSING_BINDING_INFORMATION] = "Missing binding information", [DHCP6_STATUS_OUTDATED_BINDING_INFORMATION] = "Outdated binding information", [DHCP6_STATUS_SERVER_SHUTTING_DOWN] = "Server shutting down", [DHCP6_STATUS_DNS_UPDATE_NOT_SUPPORTED] = "DNS update not supported", [DHCP6_STATUS_EXCESSIVE_TIME_SKEW] = "Excessive time skew", }; DEFINE_STRING_TABLE_LOOKUP(dhcp6_message_status, DHCP6Status); int dhcp6_message_status_to_errno(DHCP6Status s) { switch (s) { case DHCP6_STATUS_SUCCESS: return 0; case DHCP6_STATUS_NO_BINDING: return -EADDRNOTAVAIL; default: return -EINVAL; } }
5,145
52.051546
85
c