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/test/test-lock-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include "fd-util.h" #include "lock-util.h" #include "rm-rf.h" #include "tests.h" #include "tmpfile-util.h" TEST(make_lock_file) { _cleanup_(rm_rf_physical_and_freep) char *t = NULL; _cleanup_close_ int tfd = -EBADF; _cleanup_(release_lock_file) LockFile lock1 = LOCK_FILE_INIT, lock2 = LOCK_FILE_INIT; assert_se((tfd = mkdtemp_open(NULL, 0, &t)) >= 0); assert_se(make_lock_file_at(tfd, "lock", LOCK_EX, &lock1) >= 0); assert_se(faccessat(tfd, "lock", F_OK, 0) >= 0); assert_se(make_lock_file_at(tfd, "lock", LOCK_EX|LOCK_NB, &lock2) == -EBUSY); release_lock_file(&lock1); assert_se(RET_NERRNO(faccessat(tfd, "lock", F_OK, 0)) == -ENOENT); assert_se(make_lock_file_at(tfd, "lock", LOCK_EX, &lock2) >= 0); release_lock_file(&lock2); assert_se(make_lock_file_at(tfd, "lock", LOCK_SH, &lock1) >= 0); assert_se(faccessat(tfd, "lock", F_OK, 0) >= 0); assert_se(make_lock_file_at(tfd, "lock", LOCK_SH, &lock2) >= 0); release_lock_file(&lock1); assert_se(faccessat(tfd, "lock", F_OK, 0) >= 0); release_lock_file(&lock2); assert_se(fchdir(tfd) >= 0); assert_se(make_lock_file_at(tfd, "lock", LOCK_EX, &lock1) >= 0); assert_se(make_lock_file("lock", LOCK_EX|LOCK_NB, &lock2) == -EBUSY); } DEFINE_TEST_MAIN(LOG_INFO);
1,444
37.026316
93
c
null
systemd-main/src/test/test-logarithm.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "logarithm.h" #include "tests.h" TEST(LOG2ULL) { assert_se(LOG2ULL(0) == 0); assert_se(LOG2ULL(1) == 0); assert_se(LOG2ULL(8) == 3); assert_se(LOG2ULL(9) == 3); assert_se(LOG2ULL(15) == 3); assert_se(LOG2ULL(16) == 4); assert_se(LOG2ULL(1024*1024) == 20); assert_se(LOG2ULL(1024*1024+5) == 20); } TEST(CONST_LOG2ULL) { assert_se(CONST_LOG2ULL(0) == 0); assert_se(CONST_LOG2ULL(1) == 0); assert_se(CONST_LOG2ULL(8) == 3); assert_se(CONST_LOG2ULL(9) == 3); assert_se(CONST_LOG2ULL(15) == 3); assert_se(CONST_LOG2ULL(16) == 4); assert_se(CONST_LOG2ULL(1024*1024) == 20); assert_se(CONST_LOG2ULL(1024*1024+5) == 20); } TEST(NONCONST_LOG2ULL) { assert_se(NONCONST_LOG2ULL(0) == 0); assert_se(NONCONST_LOG2ULL(1) == 0); assert_se(NONCONST_LOG2ULL(8) == 3); assert_se(NONCONST_LOG2ULL(9) == 3); assert_se(NONCONST_LOG2ULL(15) == 3); assert_se(NONCONST_LOG2ULL(16) == 4); assert_se(NONCONST_LOG2ULL(1024*1024) == 20); assert_se(NONCONST_LOG2ULL(1024*1024+5) == 20); } TEST(log2u64) { assert_se(log2u64(0) == 0); assert_se(log2u64(1) == 0); assert_se(log2u64(8) == 3); assert_se(log2u64(9) == 3); assert_se(log2u64(15) == 3); assert_se(log2u64(16) == 4); assert_se(log2u64(1024*1024) == 20); assert_se(log2u64(1024*1024+5) == 20); } TEST(log2u) { assert_se(log2u(0) == 0); assert_se(log2u(1) == 0); assert_se(log2u(2) == 1); assert_se(log2u(3) == 1); assert_se(log2u(4) == 2); assert_se(log2u(32) == 5); assert_se(log2u(33) == 5); assert_se(log2u(63) == 5); assert_se(log2u(INT_MAX) == sizeof(int)*8-2); } TEST(log2i) { assert_se(log2i(0) == 0); assert_se(log2i(1) == 0); assert_se(log2i(2) == 1); assert_se(log2i(3) == 1); assert_se(log2i(4) == 2); assert_se(log2i(32) == 5); assert_se(log2i(33) == 5); assert_se(log2i(63) == 5); assert_se(log2i(INT_MAX) == sizeof(int)*8-2); } TEST(popcount) { uint16_t u16a = 0x0000; uint16_t u16b = 0xFFFF; uint32_t u32a = 0x00000010; uint32_t u32b = 0xFFFFFFFF; uint64_t u64a = 0x0000000000000010; uint64_t u64b = 0x0100000000100010; assert_se(popcount(u16a) == 0); assert_se(popcount(u16b) == 16); assert_se(popcount(u32a) == 1); assert_se(popcount(u32b) == 32); assert_se(popcount(u64a) == 1); assert_se(popcount(u64b) == 3); /* This would fail: * error: β€˜_Generic’ selector of type β€˜int’ is not compatible with any association * assert_se(popcount(0x10) == 1); */ } DEFINE_TEST_MAIN(LOG_INFO);
2,926
29.489583
90
c
null
systemd-main/src/test/test-loopback.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sched.h> #include <stdio.h> #include <string.h> #include "errno-util.h" #include "log.h" #include "loopback-setup.h" #include "tests.h" TEST_RET(loopback_setup) { int r; if (unshare(CLONE_NEWUSER | CLONE_NEWNET) < 0) { if (ERRNO_IS_PRIVILEGE(errno) || ERRNO_IS_NOT_SUPPORTED(errno)) { log_notice("Skipping test, lacking privileges or namespaces not supported"); return EXIT_TEST_SKIP; } return log_error_errno(errno, "Failed to create user+network namespace: %m"); } r = loopback_setup(); if (r < 0) return log_error_errno(r, "loopback: %m"); log_info("> ipv6 main"); system("ip -6 route show table main"); log_info("> ipv6 local"); system("ip -6 route show table local"); log_info("> ipv4 main"); system("ip -4 route show table main"); log_info("> ipv4 local"); system("ip -4 route show table local"); return EXIT_SUCCESS; } static int intro(void) { log_show_color(true); return EXIT_SUCCESS; } DEFINE_TEST_MAIN_WITH_INTRO(LOG_INFO, intro);
1,250
26.8
100
c
null
systemd-main/src/test/test-manager.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "manager.h" #include "tests.h" TEST(manager_taint_string) { Manager m = {}; _cleanup_free_ char *a = manager_taint_string(&m); assert_se(a); log_debug("taint string w/o split-usr: '%s'", a); /* split-usr is the only one that is cached in Manager, so we know it's not present. * The others are queried dynamically, so we'd need to duplicate the logic here * to test for them. Let's do just one. */ assert_se(!strstr(a, "split-usr")); if (cg_all_unified() == 0) assert_se(strstr(a, "cgroupsv1")); else assert_se(!strstr(a, "cgroupsv1")); m.taint_usr = true; _cleanup_free_ char *b = manager_taint_string(&m); assert_se(b); log_debug("taint string w/ split-usr: '%s'", b); assert_se(strstr(b, "split-usr")); } DEFINE_TEST_MAIN(LOG_DEBUG);
954
30.833333
92
c
null
systemd-main/src/test/test-math-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <float.h> #include "math-util.h" #include "tests.h" TEST(iszero_safe) { /* zeros */ assert_se(iszero_safe(0.0)); assert_se(iszero_safe(-0.0)); assert_se(iszero_safe(0e0)); assert_se(iszero_safe(-0e0)); assert_se(iszero_safe(0e+0)); assert_se(iszero_safe(0e-0)); assert_se(iszero_safe(-0e-0)); assert_se(iszero_safe(-0e000)); assert_se(iszero_safe(0e000)); /* non-zero normal values */ assert_se(!iszero_safe(42.0)); assert_se(!iszero_safe(M_PI)); assert_se(!iszero_safe(DBL_MAX)); assert_se(!iszero_safe(-DBL_MAX)); assert_se(!iszero_safe(DBL_MIN)); assert_se(!iszero_safe(-DBL_MIN)); assert_se(!iszero_safe(1 / DBL_MAX)); /* subnormal values */ assert_se(!iszero_safe(DBL_MIN / 2)); assert_se(!iszero_safe(-DBL_MIN / 42)); assert_se(!iszero_safe(1 / DBL_MAX / 2)); /* too small values which cannot be in subnormal form */ assert_se( iszero_safe(DBL_MIN / DBL_MAX)); assert_se( iszero_safe(DBL_MIN / -DBL_MAX)); assert_se( iszero_safe(-DBL_MIN / DBL_MAX)); assert_se( iszero_safe(-DBL_MIN / -DBL_MAX)); /* NaN or infinity */ assert_se(!iszero_safe(NAN)); assert_se(!iszero_safe(INFINITY)); assert_se(!iszero_safe(-INFINITY)); assert_se(!iszero_safe(1 / NAN)); /* inverse of infinity */ assert_se( iszero_safe(1 / INFINITY)); assert_se( iszero_safe(1 / -INFINITY)); assert_se( iszero_safe(-1 / INFINITY)); assert_se( iszero_safe(-1 / -INFINITY)); assert_se( iszero_safe(42 / -INFINITY)); assert_se( iszero_safe(-42 / -INFINITY)); assert_se( iszero_safe(DBL_MIN / INFINITY)); assert_se( iszero_safe(DBL_MIN / -INFINITY)); assert_se( iszero_safe(DBL_MAX / INFINITY / 2)); assert_se( iszero_safe(DBL_MAX / -INFINITY * DBL_MAX)); /* infinity / infinity is NaN */ assert_se(!iszero_safe(INFINITY / INFINITY)); assert_se(!iszero_safe(INFINITY * 2 / INFINITY)); assert_se(!iszero_safe(INFINITY / DBL_MAX / INFINITY)); } TEST(fp_equal) { /* normal values */ assert_se( fp_equal(0.0, -0e0)); assert_se( fp_equal(3.0, 3)); assert_se(!fp_equal(3.000001, 3)); assert_se( fp_equal(M_PI, M_PI)); assert_se(!fp_equal(M_PI, -M_PI)); assert_se( fp_equal(DBL_MAX, DBL_MAX)); assert_se(!fp_equal(DBL_MAX, -DBL_MAX)); assert_se(!fp_equal(-DBL_MAX, DBL_MAX)); assert_se( fp_equal(-DBL_MAX, -DBL_MAX)); assert_se( fp_equal(DBL_MIN, DBL_MIN)); assert_se(!fp_equal(DBL_MIN, -DBL_MIN)); assert_se(!fp_equal(-DBL_MIN, DBL_MIN)); assert_se( fp_equal(-DBL_MIN, -DBL_MIN)); /* subnormal values */ assert_se( fp_equal(DBL_MIN / 10, DBL_MIN / 10)); assert_se(!fp_equal(DBL_MIN / 10, -DBL_MIN / 10)); assert_se(!fp_equal(-DBL_MIN / 10, DBL_MIN / 10)); assert_se( fp_equal(-DBL_MIN / 10, -DBL_MIN / 10)); assert_se(!fp_equal(DBL_MIN / 10, DBL_MIN / 15)); assert_se(!fp_equal(DBL_MIN / 10, DBL_MIN / 15)); /* subnormal difference */ assert_se(!fp_equal(DBL_MIN / 10, DBL_MIN + DBL_MIN / 10)); assert_se( fp_equal(3.0, 3.0 + DBL_MIN / 2)); /* 3.0 + DBL_MIN / 2 is truncated to 3.0 */ /* too small values */ assert_se( fp_equal(DBL_MIN / DBL_MAX, -DBL_MIN / DBL_MAX)); /* NaN or infinity */ assert_se(!fp_equal(NAN, NAN)); assert_se(!fp_equal(NAN, 0)); assert_se(!fp_equal(NAN, INFINITY)); assert_se(!fp_equal(INFINITY, INFINITY)); assert_se(!fp_equal(INFINITY, -INFINITY)); assert_se(!fp_equal(-INFINITY, INFINITY)); assert_se(!fp_equal(-INFINITY, -INFINITY)); /* inverse of infinity */ assert_se( fp_equal(0, 1 / INFINITY)); assert_se( fp_equal(42 / INFINITY, 1 / -INFINITY)); assert_se(!fp_equal(42 / INFINITY, INFINITY / INFINITY)); } DEFINE_TEST_MAIN(LOG_DEBUG);
4,185
36.711712
97
c
null
systemd-main/src/test/test-memfd-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include "errno-util.h" #include "fd-util.h" #include "memfd-util.h" #include "string-util.h" #include "tests.h" TEST(memfd_get_sealed) { #define TEST_TEXT "this is some random test text we are going to write to a memfd" _cleanup_close_ int fd = -EBADF; fd = memfd_new("test-memfd-get-sealed"); if (fd < 0) { assert_se(ERRNO_IS_NOT_SUPPORTED(fd)); return; } assert_se(write(fd, TEST_TEXT, strlen(TEST_TEXT)) == strlen(TEST_TEXT)); /* we'll leave the read offset at the end of the memfd, the fdopen_independent() descriptors should * start at the beginning anyway */ assert_se(memfd_get_sealed(fd) == 0); assert_se(memfd_set_sealed(fd) >= 0); assert_se(memfd_get_sealed(fd) > 0); } DEFINE_TEST_MAIN(LOG_DEBUG);
899
28.032258
107
c
null
systemd-main/src/test/test-memory-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "memory-util.h" #include "tests.h" TEST(eqzero) { const uint32_t zeros[] = {0, 0, 0}; const uint32_t ones[] = {1, 1}; const uint32_t mixed[] = {0, 1, 0, 0, 0}; const uint8_t longer[] = {[55] = 255}; assert_se(eqzero(zeros)); assert_se(!eqzero(ones)); assert_se(!eqzero(mixed)); assert_se(!eqzero(longer)); } static void my_destructor(struct iovec *iov, size_t n) { /* not really a destructor, just something we can use to check if the destruction worked */ memset(iov, 'y', sizeof(struct iovec) * n); } TEST(cleanup_array) { struct iovec *iov, *saved_iov; size_t n, saved_n; n = 7; iov = new(struct iovec, n); assert_se(iov); memset(iov, 'x', sizeof(struct iovec) * n); saved_iov = iov; saved_n = n; { assert_se(memeqbyte('x', saved_iov, sizeof(struct iovec) * saved_n)); assert_se(iov); assert_se(n > 0); CLEANUP_ARRAY(iov, n, my_destructor); assert_se(memeqbyte('x', saved_iov, sizeof(struct iovec) * saved_n)); assert_se(iov); assert_se(n > 0); } assert_se(memeqbyte('y', saved_iov, sizeof(struct iovec) * saved_n)); assert_se(!iov); assert_se(n == 0); free(saved_iov); } DEFINE_TEST_MAIN(LOG_INFO);
1,479
25.428571
99
c
null
systemd-main/src/test/test-mempool.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "mempool.h" #include "random-util.h" #include "tests.h" struct element { uint64_t value; }; DEFINE_MEMPOOL(test_mempool, struct element, 8); TEST(mempool_trim) { #define NN 4000 struct element *a[NN]; size_t n_freed = 0; assert_se(!test_mempool.first_pool); assert_se(!test_mempool.freelist); mempool_trim(&test_mempool); for (size_t i = 0; i < NN; i++) { assert_se(a[i] = mempool_alloc_tile(&test_mempool)); a[i]->value = i; } mempool_trim(&test_mempool); /* free up to one third randomly */ size_t x = 0; for (size_t i = 0; i < NN/3; i++) { x = (x + random_u64()) % ELEMENTSOF(a); assert_se(!a[x] || a[x]->value == x); if (a[x]) n_freed ++; a[x] = mempool_free_tile(&test_mempool, a[x]); } mempool_trim(&test_mempool); /* free definitely at least one third */ for (size_t i = 2; i < NN; i += 3) { assert_se(!a[i] || a[i]->value == i); if (a[i]) n_freed ++; a[i] = mempool_free_tile(&test_mempool, a[i]); } mempool_trim(&test_mempool); /* Allocate another set of tiles, which will fill up the free list and allocate some new tiles */ struct element *b[NN]; for (size_t i = 0; i < NN; i++) { assert_se(b[i] = mempool_alloc_tile(&test_mempool)); b[i]->value = ~(uint64_t) i; } mempool_trim(&test_mempool); /* free everything from the original set*/ for (size_t i = 0; i < NN; i += 1) { assert_se(!a[i] || a[i]->value == i); if (a[i]) n_freed ++; a[i] = mempool_free_tile(&test_mempool, a[i]); } mempool_trim(&test_mempool); /* and now everything from the second set too */ for (size_t i = 0; i < NN; i += 1) { assert_se(!b[i] || b[i]->value == ~(uint64_t) i); if (b[i]) n_freed ++; b[i] = mempool_free_tile(&test_mempool, b[i]); } assert_se(n_freed == NN * 2); mempool_trim(&test_mempool); assert_se(!test_mempool.first_pool); assert_se(!test_mempool.freelist); } DEFINE_TEST_MAIN(LOG_DEBUG);
2,516
26.064516
105
c
null
systemd-main/src/test/test-mkdir.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include "capability-util.h" #include "fs-util.h" #include "mkdir.h" #include "path-util.h" #include "process-util.h" #include "rm-rf.h" #include "stat-util.h" #include "tests.h" #include "tmpfile-util.h" #include "user-util.h" TEST(mkdir_p_safe) { _cleanup_(rm_rf_physical_and_freep) char *tmp = NULL; _cleanup_free_ char *p = NULL, *q = NULL; int r; assert_se(mkdtemp_malloc("/tmp/test-mkdir-XXXXXX", &tmp) >= 0); assert_se(p = path_join(tmp, "run/aaa/bbb")); assert_se(mkdir_p(p, 0755) >= 0); assert_se(is_dir(p, false) > 0); assert_se(is_dir(p, true) > 0); p = mfree(p); assert_se(p = path_join(tmp, "run/ccc/ddd")); assert_se(mkdir_p_safe(tmp, p, 0755, UID_INVALID, GID_INVALID, 0) >= 0); assert_se(is_dir(p, false) > 0); assert_se(is_dir(p, true) > 0); p = mfree(p); assert_se(p = path_join(tmp, "var/run")); assert_se(mkdir_parents_safe(tmp, p, 0755, UID_INVALID, GID_INVALID, 0) >= 0); assert_se(symlink("../run", p) >= 0); assert_se(is_dir(p, false) == 0); assert_se(is_dir(p, true) > 0); assert_se(mkdir_safe(p, 0755, UID_INVALID, GID_INVALID, 0) == -ENOTDIR); assert_se(mkdir_safe(p, 0755, UID_INVALID, GID_INVALID, MKDIR_IGNORE_EXISTING) >= 0); assert_se(mkdir_safe(p, 0755, UID_INVALID, GID_INVALID, MKDIR_FOLLOW_SYMLINK) >= 0); assert_se(is_dir(p, false) == 0); assert_se(is_dir(p, true) > 0); p = mfree(p); assert_se(p = path_join(tmp, "var/run/hoge/foo/baz")); assert_se(mkdir_p_safe(tmp, p, 0755, UID_INVALID, GID_INVALID, 0) >= 0); assert_se(is_dir(p, false) > 0); assert_se(is_dir(p, true) > 0); p = mfree(p); assert_se(p = path_join(tmp, "not-exists")); assert_se(q = path_join(p, "aaa")); assert_se(mkdir_p_safe(p, q, 0755, UID_INVALID, GID_INVALID, 0) == -ENOENT); p = mfree(p); q = mfree(q); assert_se(p = path_join(tmp, "regular-file")); assert_se(q = path_join(p, "aaa")); assert_se(touch(p) >= 0); assert_se(mkdir_p_safe(p, q, 0755, UID_INVALID, GID_INVALID, 0) == -ENOTDIR); p = mfree(p); q = mfree(q); assert_se(p = path_join(tmp, "symlink")); assert_se(q = path_join(p, "hoge/foo")); assert_se(symlink("aaa", p) >= 0); assert_se(mkdir_p_safe(tmp, q, 0755, UID_INVALID, GID_INVALID, 0) >= 0); assert_se(is_dir(q, false) > 0); assert_se(is_dir(q, true) > 0); q = mfree(q); assert_se(q = path_join(tmp, "aaa/hoge/foo")); assert_se(is_dir(q, false) > 0); assert_se(is_dir(q, true) > 0); assert_se(mkdir_p_safe(tmp, "/tmp/test-mkdir-outside", 0755, UID_INVALID, GID_INVALID, 0) == -ENOTDIR); p = mfree(p); assert_se(p = path_join(tmp, "zero-mode/should-fail-to-create-child")); assert_se(mkdir_parents_safe(tmp, p, 0000, UID_INVALID, GID_INVALID, 0) >= 0); r = safe_fork("(test-mkdir-no-cap)", FORK_DEATHSIG | FORK_WAIT | FORK_LOG, NULL); if (r == 0) { (void) capability_bounding_set_drop(0, /* right_now = */ true); assert_se(mkdir_p_safe(tmp, p, 0000, UID_INVALID, GID_INVALID, 0) == -EACCES); _exit(EXIT_SUCCESS); } assert_se(r >= 0); } TEST(mkdir_p_root) { _cleanup_(rm_rf_physical_and_freep) char *tmp = NULL; _cleanup_free_ char *p = NULL; assert_se(mkdtemp_malloc("/tmp/test-mkdir-XXXXXX", &tmp) >= 0); assert_se(p = path_join(tmp, "run/aaa/bbb")); assert_se(mkdir_p_root(tmp, "/run/aaa/bbb", UID_INVALID, GID_INVALID, 0755) >= 0); assert_se(is_dir(p, false) > 0); assert_se(is_dir(p, true) > 0); p = mfree(p); assert_se(p = path_join(tmp, "var/run")); assert_se(mkdir_parents_safe(tmp, p, 0755, UID_INVALID, GID_INVALID, 0) >= 0); assert_se(symlink("../run", p) >= 0); assert_se(is_dir(p, false) == 0); assert_se(is_dir(p, true) > 0); p = mfree(p); assert_se(p = path_join(tmp, "var/run/hoge/foo/baz")); assert_se(mkdir_p_root(tmp, "/var/run/hoge/foo/baz", UID_INVALID, GID_INVALID, 0755) >= 0); assert_se(is_dir(p, false) > 0); assert_se(is_dir(p, true) > 0); p = mfree(p); assert_se(p = path_join(tmp, "not-exists")); assert_se(mkdir_p_root(p, "/aaa", UID_INVALID, GID_INVALID, 0755) == -ENOENT); p = mfree(p); assert_se(p = path_join(tmp, "regular-file")); assert_se(touch(p) >= 0); assert_se(mkdir_p_root(p, "/aaa", UID_INVALID, GID_INVALID, 0755) == -ENOTDIR); /* FIXME: The tests below do not work. p = mfree(p); assert_se(p = path_join(tmp, "symlink")); assert_se(symlink("aaa", p) >= 0); assert_se(mkdir_p_root(tmp, "/symlink/hoge/foo", UID_INVALID, GID_INVALID, 0755) >= 0); p = mfree(p); assert_se(p = path_join(tmp, "symlink/hoge/foo")); assert_se(is_dir(p, false) > 0); assert_se(is_dir(p, true) > 0); p = mfree(p); assert_se(p = path_join(tmp, "aaa/hoge/foo")); assert_se(is_dir(p, false) > 0); assert_se(is_dir(p, true) > 0); */ } DEFINE_TEST_MAIN(LOG_DEBUG);
5,430
37.246479
111
c
null
systemd-main/src/test/test-memstream-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "memstream-util.h" #include "string-util.h" #include "tests.h" TEST(memstream_done) { _cleanup_(memstream_done) MemStream m = {}; assert_se(memstream_init(&m)); } TEST(memstream_empty) { _cleanup_(memstream_done) MemStream m = {}; _cleanup_free_ char *buf = NULL; size_t sz; assert_se(memstream_init(&m)); assert_se(memstream_finalize(&m, &buf, &sz) >= 0); assert_se(streq(buf, "")); assert_se(sz == 0); } TEST(memstream) { _cleanup_(memstream_done) MemStream m = {}; _cleanup_free_ char *buf = NULL; size_t sz; FILE *f; assert_se(f = memstream_init(&m)); fputs("hoge", f); fputs("γŠγ―γ‚ˆγ†οΌ", f); fputs(u8"πŸ˜€πŸ˜€πŸ˜€", f); assert_se(memstream_finalize(&m, &buf, &sz) >= 0); assert_se(streq(buf, u8"hogeγŠγ―γ‚ˆγ†οΌπŸ˜€πŸ˜€πŸ˜€")); assert_se(sz == strlen(u8"hogeγŠγ―γ‚ˆγ†οΌπŸ˜€πŸ˜€πŸ˜€")); buf = mfree(buf); assert_se(f = memstream_init(&m)); fputs("second", f); assert_se(memstream_finalize(&m, &buf, &sz) >= 0); assert_se(streq(buf, "second")); assert_se(sz == strlen("second")); } TEST(memstream_dump) { _cleanup_(memstream_done) MemStream m = {}; FILE *f; assert_se(f = memstream_init(&m)); fputs("first", f); assert_se(memstream_dump(LOG_DEBUG, &m) >= 0); assert_se(f = memstream_init(&m)); fputs("second", f); assert_se(memstream_dump(LOG_DEBUG, &m) >= 0); } DEFINE_TEST_MAIN(LOG_DEBUG);
1,594
25.147541
58
c
null
systemd-main/src/test/test-modhex.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "recovery-key.h" #include "alloc-util.h" #include "string-util.h" #include "tests.h" static void test_normalize_recovery_key(const char *t, const char *expected) { _cleanup_free_ char *z = NULL; int r; assert_se(t); r = normalize_recovery_key(t, &z); assert_se(expected ? (r >= 0 && streq(z, expected)) : (r == -EINVAL && z == NULL)); } TEST(normalize_recovery_key_all) { test_normalize_recovery_key("iefgcelh-biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj", "iefgcelh-biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj"); test_normalize_recovery_key("iefgcelhbiduvkjvcjvuncnkvlfchdidjhtuhhdeurkllkegilkjgbrthjkbgktj", "iefgcelh-biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj"); test_normalize_recovery_key("IEFGCELH-BIDUVKJV-CJVUNCNK-VLFCHDID-JHTUHHDE-URKLLKEG-ILKJGBRT-HJKBGKTJ", "iefgcelh-biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj"); test_normalize_recovery_key("IEFGCELHBIDUVKJVCJVUNCNKVLFCHDIDJHTUHHDEURKLLKEGILKJGBRTHJKBGKTJ", "iefgcelh-biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj"); test_normalize_recovery_key("Iefgcelh-Biduvkjv-Cjvuncnk-Vlfchdid-Jhtuhhde-Urkllkeg-Ilkjgbrt-Hjkbgktj", "iefgcelh-biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj"); test_normalize_recovery_key("Iefgcelhbiduvkjvcjvuncnkvlfchdidjhtuhhdeurkllkegilkjgbrthjkbgktj", "iefgcelh-biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj"); test_normalize_recovery_key("iefgcelh-biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgkt", NULL); test_normalize_recovery_key("iefgcelhbiduvkjvcjvuncnkvlfchdidjhtuhhdeurkllkegilkjgbrthjkbgkt", NULL); test_normalize_recovery_key("IEFGCELHBIDUVKJVCJVUNCNKVLFCHDIDJHTUHHDEURKLLKEGILKJGBRTHJKBGKT", NULL); test_normalize_recovery_key("xefgcelh-biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj", NULL); test_normalize_recovery_key("Xefgcelh-biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj", NULL); test_normalize_recovery_key("iefgcelh+biduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj", NULL); test_normalize_recovery_key("iefgcelhebiduvkjv-cjvuncnk-vlfchdid-jhtuhhde-urkllkeg-ilkjgbrt-hjkbgktj", NULL); test_normalize_recovery_key("", NULL); } DEFINE_TEST_MAIN(LOG_INFO);
2,723
51.384615
117
c
null
systemd-main/src/test/test-net-naming-scheme.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "netif-naming-scheme.h" #include "string-util.h" #include "tests.h" TEST(default_net_naming_scheme) { const NamingScheme *n; assert_se(n = naming_scheme_from_name(DEFAULT_NET_NAMING_SCHEME)); log_info("default β†’ %s", n->name); } TEST(naming_scheme_conversions) { const NamingScheme *n; assert_se(n = naming_scheme_from_name("latest")); log_info("latest β†’ %s", n->name); assert_se(n = naming_scheme_from_name("v238")); assert_se(streq(n->name, "v238")); } DEFINE_TEST_MAIN(LOG_INFO);
610
25.565217
74
c
null
systemd-main/src/test/test-netlink-manual.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <arpa/inet.h> #include <linux/if_tunnel.h> #include <linux/ip.h> #include <sys/types.h> #include <unistd.h> #include "sd-netlink.h" #include "macro.h" #include "module-util.h" #include "tests.h" static int load_module(const char *mod_name) { _cleanup_(kmod_unrefp) struct kmod_ctx *ctx = NULL; _cleanup_(kmod_module_unref_listp) struct kmod_list *list = NULL; struct kmod_list *l; int r; ctx = kmod_new(NULL, NULL); if (!ctx) return log_oom(); r = kmod_module_new_from_lookup(ctx, mod_name, &list); if (r < 0) return r; kmod_list_foreach(l, list) { _cleanup_(kmod_module_unrefp) struct kmod_module *mod = NULL; mod = kmod_module_get_module(l); r = kmod_module_probe_insert_module(mod, 0, NULL, NULL, NULL, NULL); if (r > 0) r = -EINVAL; } return r; } static int test_tunnel_configure(sd_netlink *rtnl) { int r; sd_netlink_message *m, *n; struct in_addr local, remote; /* skip test if module cannot be loaded */ r = load_module("ipip"); if (r < 0) return log_tests_skipped_errno(r, "failed to load module 'ipip'"); r = load_module("sit"); if (r < 0) return log_tests_skipped_errno(r, "failed to load module 'sit'"); if (getuid() != 0) return log_tests_skipped("not root"); /* IPIP tunnel */ assert_se(sd_rtnl_message_new_link(rtnl, &m, RTM_NEWLINK, 0) >= 0); assert_se(m); assert_se(sd_netlink_message_append_string(m, IFLA_IFNAME, "ipip-tunnel") >= 0); assert_se(sd_netlink_message_append_u32(m, IFLA_MTU, 1234)>= 0); assert_se(sd_netlink_message_open_container(m, IFLA_LINKINFO) >= 0); assert_se(sd_netlink_message_open_container_union(m, IFLA_INFO_DATA, "ipip") >= 0); inet_pton(AF_INET, "192.168.21.1", &local.s_addr); assert_se(sd_netlink_message_append_u32(m, IFLA_IPTUN_LOCAL, local.s_addr) >= 0); inet_pton(AF_INET, "192.168.21.2", &remote.s_addr); assert_se(sd_netlink_message_append_u32(m, IFLA_IPTUN_REMOTE, remote.s_addr) >= 0); assert_se(sd_netlink_message_close_container(m) >= 0); assert_se(sd_netlink_message_close_container(m) >= 0); assert_se(sd_netlink_call(rtnl, m, -1, 0) == 1); assert_se((m = sd_netlink_message_unref(m)) == NULL); /* sit */ assert_se(sd_rtnl_message_new_link(rtnl, &n, RTM_NEWLINK, 0) >= 0); assert_se(n); assert_se(sd_netlink_message_append_string(n, IFLA_IFNAME, "sit-tunnel") >= 0); assert_se(sd_netlink_message_append_u32(n, IFLA_MTU, 1234)>= 0); assert_se(sd_netlink_message_open_container(n, IFLA_LINKINFO) >= 0); assert_se(sd_netlink_message_open_container_union(n, IFLA_INFO_DATA, "sit") >= 0); assert_se(sd_netlink_message_append_u8(n, IFLA_IPTUN_PROTO, IPPROTO_IPIP) >= 0); inet_pton(AF_INET, "192.168.21.3", &local.s_addr); assert_se(sd_netlink_message_append_u32(n, IFLA_IPTUN_LOCAL, local.s_addr) >= 0); inet_pton(AF_INET, "192.168.21.4", &remote.s_addr); assert_se(sd_netlink_message_append_u32(n, IFLA_IPTUN_REMOTE, remote.s_addr) >= 0); assert_se(sd_netlink_message_close_container(n) >= 0); assert_se(sd_netlink_message_close_container(n) >= 0); assert_se(sd_netlink_call(rtnl, n, -1, 0) == 1); assert_se((n = sd_netlink_message_unref(n)) == NULL); return EXIT_SUCCESS; } int main(int argc, char *argv[]) { sd_netlink *rtnl; int r; test_setup_logging(LOG_INFO); assert_se(sd_netlink_open(&rtnl) >= 0); assert_se(rtnl); r = test_tunnel_configure(rtnl); assert_se((rtnl = sd_netlink_unref(rtnl)) == NULL); return r; }
4,018
30.645669
91
c
null
systemd-main/src/test/test-nss-hosts.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <net/if.h> #include <stdlib.h> #include <unistd.h> #include "af-list.h" #include "alloc-util.h" #include "dlfcn-util.h" #include "env-util.h" #include "errno-list.h" #include "format-util.h" #include "hexdecoct.h" #include "hostname-util.h" #include "in-addr-util.h" #include "local-addresses.h" #include "log.h" #include "main-func.h" #include "nss-test-util.h" #include "nss-util.h" #include "parse-util.h" #include "path-util.h" #include "socket-util.h" #include "stdio-util.h" #include "string-util.h" #include "strv.h" #include "tests.h" static size_t arg_bufsize = 1024; static const char* af_to_string(int family, char *buf, size_t buf_len) { const char *name; if (family == AF_UNSPEC) return "*"; name = af_to_name(family); if (name) return name; (void) snprintf(buf, buf_len, "%i", family); return buf; } static int print_gaih_addrtuples(const struct gaih_addrtuple *tuples) { int r, n = 0; for (const struct gaih_addrtuple *it = tuples; it; it = it->next) { _cleanup_free_ char *a = NULL; union in_addr_union u; char family_name[DECIMAL_STR_MAX(int)]; memcpy(&u, it->addr, 16); r = in_addr_to_string(it->family, &u, &a); assert_se(IN_SET(r, 0, -EAFNOSUPPORT)); if (r == -EAFNOSUPPORT) assert_se(a = hexmem(it->addr, 16)); log_info(" \"%s\" %s %s %s", it->name, af_to_string(it->family, family_name, sizeof family_name), a, FORMAT_IFNAME_FULL(it->scopeid, FORMAT_IFNAME_IFINDEX_WITH_PERCENT)); n++; } return n; } static void print_struct_hostent(struct hostent *host, const char *canon) { log_info(" \"%s\"", host->h_name); STRV_FOREACH(s, host->h_aliases) log_info(" alias \"%s\"", *s); STRV_FOREACH(s, host->h_addr_list) { union in_addr_union u; _cleanup_free_ char *a = NULL; char family_name[DECIMAL_STR_MAX(int)]; int r; assert_se((unsigned) host->h_length == FAMILY_ADDRESS_SIZE(host->h_addrtype)); memcpy(&u, *s, host->h_length); r = in_addr_to_string(host->h_addrtype, &u, &a); assert_se(r == 0); log_info(" %s %s", af_to_string(host->h_addrtype, family_name, sizeof family_name), a); } if (canon) log_info(" canonical: \"%s\"", canon); } static void test_gethostbyname4_r(void *handle, const char *module, const char *name) { const char *fname; _nss_gethostbyname4_r_t f; char buffer[arg_bufsize]; struct gaih_addrtuple *pat = NULL; int errno1 = 999, errno2 = 999; /* nss-dns doesn't set those */ int32_t ttl = INT32_MAX; /* nss-dns wants to return the lowest ttl, and will access this variable through *ttlp, so we need to set it to something. I'm not sure if this is a bug in nss-dns or not. */ enum nss_status status; char pretty_status[DECIMAL_STR_MAX(enum nss_status)]; int n; fname = strjoina("_nss_", module, "_gethostbyname4_r"); f = dlsym(handle, fname); log_debug("dlsym(0x%p, %s) β†’ 0x%p", handle, fname, f); if (!f) { log_info("%s not defined", fname); return; } status = f(name, &pat, buffer, sizeof buffer, &errno1, &errno2, &ttl); if (status == NSS_STATUS_SUCCESS) { log_info("%s(\"%s\") β†’ status=%s%-20spat=buffer+0x%"PRIxPTR" errno=%d/%s h_errno=%d/%s ttl=%"PRIi32, fname, name, nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", pat ? (uintptr_t) pat - (uintptr_t) buffer : 0, errno1, errno_to_name(errno1) ?: "---", errno2, hstrerror(errno2), ttl); n = print_gaih_addrtuples(pat); } else { log_info("%s(\"%s\") β†’ status=%s%-20spat=0x%p errno=%d/%s h_errno=%d/%s", fname, name, nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", pat, errno1, errno_to_name(errno1) ?: "---", errno2, hstrerror(errno2)); n = 0; } if (STR_IN_SET(module, "resolve", "mymachines") && status == NSS_STATUS_UNAVAIL) return; if (streq(name, "localhost")) { if (streq(module, "myhostname")) { assert_se(status == NSS_STATUS_SUCCESS); assert_se(n == socket_ipv6_is_enabled() + 1); } else if (streq(module, "resolve") && getenv_bool_secure("SYSTEMD_NSS_RESOLVE_SYNTHESIZE") != 0) { assert_se(status == NSS_STATUS_SUCCESS); if (socket_ipv6_is_enabled()) assert_se(n == 2); else assert_se(n <= 2); /* Even if IPv6 is disabled, /etc/hosts may contain ::1. */ } } } static void test_gethostbyname3_r(void *handle, const char *module, const char *name, int af) { const char *fname; _nss_gethostbyname3_r_t f; char buffer[arg_bufsize]; int errno1 = 999, errno2 = 999; /* nss-dns doesn't set those */ int32_t ttl = INT32_MAX; /* nss-dns wants to return the lowest ttl, and will access this variable through *ttlp, so we need to set it to something. I'm not sure if this is a bug in nss-dns or not. */ enum nss_status status; char pretty_status[DECIMAL_STR_MAX(enum nss_status)]; struct hostent host; char *canon; char family_name[DECIMAL_STR_MAX(int)]; fname = strjoina("_nss_", module, "_gethostbyname3_r"); f = dlsym(handle, fname); log_debug("dlsym(0x%p, %s) β†’ 0x%p", handle, fname, f); if (!f) { log_info("%s not defined", fname); return; } status = f(name, af, &host, buffer, sizeof buffer, &errno1, &errno2, &ttl, &canon); log_info("%s(\"%s\", %s) β†’ status=%s%-20serrno=%d/%s h_errno=%d/%s ttl=%"PRIi32, fname, name, af_to_string(af, family_name, sizeof family_name), nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", errno1, errno_to_name(errno1) ?: "---", errno2, hstrerror(errno2), ttl); if (status == NSS_STATUS_SUCCESS) print_struct_hostent(&host, canon); } static void test_gethostbyname2_r(void *handle, const char *module, const char *name, int af) { const char *fname; _nss_gethostbyname2_r_t f; char buffer[arg_bufsize]; int errno1 = 999, errno2 = 999; /* nss-dns doesn't set those */ enum nss_status status; char pretty_status[DECIMAL_STR_MAX(enum nss_status)]; struct hostent host; char family_name[DECIMAL_STR_MAX(int)]; fname = strjoina("_nss_", module, "_gethostbyname2_r"); f = dlsym(handle, fname); log_debug("dlsym(0x%p, %s) β†’ 0x%p", handle, fname, f); if (!f) { log_info("%s not defined", fname); return; } status = f(name, af, &host, buffer, sizeof buffer, &errno1, &errno2); log_info("%s(\"%s\", %s) β†’ status=%s%-20serrno=%d/%s h_errno=%d/%s", fname, name, af_to_string(af, family_name, sizeof family_name), nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", errno1, errno_to_name(errno1) ?: "---", errno2, hstrerror(errno2)); if (status == NSS_STATUS_SUCCESS) print_struct_hostent(&host, NULL); } static void test_gethostbyname_r(void *handle, const char *module, const char *name) { const char *fname; _nss_gethostbyname_r_t f; char buffer[arg_bufsize]; int errno1 = 999, errno2 = 999; /* nss-dns doesn't set those */ enum nss_status status; char pretty_status[DECIMAL_STR_MAX(enum nss_status)]; struct hostent host; fname = strjoina("_nss_", module, "_gethostbyname_r"); f = dlsym(handle, fname); log_debug("dlsym(0x%p, %s) β†’ 0x%p", handle, fname, f); if (!f) { log_info("%s not defined", fname); return; } status = f(name, &host, buffer, sizeof buffer, &errno1, &errno2); log_info("%s(\"%s\") β†’ status=%s%-20serrno=%d/%s h_errno=%d/%s", fname, name, nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", errno1, errno_to_name(errno1) ?: "---", errno2, hstrerror(errno2)); if (status == NSS_STATUS_SUCCESS) print_struct_hostent(&host, NULL); } static void test_gethostbyaddr2_r(void *handle, const char *module, const void* addr, socklen_t len, int af) { const char *fname; _nss_gethostbyaddr2_r_t f; char buffer[arg_bufsize]; int errno1 = 999, errno2 = 999; /* nss-dns doesn't set those */ enum nss_status status; char pretty_status[DECIMAL_STR_MAX(enum nss_status)]; struct hostent host; int32_t ttl = INT32_MAX; _cleanup_free_ char *addr_pretty = NULL; fname = strjoina("_nss_", module, "_gethostbyaddr2_r"); f = dlsym(handle, fname); log_full_errno(f ? LOG_DEBUG : LOG_INFO, errno, "dlsym(0x%p, %s) β†’ 0x%p: %m", handle, fname, f); if (!f) { log_info("%s not defined", fname); return; } assert_se(in_addr_to_string(af, addr, &addr_pretty) >= 0); status = f(addr, len, af, &host, buffer, sizeof buffer, &errno1, &errno2, &ttl); log_info("%s(\"%s\") β†’ status=%s%-20serrno=%d/%s h_errno=%d/%s ttl=%"PRIi32, fname, addr_pretty, nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", errno1, errno_to_name(errno1) ?: "---", errno2, hstrerror(errno2), ttl); if (status == NSS_STATUS_SUCCESS) print_struct_hostent(&host, NULL); } static void test_gethostbyaddr_r(void *handle, const char *module, const void* addr, socklen_t len, int af) { const char *fname; _nss_gethostbyaddr_r_t f; char buffer[arg_bufsize]; int errno1 = 999, errno2 = 999; /* nss-dns doesn't set those */ enum nss_status status; char pretty_status[DECIMAL_STR_MAX(enum nss_status)]; struct hostent host; _cleanup_free_ char *addr_pretty = NULL; fname = strjoina("_nss_", module, "_gethostbyaddr_r"); f = dlsym(handle, fname); log_full_errno(f ? LOG_DEBUG : LOG_INFO, errno, "dlsym(0x%p, %s) β†’ 0x%p: %m", handle, fname, f); if (!f) { log_info("%s not defined", fname); return; } assert_se(in_addr_to_string(af, addr, &addr_pretty) >= 0); status = f(addr, len, af, &host, buffer, sizeof buffer, &errno1, &errno2); log_info("%s(\"%s\") β†’ status=%s%-20serrno=%d/%s h_errno=%d/%s", fname, addr_pretty, nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", errno1, errno_to_name(errno1) ?: "---", errno2, hstrerror(errno2)); if (status == NSS_STATUS_SUCCESS) print_struct_hostent(&host, NULL); } static void test_byname(void *handle, const char *module, const char *name) { test_gethostbyname4_r(handle, module, name); puts(""); test_gethostbyname3_r(handle, module, name, AF_INET); puts(""); test_gethostbyname3_r(handle, module, name, AF_INET6); puts(""); test_gethostbyname3_r(handle, module, name, AF_UNSPEC); puts(""); test_gethostbyname3_r(handle, module, name, AF_UNIX); puts(""); test_gethostbyname2_r(handle, module, name, AF_INET); puts(""); test_gethostbyname2_r(handle, module, name, AF_INET6); puts(""); test_gethostbyname2_r(handle, module, name, AF_UNSPEC); puts(""); test_gethostbyname2_r(handle, module, name, AF_UNIX); puts(""); test_gethostbyname_r(handle, module, name); puts(""); } static void test_byaddr(void *handle, const char *module, const void* addr, socklen_t len, int af) { test_gethostbyaddr2_r(handle, module, addr, len, af); puts(""); test_gethostbyaddr_r(handle, module, addr, len, af); puts(""); } static int make_addresses(struct local_address **addresses) { int n; _cleanup_free_ struct local_address *addrs = NULL; n = local_addresses(NULL, 0, AF_UNSPEC, &addrs); if (n < 0) log_info_errno(n, "Failed to query local addresses: %m"); assert_se(GREEDY_REALLOC(addrs, n + 3)); addrs[n++] = (struct local_address) { .family = AF_INET, .address.in = { htobe32(0x7F000001) } }; addrs[n++] = (struct local_address) { .family = AF_INET, .address.in = { htobe32(0x7F000002) } }; addrs[n++] = (struct local_address) { .family = AF_INET6, .address.in6 = in6addr_loopback }; *addresses = TAKE_PTR(addrs); return n; } static int test_one_module(const char *dir, const char *module, char **names, struct local_address *addresses, int n_addresses) { log_info("======== %s ========", module); _cleanup_(dlclosep) void *handle = nss_open_handle(dir, module, RTLD_LAZY|RTLD_NODELETE); if (!handle) return -EINVAL; STRV_FOREACH(name, names) test_byname(handle, module, *name); for (int i = 0; i < n_addresses; i++) test_byaddr(handle, module, &addresses[i].address, FAMILY_ADDRESS_SIZE(addresses[i].family), addresses[i].family); log_info(" "); return 0; } static int parse_argv(int argc, char **argv, char ***the_modules, char ***the_names, struct local_address **the_addresses, int *n_addresses) { _cleanup_strv_free_ char **modules = NULL, **names = NULL; _cleanup_free_ struct local_address *addrs = NULL; const char *p; int r, n = 0; p = getenv("SYSTEMD_TEST_NSS_BUFSIZE"); if (p) { r = safe_atozu(p, &arg_bufsize); if (r < 0) return log_error_errno(r, "Failed to parse $SYSTEMD_TEST_NSS_BUFSIZE"); } if (argc > 1) modules = strv_new(argv[1]); else modules = strv_new( #if ENABLE_NSS_MYHOSTNAME "myhostname", #endif #if ENABLE_NSS_RESOLVE "resolve", #endif #if ENABLE_NSS_MYMACHINES "mymachines", #endif NULL); assert_se(modules); if (argc > 2) { int family; union in_addr_union address; STRV_FOREACH(name, argv + 2) { r = in_addr_from_string_auto(*name, &family, &address); if (r < 0) { /* assume this is a name */ r = strv_extend(&names, *name); if (r < 0) return r; } else { assert_se(GREEDY_REALLOC0(addrs, n + 1)); addrs[n++] = (struct local_address) { .family = family, .address = address }; } } } else { _cleanup_free_ char *hostname = NULL; assert_se(hostname = gethostname_malloc()); assert_se(names = strv_new("localhost", "_gateway", "_outbound", "foo_no_such_host", hostname)); n = make_addresses(&addrs); assert_se(n >= 0); } *the_modules = TAKE_PTR(modules); *the_names = TAKE_PTR(names); *the_addresses = TAKE_PTR(addrs); *n_addresses = n; return 0; } static int run(int argc, char **argv) { _cleanup_free_ char *dir = NULL; _cleanup_strv_free_ char **modules = NULL, **names = NULL; _cleanup_free_ struct local_address *addresses = NULL; int n_addresses = 0; int r; test_setup_logging(LOG_INFO); r = parse_argv(argc, argv, &modules, &names, &addresses, &n_addresses); if (r < 0) return log_error_errno(r, "Failed to parse arguments: %m"); assert_se(path_extract_directory(argv[0], &dir) >= 0); STRV_FOREACH(module, modules) { r = test_one_module(dir, *module, names, addresses, n_addresses); if (r < 0) return r; } return 0; } DEFINE_MAIN_FUNCTION(run);
18,650
36.908537
116
c
null
systemd-main/src/test/test-nss-users.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <pwd.h> #include <stdlib.h> #include <sys/types.h> #include <unistd.h> #include "alloc-util.h" #include "dlfcn-util.h" #include "errno-list.h" #include "format-util.h" #include "log.h" #include "main-func.h" #include "nss-test-util.h" #include "nss-util.h" #include "path-util.h" #include "parse-util.h" #include "stdio-util.h" #include "string-util.h" #include "strv.h" #include "tests.h" #include "user-util.h" static size_t arg_bufsize = 1024; static void print_struct_passwd(const struct passwd *pwd) { log_info(" \"%s\" / "UID_FMT":"GID_FMT, pwd->pw_name, pwd->pw_uid, pwd->pw_gid); log_info(" passwd=\"%s\"", pwd->pw_passwd); log_info(" gecos=\"%s\"", pwd->pw_gecos); log_info(" dir=\"%s\"", pwd->pw_dir); log_info(" shell=\"%s\"", pwd->pw_shell); } static void print_struct_group(const struct group *gr) { _cleanup_free_ char *members = NULL; log_info(" \"%s\" / "GID_FMT, gr->gr_name, gr->gr_gid); log_info(" passwd=\"%s\"", gr->gr_passwd); assert_se(members = strv_join(gr->gr_mem, ", ")); // FIXME: use shell_maybe_quote(SHELL_ESCAPE_EMPTY) when it becomes available log_info(" members=%s", members); } static void test_getpwnam_r(void *handle, const char *module, const char *name) { const char *fname; _nss_getpwnam_r_t f; char buffer[arg_bufsize]; int errno1 = 999; /* nss-dns doesn't set those */ enum nss_status status; char pretty_status[DECIMAL_STR_MAX(enum nss_status)]; struct passwd pwd; fname = strjoina("_nss_", module, "_getpwnam_r"); f = dlsym(handle, fname); log_debug("dlsym(0x%p, %s) β†’ 0x%p", handle, fname, f); if (!f) { log_info("%s not defined", fname); return; } status = f(name, &pwd, buffer, sizeof buffer, &errno1); log_info("%s(\"%s\") β†’ status=%s%-20serrno=%d/%s", fname, name, nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", errno1, errno_to_name(errno1) ?: "---"); if (status == NSS_STATUS_SUCCESS) print_struct_passwd(&pwd); } static void test_getgrnam_r(void *handle, const char *module, const char *name) { const char *fname; _nss_getgrnam_r_t f; char buffer[arg_bufsize]; int errno1 = 999; /* nss-dns doesn't set those */ enum nss_status status; char pretty_status[DECIMAL_STR_MAX(enum nss_status)]; struct group gr; fname = strjoina("_nss_", module, "_getgrnam_r"); f = dlsym(handle, fname); log_debug("dlsym(0x%p, %s) β†’ 0x%p", handle, fname, f); if (!f) { log_info("%s not defined", fname); return; } status = f(name, &gr, buffer, sizeof buffer, &errno1); log_info("%s(\"%s\") β†’ status=%s%-20serrno=%d/%s", fname, name, nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", errno1, errno_to_name(errno1) ?: "---"); if (status == NSS_STATUS_SUCCESS) print_struct_group(&gr); } static void test_getpwuid_r(void *handle, const char *module, uid_t uid) { const char *fname; _nss_getpwuid_r_t f; char buffer[arg_bufsize]; int errno1 = 999; /* nss-dns doesn't set those */ enum nss_status status; char pretty_status[DECIMAL_STR_MAX(enum nss_status)]; struct passwd pwd; fname = strjoina("_nss_", module, "_getpwuid_r"); f = dlsym(handle, fname); log_debug("dlsym(0x%p, %s) β†’ 0x%p", handle, fname, f); if (!f) { log_info("%s not defined", fname); return; } status = f(uid, &pwd, buffer, sizeof buffer, &errno1); log_info("%s("UID_FMT") β†’ status=%s%-20serrno=%d/%s", fname, uid, nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", errno1, errno_to_name(errno1) ?: "---"); if (status == NSS_STATUS_SUCCESS) print_struct_passwd(&pwd); } static void test_getgrgid_r(void *handle, const char *module, gid_t gid) { const char *fname; _nss_getgrgid_r_t f; char buffer[arg_bufsize]; int errno1 = 999; /* nss-dns doesn't set those */ enum nss_status status; char pretty_status[DECIMAL_STR_MAX(enum nss_status)]; struct group gr; fname = strjoina("_nss_", module, "_getgrgid_r"); f = dlsym(handle, fname); log_debug("dlsym(0x%p, %s) β†’ 0x%p", handle, fname, f); if (!f) { log_info("%s not defined", fname); return; } status = f(gid, &gr, buffer, sizeof buffer, &errno1); log_info("%s("GID_FMT") β†’ status=%s%-20serrno=%d/%s", fname, gid, nss_status_to_string(status, pretty_status, sizeof pretty_status), "\n", errno1, errno_to_name(errno1) ?: "---"); if (status == NSS_STATUS_SUCCESS) print_struct_group(&gr); } static void test_byname(void *handle, const char *module, const char *name) { test_getpwnam_r(handle, module, name); test_getgrnam_r(handle, module, name); puts(""); } static void test_byuid(void *handle, const char *module, uid_t uid) { test_getpwuid_r(handle, module, uid); test_getgrgid_r(handle, module, uid); puts(""); } static int test_one_module(const char *dir, const char *module, char **names) { log_info("======== %s ========", module); _cleanup_(dlclosep) void *handle = nss_open_handle(dir, module, RTLD_LAZY|RTLD_NODELETE); if (!handle) return -EINVAL; STRV_FOREACH(name, names) test_byname(handle, module, *name); STRV_FOREACH(name, names) { uid_t uid; assert_cc(sizeof(uid_t) == sizeof(uint32_t)); /* We use safe_atou32 because we don't want to refuse invalid uids. */ if (safe_atou32(*name, &uid) < 0) continue; test_byuid(handle, module, uid); } log_info(" "); return 0; } static int parse_argv(int argc, char **argv, char ***the_modules, char ***the_names) { _cleanup_strv_free_ char **modules = NULL, **names = NULL; const char *p; int r; p = getenv("SYSTEMD_TEST_NSS_BUFSIZE"); if (p) { r = safe_atozu(p, &arg_bufsize); if (r < 0) return log_error_errno(r, "Failed to parse $SYSTEMD_TEST_NSS_BUFSIZE"); } if (argc > 1) modules = strv_new(argv[1]); else modules = strv_new( #if ENABLE_NSS_SYSTEMD "systemd", #endif #if ENABLE_NSS_MYMACHINES "mymachines", #endif NULL); assert_se(modules); if (argc > 2) names = strv_copy(strv_skip(argv, 2)); else names = strv_new("root", NOBODY_USER_NAME, "foo_no_such_user", "0", "65534"); assert_se(names); *the_modules = TAKE_PTR(modules); *the_names = TAKE_PTR(names); return 0; } static int run(int argc, char **argv) { _cleanup_free_ char *dir = NULL; _cleanup_strv_free_ char **modules = NULL, **names = NULL; int r; test_setup_logging(LOG_INFO); r = parse_argv(argc, argv, &modules, &names); if (r < 0) return log_error_errno(r, "Failed to parse arguments: %m"); assert_se(path_extract_directory(argv[0], &dir) >= 0); STRV_FOREACH(module, modules) { r = test_one_module(dir, *module, names); if (r < 0) return r; } return 0; } DEFINE_MAIN_FUNCTION(run);
8,439
31.840467
97
c
null
systemd-main/src/test/test-nulstr-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "nulstr-util.h" #include "set.h" #include "strv.h" #include "tests.h" TEST(strv_split_nulstr) { _cleanup_strv_free_ char **l = NULL; const char nulstr[] = "str0\0str1\0str2\0str3\0"; l = strv_split_nulstr(nulstr); assert_se(l); assert_se(streq(l[0], "str0")); assert_se(streq(l[1], "str1")); assert_se(streq(l[2], "str2")); assert_se(streq(l[3], "str3")); } #define strv_parse_nulstr_full_one(s, n, e0, e1) \ ({ \ _cleanup_strv_free_ char **v0 = NULL, **v1 = NULL; \ \ assert_se(v0 = strv_parse_nulstr_full(s, n, false)); \ assert_se(strv_equal(v0, e0)); \ assert_se(v1 = strv_parse_nulstr_full(s, n, true)); \ assert_se(strv_equal(v1, e1)); \ }) TEST(strv_parse_nulstr_full) { const char nulstr1[] = "hoge\0hoge2\0hoge3\0\0hoge5\0\0xxx"; const char nulstr2[] = "hoge\0hoge2\0hoge3\0\0hoge5\0\0xxx\0\0\0"; strv_parse_nulstr_full_one(nulstr1, sizeof(nulstr1) - 1, STRV_MAKE("hoge", "hoge2", "hoge3", "", "hoge5", "", "xxx"), STRV_MAKE("hoge", "hoge2", "hoge3", "", "hoge5", "", "xxx")); strv_parse_nulstr_full_one(nulstr2, sizeof(nulstr2) - 1, STRV_MAKE("hoge", "hoge2", "hoge3", "", "hoge5", "", "xxx", "", ""), STRV_MAKE("hoge", "hoge2", "hoge3", "", "hoge5", "", "xxx")); strv_parse_nulstr_full_one(((const char[0]) {}), 0, STRV_MAKE_EMPTY, STRV_MAKE_EMPTY); strv_parse_nulstr_full_one(((const char[1]) { 0 }), 1, STRV_MAKE(""), STRV_MAKE_EMPTY); strv_parse_nulstr_full_one(((const char[1]) { 'x' }), 1, STRV_MAKE("x"), STRV_MAKE("x")); strv_parse_nulstr_full_one(((const char[2]) { 0, 0 }), 2, STRV_MAKE("", ""), STRV_MAKE_EMPTY); strv_parse_nulstr_full_one(((const char[2]) { 'x', 0 }), 2, STRV_MAKE("x"), STRV_MAKE("x")); strv_parse_nulstr_full_one(((const char[3]) { 0, 0, 0 }), 3, STRV_MAKE("", "", ""), STRV_MAKE_EMPTY); strv_parse_nulstr_full_one(((const char[3]) { 'x', 0, 0 }), 3, STRV_MAKE("x", ""), STRV_MAKE("x")); strv_parse_nulstr_full_one(((const char[3]) { 0, 'x', 0 }), 3, STRV_MAKE("", "x"), STRV_MAKE("", "x")); strv_parse_nulstr_full_one(((const char[3]) { 0, 0, 'x' }), 3, STRV_MAKE("", "", "x"), STRV_MAKE("", "", "x")); strv_parse_nulstr_full_one(((const char[3]) { 'x', 'x', 0 }), 3, STRV_MAKE("xx"), STRV_MAKE("xx")); strv_parse_nulstr_full_one(((const char[3]) { 0, 'x', 'x' }), 3, STRV_MAKE("", "xx"), STRV_MAKE("", "xx")); strv_parse_nulstr_full_one(((const char[3]) { 'x', 0, 'x' }), 3, STRV_MAKE("x", "x"), STRV_MAKE("x", "x")); strv_parse_nulstr_full_one(((const char[3]) { 'x', 'x', 'x' }), 3, STRV_MAKE("xxx"), STRV_MAKE("xxx")); } static void test_strv_make_nulstr_one(char **l) { _cleanup_free_ char *b = NULL, *c = NULL; _cleanup_strv_free_ char **q = NULL; size_t n, m; unsigned i = 0; log_info("/* %s */", __func__); assert_se(strv_make_nulstr(l, &b, &n) >= 0); assert_se(q = strv_parse_nulstr(b, n)); assert_se(strv_equal(l, q)); assert_se(strv_make_nulstr(q, &c, &m) >= 0); assert_se(memcmp_nn(b, n, c, m) == 0); NULSTR_FOREACH(s, b) assert_se(streq(s, l[i++])); assert_se(i == strv_length(l)); } TEST(strv_make_nulstr) { test_strv_make_nulstr_one(NULL); test_strv_make_nulstr_one(STRV_MAKE(NULL)); test_strv_make_nulstr_one(STRV_MAKE("foo")); test_strv_make_nulstr_one(STRV_MAKE("foo", "bar")); test_strv_make_nulstr_one(STRV_MAKE("foo", "bar", "quuux")); } TEST(set_make_nulstr) { _cleanup_set_free_free_ Set *set = NULL; size_t len = 0; int r; { /* Unallocated and empty set. */ static const char expect[] = { 0x00, 0x00 }; _cleanup_free_ char *nulstr = NULL; r = set_make_nulstr(set, &nulstr, &len); assert_se(r == 0); assert_se(len == 0); assert_se(memcmp(expect, nulstr, len + 2) == 0); } { /* Allocated by empty set. */ static const char expect[] = { 0x00, 0x00 }; _cleanup_free_ char *nulstr = NULL; set = set_new(NULL); assert_se(set); r = set_make_nulstr(set, &nulstr, &len); assert_se(r == 0); assert_se(len == 0); assert_se(memcmp(expect, nulstr, len + 2) == 0); } { /* Non-empty set. */ static const char expect[] = { 'a', 'a', 'a', 0x00, 0x00 }; _cleanup_free_ char *nulstr = NULL; assert_se(set_put_strdup(&set, "aaa") >= 0); r = set_make_nulstr(set, &nulstr, &len); assert_se(r == 0); assert_se(len == 4); assert_se(memcmp(expect, nulstr, len + 1) == 0); } } static void test_strv_make_nulstr_binary_one(char **l, const char *b, size_t n) { _cleanup_strv_free_ char **z = NULL; _cleanup_free_ char *a = NULL; size_t m; assert_se(strv_make_nulstr(l, &a, &m) >= 0); assert_se(memcmp_nn(a, m, b, n) == 0); assert_se(z = strv_parse_nulstr(a, m)); assert_se(strv_equal(l, z)); } TEST(strv_make_nulstr_binary) { test_strv_make_nulstr_binary_one(NULL, (const char[0]) {}, 0); test_strv_make_nulstr_binary_one(STRV_MAKE(NULL), (const char[0]) {}, 0); test_strv_make_nulstr_binary_one(STRV_MAKE(""), (const char[1]) { 0 }, 1); test_strv_make_nulstr_binary_one(STRV_MAKE("", ""), (const char[2]) { 0, 0 }, 2); test_strv_make_nulstr_binary_one(STRV_MAKE("x", ""), (const char[3]) { 'x', 0, 0 }, 3); test_strv_make_nulstr_binary_one(STRV_MAKE("", "x"), (const char[3]) { 0, 'x', 0 }, 3); test_strv_make_nulstr_binary_one(STRV_MAKE("", "", ""), (const char[3]) { 0, 0, 0 }, 3); test_strv_make_nulstr_binary_one(STRV_MAKE("x", "", ""), (const char[4]) { 'x', 0, 0, 0 }, 4); test_strv_make_nulstr_binary_one(STRV_MAKE("", "x", ""), (const char[4]) { 0, 'x', 0, 0 }, 4); test_strv_make_nulstr_binary_one(STRV_MAKE("", "", "x"), (const char[4]) { 0, 0, 'x', 0 }, 4); test_strv_make_nulstr_binary_one(STRV_MAKE("x", "x", ""), (const char[5]) { 'x', 0, 'x', 0, 0 }, 5); test_strv_make_nulstr_binary_one(STRV_MAKE("", "x", "x"), (const char[5]) { 0, 'x', 0, 'x', 0 }, 5); test_strv_make_nulstr_binary_one(STRV_MAKE("x", "", "x"), (const char[5]) { 'x', 0, 0, 'x', 0 }, 5); test_strv_make_nulstr_binary_one(STRV_MAKE("x", "x", "x"), (const char[6]) { 'x', 0, 'x', 0, 'x', 0 }, 6); } DEFINE_TEST_MAIN(LOG_INFO);
7,755
40.924324
114
c
null
systemd-main/src/test/test-open-file.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "open-file.h" #include "string-util.h" #include "tests.h" TEST(open_file_parse) { _cleanup_(open_file_freep) OpenFile *of = NULL; int r; r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:read-only", &of); assert_se(r >= 0); assert_se(streq(of->path, "/proc/1/ns/mnt")); assert_se(streq(of->fdname, "host-mount-namespace")); assert_se(of->flags == OPENFILE_READ_ONLY); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt", &of); assert_se(r >= 0); assert_se(streq(of->path, "/proc/1/ns/mnt")); assert_se(streq(of->fdname, "mnt")); assert_se(of->flags == 0); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace", &of); assert_se(r >= 0); assert_se(streq(of->path, "/proc/1/ns/mnt")); assert_se(streq(of->fdname, "host-mount-namespace")); assert_se(of->flags == 0); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt::read-only", &of); assert_se(r >= 0); assert_se(streq(of->path, "/proc/1/ns/mnt")); assert_se(streq(of->fdname, "mnt")); assert_se(of->flags == OPENFILE_READ_ONLY); of = open_file_free(of); r = open_file_parse("../file.dat:file:read-only", &of); assert_se(r == -EINVAL); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:rw", &of); assert_se(r == -EINVAL); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:append", &of); assert_se(r >= 0); assert_se(streq(of->path, "/proc/1/ns/mnt")); assert_se(streq(of->fdname, "host-mount-namespace")); assert_se(of->flags == OPENFILE_APPEND); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:truncate", &of); assert_se(r >= 0); assert_se(streq(of->path, "/proc/1/ns/mnt")); assert_se(streq(of->fdname, "host-mount-namespace")); assert_se(of->flags == OPENFILE_TRUNCATE); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:read-only,append", &of); assert_se(r == -EINVAL); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:read-only,truncate", &of); assert_se(r == -EINVAL); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:append,truncate", &of); assert_se(r == -EINVAL); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:read-only,read-only", &of); assert_se(r == -EINVAL); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:graceful", &of); assert_se(r >= 0); assert_se(streq(of->path, "/proc/1/ns/mnt")); assert_se(streq(of->fdname, "host-mount-namespace")); assert_se(of->flags == OPENFILE_GRACEFUL); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:read-only,graceful", &of); assert_se(r >= 0); assert_se(streq(of->path, "/proc/1/ns/mnt")); assert_se(streq(of->fdname, "host-mount-namespace")); assert_se(of->flags == (OPENFILE_READ_ONLY | OPENFILE_GRACEFUL)); of = open_file_free(of); r = open_file_parse("/proc/1/ns/mnt:host-mount-namespace:read-only:other", &of); assert_se(r == -EINVAL); } TEST(open_file_to_string) { _cleanup_free_ char *s = NULL; _cleanup_(open_file_freep) OpenFile *of = NULL; int r; assert_se(of = new (OpenFile, 1)); *of = (OpenFile){ .path = strdup("/proc/1/ns/mnt"), .fdname = strdup("host-mount-namespace"), .flags = OPENFILE_READ_ONLY }; r = open_file_to_string(of, &s); assert_se(r >= 0); assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace:read-only")); s = mfree(s); of->flags = OPENFILE_APPEND; r = open_file_to_string(of, &s); assert_se(r >= 0); assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace:append")); s = mfree(s); of->flags = OPENFILE_TRUNCATE; r = open_file_to_string(of, &s); assert_se(r >= 0); assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace:truncate")); s = mfree(s); of->flags = OPENFILE_GRACEFUL; r = open_file_to_string(of, &s); assert_se(r >= 0); assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace:graceful")); s = mfree(s); of->flags = OPENFILE_READ_ONLY | OPENFILE_GRACEFUL; r = open_file_to_string(of, &s); assert_se(r >= 0); assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace:read-only,graceful")); s = mfree(s); of->flags = 0; r = open_file_to_string(of, &s); assert_se(r >= 0); assert_se(streq(s, "/proc/1/ns/mnt:host-mount-namespace")); s = mfree(s); assert_se(free_and_strdup(&of->fdname, "mnt")); of->flags = OPENFILE_READ_ONLY; r = open_file_to_string(of, &s); assert_se(r >= 0); assert_se(streq(s, "/proc/1/ns/mnt::read-only")); s = mfree(s); assert_se(free_and_strdup(&of->path, "/path:with:colon")); assert_se(free_and_strdup(&of->fdname, "path:with:colon")); of->flags = 0; r = open_file_to_string(of, &s); assert_se(r >= 0); assert_se(streq(s, "/path\\:with\\:colon")); } DEFINE_TEST_MAIN(LOG_INFO);
5,792
30.145161
92
c
null
systemd-main/src/test/test-ordered-set.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdio.h> #include "ordered-set.h" #include "string-util.h" #include "strv.h" #include "tests.h" TEST(set_steal_first) { _cleanup_ordered_set_free_ OrderedSet *m = NULL; int seen[3] = {}; char *val; m = ordered_set_new(&string_hash_ops); assert_se(m); assert_se(ordered_set_put(m, (void*) "1") == 1); assert_se(ordered_set_put(m, (void*) "22") == 1); assert_se(ordered_set_put(m, (void*) "333") == 1); ordered_set_print(stdout, "SET=", m); while ((val = ordered_set_steal_first(m))) seen[strlen(val) - 1]++; assert_se(seen[0] == 1 && seen[1] == 1 && seen[2] == 1); assert_se(ordered_set_isempty(m)); ordered_set_print(stdout, "SET=", m); } typedef struct Item { int seen; } Item; static void item_seen(Item *item) { item->seen++; } DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, void, trivial_hash_func, trivial_compare_func, Item, item_seen); TEST(set_free_with_hash_ops) { OrderedSet *m; struct Item items[4] = {}; assert_se(m = ordered_set_new(&item_hash_ops)); for (size_t i = 0; i < ELEMENTSOF(items) - 1; i++) assert_se(ordered_set_put(m, items + i) == 1); for (size_t i = 0; i < ELEMENTSOF(items) - 1; i++) assert_se(ordered_set_put(m, items + i) == 0); /* We get 0 here, because we use trivial hash * ops. Also see below... */ m = ordered_set_free(m); assert_se(items[0].seen == 1); assert_se(items[1].seen == 1); assert_se(items[2].seen == 1); assert_se(items[3].seen == 0); } TEST(set_put) { _cleanup_ordered_set_free_ OrderedSet *m = NULL; _cleanup_free_ char **t = NULL, *str = NULL; m = ordered_set_new(&string_hash_ops); assert_se(m); assert_se(ordered_set_put(m, (void*) "1") == 1); assert_se(ordered_set_put(m, (void*) "22") == 1); assert_se(ordered_set_put(m, (void*) "333") == 1); assert_se(ordered_set_put(m, (void*) "333") == 0); assert_se(ordered_set_remove(m, (void*) "333")); assert_se(ordered_set_put(m, (void*) "333") == 1); assert_se(ordered_set_put(m, (void*) "333") == 0); assert_se(ordered_set_put(m, (void*) "22") == 0); assert_se(str = strdup("333")); assert_se(ordered_set_put(m, str) == -EEXIST); /* ... and we get -EEXIST here, because we use * non-trivial hash ops. */ assert_se(t = ordered_set_get_strv(m)); assert_se(streq(t[0], "1")); assert_se(streq(t[1], "22")); assert_se(streq(t[2], "333")); assert_se(!t[3]); ordered_set_print(stdout, "FOO=", m); } TEST(set_put_string_set) { _cleanup_ordered_set_free_ OrderedSet *m = NULL, *q = NULL; _cleanup_free_ char **final = NULL; /* "just free" because the strings are in the set */ assert_se(ordered_set_put_strdup(&m, "1") == 1); assert_se(ordered_set_put_strdup(&m, "22") == 1); assert_se(ordered_set_put_strdup(&m, "333") == 1); assert_se(ordered_set_put_strdup(&q, "11") == 1); assert_se(ordered_set_put_strdup(&q, "22") == 1); assert_se(ordered_set_put_strdup(&q, "33") == 1); assert_se(ordered_set_put_string_set(&m, q) == 2); assert_se(final = ordered_set_get_strv(m)); assert_se(strv_equal(final, STRV_MAKE("1", "22", "333", "11", "33"))); ordered_set_print(stdout, "BAR=", m); } DEFINE_TEST_MAIN(LOG_INFO);
3,730
32.017699
125
c
null
systemd-main/src/test/test-os-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include "fileio.h" #include "fs-util.h" #include "log.h" #include "mkdir.h" #include "os-util.h" #include "path-util.h" #include "rm-rf.h" #include "string-util.h" #include "strv.h" #include "tests.h" #include "tmpfile-util.h" TEST(path_is_os_tree) { assert_se(path_is_os_tree("/") > 0); assert_se(path_is_os_tree("/etc") == 0); assert_se(path_is_os_tree("/idontexist") == -ENOENT); } TEST(parse_os_release) { /* Let's assume that we're running in a valid system, so os-release is available */ _cleanup_free_ char *id = NULL, *id2 = NULL, *name = NULL, *foobar = NULL; assert_se(parse_os_release(NULL, "ID", &id) == 0); log_info("ID: %s", id); assert_se(setenv("SYSTEMD_OS_RELEASE", "/dev/null", 1) == 0); assert_se(parse_os_release(NULL, "ID", &id2) == 0); log_info("ID: %s", strnull(id2)); _cleanup_(unlink_tempfilep) char tmpfile[] = "/tmp/test-os-util.XXXXXX"; assert_se(write_tmpfile(tmpfile, "ID=the-id \n" "NAME=the-name") == 0); assert_se(setenv("SYSTEMD_OS_RELEASE", tmpfile, 1) == 0); assert_se(parse_os_release(NULL, "ID", &id, "NAME", &name) == 0); log_info("ID: %s NAME: %s", id, name); assert_se(streq(id, "the-id")); assert_se(streq(name, "the-name")); _cleanup_(unlink_tempfilep) char tmpfile2[] = "/tmp/test-os-util.XXXXXX"; assert_se(write_tmpfile(tmpfile2, "ID=\"ignored\" \n" "ID=\"the-id\" \n" "NAME='the-name'") == 0); assert_se(setenv("SYSTEMD_OS_RELEASE", tmpfile2, 1) == 0); assert_se(parse_os_release(NULL, "ID", &id, "NAME", &name) == 0); log_info("ID: %s NAME: %s", id, name); assert_se(streq(id, "the-id")); assert_se(streq(name, "the-name")); assert_se(parse_os_release(NULL, "FOOBAR", &foobar) == 0); log_info("FOOBAR: %s", strnull(foobar)); assert_se(foobar == NULL); assert_se(unsetenv("SYSTEMD_OS_RELEASE") == 0); } TEST(parse_extension_release) { /* Let's assume that we have a valid extension image */ _cleanup_free_ char *id = NULL, *version_id = NULL, *foobar = NULL, *a = NULL, *b = NULL; _cleanup_(rm_rf_physical_and_freep) char *tempdir = NULL; int r = mkdtemp_malloc("/tmp/test-os-util.XXXXXX", &tempdir); if (r < 0) log_error_errno(r, "Failed to setup working directory: %m"); assert_se(a = path_join(tempdir, "/usr/lib/extension-release.d/extension-release.test")); assert_se(mkdir_parents(a, 0777) >= 0); r = write_string_file(a, "ID=the-id \n VERSION_ID=the-version-id", WRITE_STRING_FILE_CREATE); if (r < 0) log_error_errno(r, "Failed to write file: %m"); assert_se(parse_extension_release(tempdir, IMAGE_SYSEXT, "test", false, "ID", &id, "VERSION_ID", &version_id) == 0); log_info("ID: %s VERSION_ID: %s", id, version_id); assert_se(streq(id, "the-id")); assert_se(streq(version_id, "the-version-id")); assert_se(b = path_join(tempdir, "/etc/extension-release.d/extension-release.tester")); assert_se(mkdir_parents(b, 0777) >= 0); r = write_string_file(b, "ID=\"ignored\" \n ID=\"the-id\" \n VERSION_ID='the-version-id'", WRITE_STRING_FILE_CREATE); if (r < 0) log_error_errno(r, "Failed to write file: %m"); assert_se(parse_extension_release(tempdir, IMAGE_CONFEXT, "tester", false, "ID", &id, "VERSION_ID", &version_id) == 0); log_info("ID: %s VERSION_ID: %s", id, version_id); assert_se(streq(id, "the-id")); assert_se(streq(version_id, "the-version-id")); assert_se(parse_extension_release(tempdir, IMAGE_CONFEXT, "tester", false, "FOOBAR", &foobar) == 0); log_info("FOOBAR: %s", strnull(foobar)); assert_se(foobar == NULL); assert_se(parse_extension_release(tempdir, IMAGE_SYSEXT, "test", false, "FOOBAR", &foobar) == 0); log_info("FOOBAR: %s", strnull(foobar)); assert_se(foobar == NULL); } TEST(load_os_release_pairs) { _cleanup_(unlink_tempfilep) char tmpfile[] = "/tmp/test-os-util.XXXXXX"; assert_se(write_tmpfile(tmpfile, "ID=\"ignored\" \n" "ID=\"the-id\" \n" "NAME='the-name'") == 0); assert_se(setenv("SYSTEMD_OS_RELEASE", tmpfile, 1) == 0); _cleanup_strv_free_ char **pairs = NULL; assert_se(load_os_release_pairs(NULL, &pairs) == 0); assert_se(strv_equal(pairs, STRV_MAKE("ID", "the-id", "NAME", "the-name"))); assert_se(unsetenv("SYSTEMD_OS_RELEASE") == 0); } TEST(os_release_support_ended) { int r; assert_se(os_release_support_ended("1999-01-01", false, NULL) == true); assert_se(os_release_support_ended("2037-12-31", false, NULL) == false); assert_se(os_release_support_ended("-1-1-1", true, NULL) == -EINVAL); r = os_release_support_ended(NULL, false, NULL); if (r < 0) log_info_errno(r, "Failed to check host: %m"); else log_info_errno(r, "Host is supported: %s", yes_no(!r)); } DEFINE_TEST_MAIN(LOG_DEBUG);
5,515
39.558824
127
c
null
systemd-main/src/test/test-parse-argument.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <signal.h> #include "parse-argument.h" #include "stdio-util.h" #include "tests.h" TEST(parse_json_argument) { JsonFormatFlags flags = JSON_FORMAT_PRETTY; assert_se(parse_json_argument("help", &flags) == 0); assert_se(flags == JSON_FORMAT_PRETTY); assert_se(parse_json_argument("off", &flags) == 1); assert_se(flags == JSON_FORMAT_OFF); } TEST(parse_path_argument) { _cleanup_free_ char *path = NULL; assert_se(parse_path_argument("help", false, &path) == 0); assert_se(streq(basename(path), "help")); assert_se(parse_path_argument("/", false, &path) == 0); assert_se(streq(path, "/")); assert_se(parse_path_argument("/", true, &path) == 0); assert_se(path == NULL); } TEST(parse_signal_argument) { int signal = -1; assert_se(parse_signal_argument("help", &signal) == 0); assert_se(signal == -1); assert_se(parse_signal_argument("list", &signal) == 0); assert_se(signal == -1); assert_se(parse_signal_argument("SIGABRT", &signal) == 1); assert_se(signal == SIGABRT); assert_se(parse_signal_argument("ABRT", &signal) == 1); assert_se(signal == SIGABRT); char buf[DECIMAL_STR_MAX(int)]; xsprintf(buf, "%d", SIGABRT); assert_se(parse_signal_argument(buf, &signal) == 1); assert_se(signal == SIGABRT); } DEFINE_TEST_MAIN(LOG_INFO);
1,502
26.833333
66
c
null
systemd-main/src/test/test-parse-helpers.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <linux/in.h> #include <sys/socket.h> #include <stdio.h> #include "macro.h" #include "parse-helpers.h" #include "tests.h" static void test_valid_item( const char *str, int expected_af, int expected_ip_protocol, uint16_t expected_nr_ports, uint16_t expected_port_min) { uint16_t nr_ports, port_min; int af, ip_protocol; assert_se(parse_socket_bind_item(str, &af, &ip_protocol, &nr_ports, &port_min) >= 0); assert_se(af == expected_af); assert_se(ip_protocol == expected_ip_protocol); assert_se(nr_ports == expected_nr_ports); assert_se(port_min == expected_port_min); log_info("%s: \"%s\" ok", __func__, str); } static void test_invalid_item(const char *str) { uint16_t nr_ports, port_min; int af, ip_protocol; assert_se(parse_socket_bind_item(str, &af, &ip_protocol, &nr_ports, &port_min) == -EINVAL); log_info("%s: \"%s\" ok", __func__, str); } TEST(valid_items) { test_valid_item("any", AF_UNSPEC, 0, 0, 0); test_valid_item("ipv4", AF_INET, 0, 0, 0); test_valid_item("ipv6", AF_INET6, 0, 0, 0); test_valid_item("ipv4:any", AF_INET, 0, 0, 0); test_valid_item("ipv6:any", AF_INET6, 0, 0, 0); test_valid_item("tcp", AF_UNSPEC, IPPROTO_TCP, 0, 0); test_valid_item("udp", AF_UNSPEC, IPPROTO_UDP, 0, 0); test_valid_item("tcp:any", AF_UNSPEC, IPPROTO_TCP, 0, 0); test_valid_item("udp:any", AF_UNSPEC, IPPROTO_UDP, 0, 0); test_valid_item("6666", AF_UNSPEC, 0, 1, 6666); test_valid_item("6666-6667", AF_UNSPEC, 0, 2, 6666); test_valid_item("65535", AF_UNSPEC, 0, 1, 65535); test_valid_item("1-65535", AF_UNSPEC, 0, 65535, 1); test_valid_item("ipv4:tcp", AF_INET, IPPROTO_TCP, 0, 0); test_valid_item("ipv4:udp", AF_INET, IPPROTO_UDP, 0, 0); test_valid_item("ipv6:tcp", AF_INET6, IPPROTO_TCP, 0, 0); test_valid_item("ipv6:udp", AF_INET6, IPPROTO_UDP, 0, 0); test_valid_item("ipv4:6666", AF_INET, 0, 1, 6666); test_valid_item("ipv6:6666", AF_INET6, 0, 1, 6666); test_valid_item("tcp:6666", AF_UNSPEC, IPPROTO_TCP, 1, 6666); test_valid_item("udp:6666", AF_UNSPEC, IPPROTO_UDP, 1, 6666); test_valid_item("ipv4:tcp:6666", AF_INET, IPPROTO_TCP, 1, 6666); test_valid_item("ipv6:tcp:6666", AF_INET6, IPPROTO_TCP, 1, 6666); test_valid_item("ipv6:udp:6666-6667", AF_INET6, IPPROTO_UDP, 2, 6666); test_valid_item("ipv6:tcp:any", AF_INET6, IPPROTO_TCP, 0, 0); } TEST(invalid_items) { test_invalid_item(""); test_invalid_item(":"); test_invalid_item("::"); test_invalid_item("any:"); test_invalid_item("meh"); test_invalid_item("zupa:meh"); test_invalid_item("zupa:meh:eh"); test_invalid_item("ip"); test_invalid_item("dccp"); test_invalid_item("ipv6meh"); test_invalid_item("ipv6::"); test_invalid_item("ipv6:ipv6"); test_invalid_item("ipv6:icmp"); test_invalid_item("ipv6:tcp:0"); test_invalid_item("65536"); test_invalid_item("0-65535"); test_invalid_item("ipv6:tcp:6666-6665"); test_invalid_item("ipv6:tcp:6666-100000"); test_invalid_item("ipv6::6666"); test_invalid_item("ipv6:tcp:any:"); test_invalid_item("ipv6:tcp:any:ipv6"); test_invalid_item("ipv6:tcp:6666:zupa"); test_invalid_item("ipv6:tcp:6666:any"); test_invalid_item("ipv6:tcp:6666 zupa"); test_invalid_item("ipv6:tcp:6666: zupa"); test_invalid_item("ipv6:tcp:6666\n zupa"); } DEFINE_TEST_MAIN(LOG_INFO);
3,802
38.614583
99
c
null
systemd-main/src/test/test-path-lookup.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdlib.h> #include <sys/stat.h> #include "log.h" #include "path-lookup.h" #include "rm-rf.h" #include "string-util.h" #include "strv.h" #include "tests.h" #include "tmpfile-util.h" static void test_paths_one(RuntimeScope scope) { _cleanup_(rm_rf_physical_and_freep) char *tmp = NULL; _cleanup_(lookup_paths_free) LookupPaths lp_without_env = {}; _cleanup_(lookup_paths_free) LookupPaths lp_with_env = {}; char *systemd_unit_path; assert_se(mkdtemp_malloc("/tmp/test-path-lookup.XXXXXXX", &tmp) >= 0); assert_se(unsetenv("SYSTEMD_UNIT_PATH") == 0); assert_se(lookup_paths_init(&lp_without_env, scope, 0, NULL) >= 0); assert_se(!strv_isempty(lp_without_env.search_path)); lookup_paths_log(&lp_without_env); systemd_unit_path = strjoina(tmp, "/systemd-unit-path"); assert_se(setenv("SYSTEMD_UNIT_PATH", systemd_unit_path, 1) == 0); assert_se(lookup_paths_init(&lp_with_env, scope, 0, NULL) == 0); assert_se(strv_length(lp_with_env.search_path) == 1); assert_se(streq(lp_with_env.search_path[0], systemd_unit_path)); lookup_paths_log(&lp_with_env); assert_se(strv_equal(lp_with_env.search_path, STRV_MAKE(systemd_unit_path))); } TEST(paths) { test_paths_one(RUNTIME_SCOPE_SYSTEM); test_paths_one(RUNTIME_SCOPE_USER); test_paths_one(RUNTIME_SCOPE_GLOBAL); } TEST(user_and_global_paths) { _cleanup_(lookup_paths_free) LookupPaths lp_global = {}, lp_user = {}; char **u, **g; unsigned k = 0; assert_se(unsetenv("SYSTEMD_UNIT_PATH") == 0); assert_se(unsetenv("XDG_DATA_DIRS") == 0); assert_se(unsetenv("XDG_CONFIG_DIRS") == 0); assert_se(lookup_paths_init(&lp_global, RUNTIME_SCOPE_GLOBAL, 0, NULL) == 0); assert_se(lookup_paths_init(&lp_user, RUNTIME_SCOPE_USER, 0, NULL) == 0); g = lp_global.search_path; u = lp_user.search_path; /* Go over all entries in global search path, and verify * that they also exist in the user search path. Skip any * entries in user search path which don't exist in the global * one, but not vice versa. */ STRV_FOREACH(p, g) { while (u[k] && !streq(*p, u[k])) { log_info("+ %s", u[k]); k++; } log_info(" %s", *p); assert_se(u[k]); /* If NULL, we didn't find a matching entry */ k++; } STRV_FOREACH(p, u + k) log_info("+ %s", *p); } static void test_generator_binary_paths_one(RuntimeScope scope) { _cleanup_(rm_rf_physical_and_freep) char *tmp = NULL; _cleanup_strv_free_ char **gp_without_env = NULL; _cleanup_strv_free_ char **env_gp_without_env = NULL; _cleanup_strv_free_ char **gp_with_env = NULL; _cleanup_strv_free_ char **env_gp_with_env = NULL; char *systemd_generator_path = NULL; char *systemd_env_generator_path = NULL; assert_se(mkdtemp_malloc("/tmp/test-path-lookup.XXXXXXX", &tmp) >= 0); assert_se(unsetenv("SYSTEMD_GENERATOR_PATH") == 0); assert_se(unsetenv("SYSTEMD_ENVIRONMENT_GENERATOR_PATH") == 0); gp_without_env = generator_binary_paths(scope); env_gp_without_env = env_generator_binary_paths(scope); log_info("Generators dirs (%s):", runtime_scope_to_string(scope)); STRV_FOREACH(dir, gp_without_env) log_info(" %s", *dir); log_info("Environment generators dirs (%s):", runtime_scope_to_string(scope)); STRV_FOREACH(dir, env_gp_without_env) log_info(" %s", *dir); assert_se(!strv_isempty(gp_without_env)); assert_se(!strv_isempty(env_gp_without_env)); systemd_generator_path = strjoina(tmp, "/systemd-generator-path"); systemd_env_generator_path = strjoina(tmp, "/systemd-environment-generator-path"); assert_se(setenv("SYSTEMD_GENERATOR_PATH", systemd_generator_path, 1) == 0); assert_se(setenv("SYSTEMD_ENVIRONMENT_GENERATOR_PATH", systemd_env_generator_path, 1) == 0); gp_with_env = generator_binary_paths(scope); env_gp_with_env = env_generator_binary_paths(scope); log_info("Generators dirs (%s):", runtime_scope_to_string(scope)); STRV_FOREACH(dir, gp_with_env) log_info(" %s", *dir); log_info("Environment generators dirs (%s):", runtime_scope_to_string(scope)); STRV_FOREACH(dir, env_gp_with_env) log_info(" %s", *dir); assert_se(strv_equal(gp_with_env, STRV_MAKE(systemd_generator_path))); assert_se(strv_equal(env_gp_with_env, STRV_MAKE(systemd_env_generator_path))); } TEST(generator_binary_paths) { test_generator_binary_paths_one(RUNTIME_SCOPE_SYSTEM); test_generator_binary_paths_one(RUNTIME_SCOPE_USER); } DEFINE_TEST_MAIN(LOG_DEBUG);
5,065
38.889764
100
c
null
systemd-main/src/test/test-path.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdbool.h> #include <sys/stat.h> #include <sys/types.h> #include "alloc-util.h" #include "all-units.h" #include "fd-util.h" #include "fs-util.h" #include "macro.h" #include "manager.h" #include "mkdir.h" #include "path-util.h" #include "rm-rf.h" #include "string-util.h" #include "strv.h" #include "tests.h" #include "unit.h" typedef void (*test_function_t)(Manager *m); static int setup_test(Manager **m) { char **tests_path = STRV_MAKE("exists", "existsglobFOOBAR", "changed", "modified", "unit", "directorynotempty", "makedirectory"); Manager *tmp = NULL; int r; assert_se(m); r = enter_cgroup_subroot(NULL); if (r == -ENOMEDIUM) return log_tests_skipped("cgroupfs not available"); r = manager_new(RUNTIME_SCOPE_USER, MANAGER_TEST_RUN_BASIC, &tmp); if (manager_errno_skip_test(r)) return log_tests_skipped_errno(r, "manager_new"); assert_se(r >= 0); assert_se(manager_startup(tmp, NULL, NULL, NULL) >= 0); STRV_FOREACH(test_path, tests_path) { _cleanup_free_ char *p = NULL; p = strjoin("/tmp/test-path_", *test_path); assert_se(p); (void) rm_rf(p, REMOVE_ROOT|REMOVE_PHYSICAL); } *m = tmp; return 0; } static void shutdown_test(Manager *m) { assert_se(m); manager_free(m); } static Service *service_for_path(Manager *m, Path *path, const char *service_name) { _cleanup_free_ char *tmp = NULL; Unit *service_unit = NULL; assert_se(m); assert_se(path); if (!service_name) { assert_se(tmp = strreplace(UNIT(path)->id, ".path", ".service")); service_unit = manager_get_unit(m, tmp); } else service_unit = manager_get_unit(m, service_name); assert_se(service_unit); return SERVICE(service_unit); } static int _check_states(unsigned line, Manager *m, Path *path, Service *service, PathState path_state, ServiceState service_state) { assert_se(m); assert_se(service); usec_t end = now(CLOCK_MONOTONIC) + 30 * USEC_PER_SEC; while (path->state != path_state || service->state != service_state || path->result != PATH_SUCCESS || service->result != SERVICE_SUCCESS) { assert_se(sd_event_run(m->event, 100 * USEC_PER_MSEC) >= 0); usec_t n = now(CLOCK_MONOTONIC); log_info("line %u: %s: state = %s; result = %s (left: %" PRIi64 ")", line, UNIT(path)->id, path_state_to_string(path->state), path_result_to_string(path->result), (int64_t) (end - n)); log_info("line %u: %s: state = %s; result = %s", line, UNIT(service)->id, service_state_to_string(service->state), service_result_to_string(service->result)); if (service->state == SERVICE_FAILED && service->main_exec_status.status == EXIT_CGROUP && !ci_environment()) /* On a general purpose system we may fail to start the service for reasons which are * not under our control: permission limits, resource exhaustion, etc. Let's skip the * test in those cases. On developer machines we require proper setup. */ return log_notice_errno(SYNTHETIC_ERRNO(ECANCELED), "Failed to start service %s, aborting test: %s/%s", UNIT(service)->id, service_state_to_string(service->state), service_result_to_string(service->result)); if (n >= end) { log_error("Test timeout when testing %s", UNIT(path)->id); exit(EXIT_FAILURE); } } return 0; } #define check_states(...) _check_states(__LINE__, __VA_ARGS__) static void test_path_exists(Manager *m) { const char *test_path = "/tmp/test-path_exists"; Unit *unit = NULL; Path *path = NULL; Service *service = NULL; assert_se(m); assert_se(manager_load_startable_unit_or_warn(m, "path-exists.path", NULL, &unit) >= 0); path = PATH(unit); service = service_for_path(m, path, NULL); assert_se(unit_start(unit, NULL) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; assert_se(touch(test_path) >= 0); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; /* Service restarts if file still exists */ assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; assert_se(rm_rf(test_path, REMOVE_ROOT|REMOVE_PHYSICAL) == 0); assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; assert_se(unit_stop(unit) >= 0); } static void test_path_existsglob(Manager *m) { const char *test_path = "/tmp/test-path_existsglobFOOBAR"; Unit *unit = NULL; Path *path = NULL; Service *service = NULL; assert_se(m); assert_se(manager_load_startable_unit_or_warn(m, "path-existsglob.path", NULL, &unit) >= 0); path = PATH(unit); service = service_for_path(m, path, NULL); assert_se(unit_start(unit, NULL) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; assert_se(touch(test_path) >= 0); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; /* Service restarts if file still exists */ assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; assert_se(rm_rf(test_path, REMOVE_ROOT|REMOVE_PHYSICAL) == 0); assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; assert_se(unit_stop(unit) >= 0); } static void test_path_changed(Manager *m) { const char *test_path = "/tmp/test-path_changed"; FILE *f; Unit *unit = NULL; Path *path = NULL; Service *service = NULL; assert_se(m); assert_se(manager_load_startable_unit_or_warn(m, "path-changed.path", NULL, &unit) >= 0); path = PATH(unit); service = service_for_path(m, path, NULL); assert_se(unit_start(unit, NULL) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; assert_se(touch(test_path) >= 0); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; /* Service does not restart if file still exists */ assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; f = fopen(test_path, "w"); assert_se(f); fclose(f); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; (void) rm_rf(test_path, REMOVE_ROOT|REMOVE_PHYSICAL); assert_se(unit_stop(unit) >= 0); } static void test_path_modified(Manager *m) { _cleanup_fclose_ FILE *f = NULL; const char *test_path = "/tmp/test-path_modified"; Unit *unit = NULL; Path *path = NULL; Service *service = NULL; assert_se(m); assert_se(manager_load_startable_unit_or_warn(m, "path-modified.path", NULL, &unit) >= 0); path = PATH(unit); service = service_for_path(m, path, NULL); assert_se(unit_start(unit, NULL) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; assert_se(touch(test_path) >= 0); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; /* Service does not restart if file still exists */ assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; f = fopen(test_path, "w"); assert_se(f); fputs("test", f); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; (void) rm_rf(test_path, REMOVE_ROOT|REMOVE_PHYSICAL); assert_se(unit_stop(unit) >= 0); } static void test_path_unit(Manager *m) { const char *test_path = "/tmp/test-path_unit"; Unit *unit = NULL; Path *path = NULL; Service *service = NULL; assert_se(m); assert_se(manager_load_startable_unit_or_warn(m, "path-unit.path", NULL, &unit) >= 0); path = PATH(unit); service = service_for_path(m, path, "path-mycustomunit.service"); assert_se(unit_start(unit, NULL) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; assert_se(touch(test_path) >= 0); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; assert_se(rm_rf(test_path, REMOVE_ROOT|REMOVE_PHYSICAL) == 0); assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; assert_se(unit_stop(unit) >= 0); } static void test_path_directorynotempty(Manager *m) { const char *test_file, *test_path = "/tmp/test-path_directorynotempty/"; Unit *unit = NULL; Path *path = NULL; Service *service = NULL; assert_se(m); assert_se(manager_load_startable_unit_or_warn(m, "path-directorynotempty.path", NULL, &unit) >= 0); path = PATH(unit); service = service_for_path(m, path, NULL); assert_se(access(test_path, F_OK) < 0); assert_se(unit_start(unit, NULL) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; /* MakeDirectory default to no */ assert_se(access(test_path, F_OK) < 0); assert_se(mkdir_p(test_path, 0755) >= 0); test_file = strjoina(test_path, "test_file"); assert_se(touch(test_file) >= 0); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; /* Service restarts if directory is still not empty */ assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_RUNNING, SERVICE_RUNNING) < 0) return; assert_se(rm_rf(test_path, REMOVE_ROOT|REMOVE_PHYSICAL) == 0); assert_se(unit_stop(UNIT(service)) >= 0); if (check_states(m, path, service, PATH_WAITING, SERVICE_DEAD) < 0) return; assert_se(unit_stop(unit) >= 0); } static void test_path_makedirectory_directorymode(Manager *m) { const char *test_path = "/tmp/test-path_makedirectory/"; Unit *unit = NULL; struct stat s; assert_se(m); assert_se(manager_load_startable_unit_or_warn(m, "path-makedirectory.path", NULL, &unit) >= 0); assert_se(access(test_path, F_OK) < 0); assert_se(unit_start(unit, NULL) >= 0); /* Check if the directory has been created */ assert_se(access(test_path, F_OK) >= 0); /* Check the mode we specified with DirectoryMode=0744 */ assert_se(stat(test_path, &s) >= 0); assert_se((s.st_mode & S_IRWXU) == 0700); assert_se((s.st_mode & S_IRWXG) == 0040); assert_se((s.st_mode & S_IRWXO) == 0004); assert_se(unit_stop(unit) >= 0); (void) rm_rf(test_path, REMOVE_ROOT|REMOVE_PHYSICAL); } int main(int argc, char *argv[]) { static const test_function_t tests[] = { test_path_exists, test_path_existsglob, test_path_changed, test_path_modified, test_path_unit, test_path_directorynotempty, test_path_makedirectory_directorymode, NULL, }; _cleanup_free_ char *test_path = NULL; _cleanup_(rm_rf_physical_and_freep) char *runtime_dir = NULL; umask(022); test_setup_logging(LOG_INFO); assert_se(get_testdata_dir("test-path", &test_path) >= 0); assert_se(set_unit_path(test_path) >= 0); assert_se(runtime_dir = setup_fake_runtime_dir()); for (const test_function_t *test = tests; *test; test++) { Manager *m = NULL; int r; /* We create a clean environment for each test */ r = setup_test(&m); if (r != 0) return r; (*test)(m); shutdown_test(m); } return 0; }
13,897
32.73301
118
c
null
systemd-main/src/test/test-percent-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "percent-util.h" #include "tests.h" #include "time-util.h" TEST(parse_percent) { assert_se(parse_percent("") == -EINVAL); assert_se(parse_percent("foo") == -EINVAL); assert_se(parse_percent("0") == -EINVAL); assert_se(parse_percent("0.1") == -EINVAL); assert_se(parse_percent("50") == -EINVAL); assert_se(parse_percent("100") == -EINVAL); assert_se(parse_percent("-1") == -EINVAL); assert_se(parse_percent("0%") == 0); assert_se(parse_percent("55%") == 55); assert_se(parse_percent("100%") == 100); assert_se(parse_percent("-7%") == -ERANGE); assert_se(parse_percent("107%") == -ERANGE); assert_se(parse_percent("%") == -EINVAL); assert_se(parse_percent("%%") == -EINVAL); assert_se(parse_percent("%1") == -EINVAL); assert_se(parse_percent("1%%") == -EINVAL); assert_se(parse_percent("3.2%") == -EINVAL); } TEST(parse_percent_unbounded) { assert_se(parse_percent_unbounded("101%") == 101); assert_se(parse_percent_unbounded("400%") == 400); } TEST(parse_permille) { assert_se(parse_permille("") == -EINVAL); assert_se(parse_permille("foo") == -EINVAL); assert_se(parse_permille("0") == -EINVAL); assert_se(parse_permille("50") == -EINVAL); assert_se(parse_permille("100") == -EINVAL); assert_se(parse_permille("-1") == -EINVAL); assert_se(parse_permille("0.1") == -EINVAL); assert_se(parse_permille("5%") == 50); assert_se(parse_permille("5.5%") == 55); assert_se(parse_permille("5.12%") == -EINVAL); assert_se(parse_permille("0‰") == 0); assert_se(parse_permille("555‰") == 555); assert_se(parse_permille("1000‰") == 1000); assert_se(parse_permille("-7‰") == -ERANGE); assert_se(parse_permille("1007‰") == -ERANGE); assert_se(parse_permille("‰") == -EINVAL); assert_se(parse_permille("‰‰") == -EINVAL); assert_se(parse_permille("‰1") == -EINVAL); assert_se(parse_permille("1‰‰") == -EINVAL); assert_se(parse_permille("3.2‰") == -EINVAL); assert_se(parse_permille("0.1‰") == -EINVAL); assert_se(parse_permille("0%") == 0); assert_se(parse_permille("55%") == 550); assert_se(parse_permille("55.5%") == 555); assert_se(parse_permille("100%") == 1000); assert_se(parse_permille("-7%") == -ERANGE); assert_se(parse_permille("107%") == -ERANGE); assert_se(parse_permille("%") == -EINVAL); assert_se(parse_permille("%%") == -EINVAL); assert_se(parse_permille("%1") == -EINVAL); assert_se(parse_permille("1%%") == -EINVAL); assert_se(parse_permille("3.21%") == -EINVAL); assert_se(parse_permille("0.1%") == 1); } TEST(parse_permille_unbounded) { assert_se(parse_permille_unbounded("1001‰") == 1001); assert_se(parse_permille_unbounded("4000‰") == 4000); assert_se(parse_permille_unbounded("2147483647‰") == 2147483647); assert_se(parse_permille_unbounded("2147483648‰") == -ERANGE); assert_se(parse_permille_unbounded("4294967295‰") == -ERANGE); assert_se(parse_permille_unbounded("4294967296‰") == -ERANGE); assert_se(parse_permille_unbounded("101%") == 1010); assert_se(parse_permille_unbounded("400%") == 4000); assert_se(parse_permille_unbounded("214748364.7%") == 2147483647); assert_se(parse_permille_unbounded("214748364.8%") == -ERANGE); assert_se(parse_permille_unbounded("429496729.5%") == -ERANGE); assert_se(parse_permille_unbounded("429496729.6%") == -ERANGE); } TEST(parse_permyriad) { assert_se(parse_permyriad("") == -EINVAL); assert_se(parse_permyriad("foo") == -EINVAL); assert_se(parse_permyriad("0") == -EINVAL); assert_se(parse_permyriad("50") == -EINVAL); assert_se(parse_permyriad("100") == -EINVAL); assert_se(parse_permyriad("-1") == -EINVAL); assert_se(parse_permyriad("0β€±") == 0); assert_se(parse_permyriad("555β€±") == 555); assert_se(parse_permyriad("1000β€±") == 1000); assert_se(parse_permyriad("-7β€±") == -ERANGE); assert_se(parse_permyriad("10007β€±") == -ERANGE); assert_se(parse_permyriad("β€±") == -EINVAL); assert_se(parse_permyriad("β€±β€±") == -EINVAL); assert_se(parse_permyriad("β€±1") == -EINVAL); assert_se(parse_permyriad("1β€±β€±") == -EINVAL); assert_se(parse_permyriad("3.2β€±") == -EINVAL); assert_se(parse_permyriad("0‰") == 0); assert_se(parse_permyriad("555.5‰") == 5555); assert_se(parse_permyriad("1000.0‰") == 10000); assert_se(parse_permyriad("-7‰") == -ERANGE); assert_se(parse_permyriad("1007‰") == -ERANGE); assert_se(parse_permyriad("‰") == -EINVAL); assert_se(parse_permyriad("‰‰") == -EINVAL); assert_se(parse_permyriad("‰1") == -EINVAL); assert_se(parse_permyriad("1‰‰") == -EINVAL); assert_se(parse_permyriad("3.22‰") == -EINVAL); assert_se(parse_permyriad("0%") == 0); assert_se(parse_permyriad("55%") == 5500); assert_se(parse_permyriad("55.5%") == 5550); assert_se(parse_permyriad("55.50%") == 5550); assert_se(parse_permyriad("55.53%") == 5553); assert_se(parse_permyriad("100%") == 10000); assert_se(parse_permyriad("-7%") == -ERANGE); assert_se(parse_permyriad("107%") == -ERANGE); assert_se(parse_permyriad("%") == -EINVAL); assert_se(parse_permyriad("%%") == -EINVAL); assert_se(parse_permyriad("%1") == -EINVAL); assert_se(parse_permyriad("1%%") == -EINVAL); assert_se(parse_permyriad("3.212%") == -EINVAL); } TEST(parse_permyriad_unbounded) { assert_se(parse_permyriad_unbounded("1001β€±") == 1001); assert_se(parse_permyriad_unbounded("4000β€±") == 4000); assert_se(parse_permyriad_unbounded("2147483647β€±") == 2147483647); assert_se(parse_permyriad_unbounded("2147483648β€±") == -ERANGE); assert_se(parse_permyriad_unbounded("4294967295β€±") == -ERANGE); assert_se(parse_permyriad_unbounded("4294967296β€±") == -ERANGE); assert_se(parse_permyriad_unbounded("101‰") == 1010); assert_se(parse_permyriad_unbounded("400‰") == 4000); assert_se(parse_permyriad_unbounded("214748364.7‰") == 2147483647); assert_se(parse_permyriad_unbounded("214748364.8‰") == -ERANGE); assert_se(parse_permyriad_unbounded("429496729.5‰") == -ERANGE); assert_se(parse_permyriad_unbounded("429496729.6‰") == -ERANGE); assert_se(parse_permyriad_unbounded("99%") == 9900); assert_se(parse_permyriad_unbounded("40%") == 4000); assert_se(parse_permyriad_unbounded("21474836.47%") == 2147483647); assert_se(parse_permyriad_unbounded("21474836.48%") == -ERANGE); assert_se(parse_permyriad_unbounded("42949672.95%") == -ERANGE); assert_se(parse_permyriad_unbounded("42949672.96%") == -ERANGE); } TEST(scale) { /* Check some fixed values */ assert_se(UINT32_SCALE_FROM_PERCENT(0) == 0); assert_se(UINT32_SCALE_FROM_PERCENT(50) == UINT32_MAX/2+1); assert_se(UINT32_SCALE_FROM_PERCENT(100) == UINT32_MAX); assert_se(UINT32_SCALE_FROM_PERMILLE(0) == 0); assert_se(UINT32_SCALE_FROM_PERMILLE(500) == UINT32_MAX/2+1); assert_se(UINT32_SCALE_FROM_PERMILLE(1000) == UINT32_MAX); assert_se(UINT32_SCALE_FROM_PERMYRIAD(0) == 0); assert_se(UINT32_SCALE_FROM_PERMYRIAD(5000) == UINT32_MAX/2+1); assert_se(UINT32_SCALE_FROM_PERMYRIAD(10000) == UINT32_MAX); /* Make sure there's no numeric noise on the 0%…100% scale when converting from percent and back. */ for (int percent = 0; percent <= 100; percent++) { log_debug("%i%% β†’ %" PRIu32 " β†’ %i%%", percent, UINT32_SCALE_FROM_PERCENT(percent), UINT32_SCALE_TO_PERCENT(UINT32_SCALE_FROM_PERCENT(percent))); assert_se(UINT32_SCALE_TO_PERCENT(UINT32_SCALE_FROM_PERCENT(percent)) == percent); } /* Make sure there's no numeric noise on the 0‰…1000‰ scale when converting from permille and back. */ for (int permille = 0; permille <= 1000; permille++) { log_debug("%i‰ β†’ %" PRIu32 " β†’ %i‰", permille, UINT32_SCALE_FROM_PERMILLE(permille), UINT32_SCALE_TO_PERMILLE(UINT32_SCALE_FROM_PERMILLE(permille))); assert_se(UINT32_SCALE_TO_PERMILLE(UINT32_SCALE_FROM_PERMILLE(permille)) == permille); } /* Make sure there's no numeric noise on the 0‱…10000β€± scale when converting from permyriad and back. */ for (int permyriad = 0; permyriad <= 10000; permyriad++) { log_debug("%iβ€± β†’ %" PRIu32 " β†’ %iβ€±", permyriad, UINT32_SCALE_FROM_PERMYRIAD(permyriad), UINT32_SCALE_TO_PERMYRIAD(UINT32_SCALE_FROM_PERMYRIAD(permyriad))); assert_se(UINT32_SCALE_TO_PERMYRIAD(UINT32_SCALE_FROM_PERMYRIAD(permyriad)) == permyriad); } } DEFINE_TEST_MAIN(LOG_DEBUG);
9,404
46.025
112
c
null
systemd-main/src/test/test-pretty-print.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdio.h> #include <sys/stat.h> #include <sys/types.h> #include <unistd.h> #include "alloc-util.h" #include "macro.h" #include "pretty-print.h" #include "strv.h" #include "tests.h" TEST(terminal_urlify) { _cleanup_free_ char *formatted = NULL; assert_se(terminal_urlify("https://www.freedesktop.org/wiki/Software/systemd", "systemd homepage", &formatted) >= 0); printf("Hey, consider visiting the %s right now! It is very good!\n", formatted); formatted = mfree(formatted); assert_se(terminal_urlify_path("/etc/fstab", "this link to your /etc/fstab", &formatted) >= 0); printf("Or click on %s to have a look at it!\n", formatted); } TEST(cat_files) { assert_se(cat_files("/no/such/file", NULL, 0) == -ENOENT); assert_se(cat_files("/no/such/file", NULL, CAT_FLAGS_MAIN_FILE_OPTIONAL) == 0); if (access("/etc/fstab", R_OK) >= 0) assert_se(cat_files("/etc/fstab", STRV_MAKE("/etc/fstab", "/etc/fstab"), 0) == 0); } TEST(red_green_cross_check_mark) { bool b = false; printf("yea: <%s>\n", GREEN_CHECK_MARK()); printf("nay: <%s>\n", RED_CROSS_MARK()); printf("%s β†’ %s β†’ %s β†’ %s\n", COLOR_MARK_BOOL(b), COLOR_MARK_BOOL(!b), COLOR_MARK_BOOL(!!b), COLOR_MARK_BOOL(!!!b)); } TEST(print_separator) { print_separator(); } DEFINE_TEST_MAIN(LOG_INFO);
1,498
27.826923
125
c
null
systemd-main/src/test/test-prioq.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdlib.h> #include "alloc-util.h" #include "prioq.h" #include "set.h" #include "siphash24.h" #include "sort-util.h" #include "tests.h" #define SET_SIZE 1024*4 static int unsigned_compare(const unsigned *a, const unsigned *b) { return CMP(*a, *b); } TEST(unsigned) { _cleanup_(prioq_freep) Prioq *q = NULL; unsigned buffer[SET_SIZE], i, u, n; srand(0); assert_se(q = prioq_new(trivial_compare_func)); for (i = 0; i < ELEMENTSOF(buffer); i++) { u = (unsigned) rand(); buffer[i] = u; assert_se(prioq_put(q, UINT_TO_PTR(u), NULL) >= 0); n = prioq_size(q); assert_se(prioq_remove(q, UINT_TO_PTR(u), &n) == 0); } typesafe_qsort(buffer, ELEMENTSOF(buffer), unsigned_compare); for (i = 0; i < ELEMENTSOF(buffer); i++) { assert_se(prioq_size(q) == ELEMENTSOF(buffer) - i); u = PTR_TO_UINT(prioq_pop(q)); assert_se(buffer[i] == u); } assert_se(prioq_isempty(q)); } struct test { unsigned value; unsigned idx; }; static int test_compare(const struct test *x, const struct test *y) { return CMP(x->value, y->value); } static void test_hash(const struct test *x, struct siphash *state) { siphash24_compress(&x->value, sizeof(x->value), state); } DEFINE_PRIVATE_HASH_OPS(test_hash_ops, struct test, test_hash, test_compare); TEST(struct) { _cleanup_(prioq_freep) Prioq *q = NULL; _cleanup_set_free_ Set *s = NULL; unsigned previous = 0, i; struct test *t; srand(0); assert_se(q = prioq_new((compare_func_t) test_compare)); assert_se(s = set_new(&test_hash_ops)); assert_se(prioq_peek(q) == NULL); assert_se(prioq_peek_by_index(q, 0) == NULL); assert_se(prioq_peek_by_index(q, 1) == NULL); assert_se(prioq_peek_by_index(q, UINT_MAX) == NULL); for (i = 0; i < SET_SIZE; i++) { assert_se(t = new0(struct test, 1)); t->value = (unsigned) rand(); assert_se(prioq_put(q, t, &t->idx) >= 0); if (i % 4 == 0) assert_se(set_consume(s, t) >= 0); } for (i = 0; i < SET_SIZE; i++) assert_se(prioq_peek_by_index(q, i)); assert_se(prioq_peek_by_index(q, SET_SIZE) == NULL); unsigned count = 0; PRIOQ_FOREACH_ITEM(q, t) { assert_se(t); count++; } assert_se(count == SET_SIZE); while ((t = set_steal_first(s))) { assert_se(prioq_remove(q, t, &t->idx) == 1); assert_se(prioq_remove(q, t, &t->idx) == 0); assert_se(prioq_remove(q, t, NULL) == 0); free(t); } for (i = 0; i < SET_SIZE * 3 / 4; i++) { assert_se(prioq_size(q) == (SET_SIZE * 3 / 4) - i); assert_se(t = prioq_pop(q)); assert_se(prioq_remove(q, t, &t->idx) == 0); assert_se(prioq_remove(q, t, NULL) == 0); assert_se(previous <= t->value); previous = t->value; free(t); } assert_se(prioq_isempty(q)); assert_se(set_isempty(s)); } DEFINE_TEST_MAIN(LOG_INFO);
3,437
26.725806
77
c
null
systemd-main/src/test/test-procfs-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include "errno-util.h" #include "format-util.h" #include "log.h" #include "procfs-util.h" #include "process-util.h" #include "tests.h" int main(int argc, char *argv[]) { nsec_t nsec; uint64_t v, pid_max, threads_max, limit; int r; log_parse_environment(); log_open(); assert_se(procfs_cpu_get_usage(&nsec) >= 0); log_info("Current system CPU time: %s", FORMAT_TIMESPAN(nsec/NSEC_PER_USEC, 1)); assert_se(procfs_memory_get_used(&v) >= 0); log_info("Current memory usage: %s", FORMAT_BYTES(v)); assert_se(procfs_tasks_get_current(&v) >= 0); log_info("Current number of tasks: %" PRIu64, v); pid_max = TASKS_MAX; r = procfs_get_pid_max(&pid_max); if (r == -ENOENT || ERRNO_IS_PRIVILEGE(r)) return log_tests_skipped_errno(r, "can't get pid max"); assert(r >= 0); log_info("kernel.pid_max: %"PRIu64, pid_max); threads_max = TASKS_MAX; r = procfs_get_threads_max(&threads_max); if (r == -ENOENT || ERRNO_IS_PRIVILEGE(r)) return log_tests_skipped_errno(r, "can't get threads max"); assert(r >= 0); log_info("kernel.threads-max: %"PRIu64, threads_max); limit = MIN(pid_max - (pid_max > 0), threads_max); assert_se(r >= 0); log_info("Limit of tasks: %" PRIu64, limit); assert_se(limit > 0); /* This call should never fail, as we're trying to set it to the same limit */ assert(procfs_tasks_set_limit(limit) >= 0); if (limit > 100) { log_info("Reducing limit by one to %"PRIu64"…", limit-1); r = procfs_tasks_set_limit(limit-1); if (IN_SET(r, -ENOENT, -EROFS) || ERRNO_IS_PRIVILEGE(r)) return log_tests_skipped_errno(r, "can't set tasks limit"); assert_se(r >= 0); assert_se(procfs_get_pid_max(&v) >= 0); /* We never decrease the pid_max, so it shouldn't have changed */ assert_se(v == pid_max); assert_se(procfs_get_threads_max(&v) >= 0); assert_se(v == limit-1); assert_se(procfs_tasks_set_limit(limit) >= 0); assert_se(procfs_get_pid_max(&v) >= 0); assert_se(v == pid_max); assert_se(procfs_get_threads_max(&v) >= 0); assert_se(v == limit); } return 0; }
2,557
31.794872
88
c
null
systemd-main/src/test/test-qrcode-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "locale-util.h" #include "main-func.h" #include "qrcode-util.h" #include "tests.h" static int run(int argc, char **argv) { int r; test_setup_logging(LOG_DEBUG); assert_se(setenv("SYSTEMD_COLORS", "1", 1) == 0); /* Force the qrcode to be printed */ r = print_qrcode(stdout, "This should say \"TEST\"", "TEST"); if (r == -EOPNOTSUPP) return log_tests_skipped("not supported"); if (r < 0) return log_error_errno(r, "Failed to print QR code: %m"); return 0; } DEFINE_MAIN_FUNCTION(run);
635
25.5
94
c
null
systemd-main/src/test/test-random-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <math.h> #include "hexdecoct.h" #include "log.h" #include "memory-util.h" #include "random-util.h" #include "terminal-util.h" #include "tests.h" TEST(random_bytes) { uint8_t buf[16] = {}; for (size_t i = 1; i < sizeof buf; i++) { random_bytes(buf, i); if (i + 1 < sizeof buf) assert_se(buf[i] == 0); hexdump(stdout, buf, i); } } TEST(crypto_random_bytes) { uint8_t buf[16] = {}; for (size_t i = 1; i < sizeof buf; i++) { assert_se(crypto_random_bytes(buf, i) == 0); if (i + 1 < sizeof buf) assert_se(buf[i] == 0); hexdump(stdout, buf, i); } } #define TOTAL 100000 static void test_random_u64_range_one(unsigned mod) { log_info("/* %s(%u) */", __func__, mod); unsigned max = 0, count[mod]; zero(count); for (unsigned i = 0; i < TOTAL; i++) { uint64_t x; x = random_u64_range(mod); count[x]++; max = MAX(max, count[x]); } /* Print histogram: vertical axis β€” value, horizontal axis β€” count. * * The expected value is always TOTAL/mod, because the distribution should be flat. The expected * variance is TOTALΓ—pΓ—(1-p), where p==1/mod, and standard deviation the root of the variance. * Assert that the deviation from the expected value is less than 6 standard deviations. */ unsigned scale = 2 * max / (columns() < 20 ? 80 : columns() - 20); double exp = (double) TOTAL / mod; for (size_t i = 0; i < mod; i++) { double dev = (count[i] - exp) / sqrt(exp * (mod > 1 ? mod - 1 : 1) / mod); log_debug("%02zu: %5u (%+.3f)%*s", i, count[i], dev, (int) (count[i] / scale), "x"); assert_se(fabs(dev) < 6); /* 6 sigma is excessive, but this check should be enough to * identify catastrophic failure while minimizing false * positives. */ } } TEST(random_u64_range) { for (unsigned mod = 1; mod < 29; mod++) test_random_u64_range_one(mod); } DEFINE_TEST_MAIN(LOG_DEBUG);
2,425
29.325
104
c
null
systemd-main/src/test/test-ratelimit.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include "macro.h" #include "ratelimit.h" #include "tests.h" #include "time-util.h" TEST(ratelimit_below) { int i; RateLimit ratelimit = { 1 * USEC_PER_SEC, 10 }; for (i = 0; i < 10; i++) assert_se(ratelimit_below(&ratelimit)); assert_se(!ratelimit_below(&ratelimit)); sleep(1); for (i = 0; i < 10; i++) assert_se(ratelimit_below(&ratelimit)); ratelimit = (const RateLimit) { 0, 10 }; for (i = 0; i < 10000; i++) assert_se(ratelimit_below(&ratelimit)); } TEST(ratelimit_num_dropped) { int i; RateLimit ratelimit = { 1 * USEC_PER_SEC, 10 }; for (i = 0; i < 10; i++) { assert_se(ratelimit_below(&ratelimit)); assert_se(ratelimit_num_dropped(&ratelimit) == 0); } assert_se(!ratelimit_below(&ratelimit)); assert_se(ratelimit_num_dropped(&ratelimit) == 1); assert_se(!ratelimit_below(&ratelimit)); assert_se(ratelimit_num_dropped(&ratelimit) == 2); sleep(1); assert_se(ratelimit_below(&ratelimit)); assert_se(ratelimit_num_dropped(&ratelimit) == 0); } DEFINE_TEST_MAIN(LOG_INFO);
1,284
28.204545
66
c
null
systemd-main/src/test/test-replace-var.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdio.h> #include "macro.h" #include "replace-var.h" #include "string-util.h" #include "tests.h" static char *lookup(const char *variable, void *userdata) { return strjoin("<<<", variable, ">>>"); } TEST(replace_var) { char *r; assert_se(r = replace_var("@@@foobar@xyz@HALLO@foobar@test@@testtest@TEST@...@@@", lookup, NULL)); puts(r); assert_se(streq(r, "@@@foobar@xyz<<<HALLO>>>foobar@test@@testtest<<<TEST>>>...@@@")); free(r); } TEST(strreplace) { char *r; assert_se(r = strreplace("XYZFFFFXYZFFFFXYZ", "XYZ", "ABC")); puts(r); assert_se(streq(r, "ABCFFFFABCFFFFABC")); free(r); } DEFINE_TEST_MAIN(LOG_INFO);
768
22.30303
106
c
null
systemd-main/src/test/test-rm-rf.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include "alloc-util.h" #include "process-util.h" #include "rm-rf.h" #include "string-util.h" #include "tests.h" #include "tmpfile-util.h" static void test_rm_rf_chmod_inner(void) { _cleanup_(rm_rf_physical_and_freep) char *d = NULL; const char *a, *b, *x, *y; struct stat st; assert_se(getuid() != 0); assert_se(mkdtemp_malloc("/tmp/test-rm-rf.XXXXXXX", &d) >= 0); a = strjoina(d, "/a"); b = strjoina(a, "/b"); x = strjoina(d, "/x"); y = strjoina(x, "/y"); assert_se(mkdir(x, 0700) >= 0); assert_se(mknod(y, S_IFREG | 0600, 0) >= 0); assert_se(chmod(y, 0400) >= 0); assert_se(chmod(x, 0500) >= 0); assert_se(chmod(d, 0500) >= 0); assert_se(rm_rf(d, REMOVE_PHYSICAL) == -EACCES); assert_se(access(d, F_OK) >= 0); assert_se(access(x, F_OK) >= 0); assert_se(access(y, F_OK) >= 0); assert_se(rm_rf(d, REMOVE_PHYSICAL|REMOVE_CHMOD) >= 0); assert_se(access(d, F_OK) >= 0); assert_se(access(x, F_OK) < 0 && errno == ENOENT); assert_se(access(y, F_OK) < 0 && errno == ENOENT); assert_se(mkdir(a, 0700) >= 0); assert_se(mkdir(b, 0700) >= 0); assert_se(mkdir(x, 0700) >= 0); assert_se(mknod(y, S_IFREG | 0600, 0) >= 0); assert_se(chmod(b, 0000) >= 0); assert_se(chmod(a, 0000) >= 0); assert_se(chmod(y, 0000) >= 0); assert_se(chmod(x, 0000) >= 0); assert_se(chmod(d, 0500) >= 0); assert_se(rm_rf(d, REMOVE_PHYSICAL|REMOVE_CHMOD|REMOVE_CHMOD_RESTORE|REMOVE_ONLY_DIRECTORIES) == -ENOTEMPTY); assert_se(access(a, F_OK) < 0 && errno == ENOENT); assert_se(access(d, F_OK) >= 0); assert_se(stat(d, &st) >= 0 && (st.st_mode & 07777) == 0500); assert_se(access(x, F_OK) >= 0); assert_se(stat(x, &st) >= 0 && (st.st_mode & 07777) == 0000); assert_se(chmod(x, 0700) >= 0); assert_se(access(y, F_OK) >= 0); assert_se(stat(y, &st) >= 0 && (st.st_mode & 07777) == 0000); assert_se(chmod(y, 0000) >= 0); assert_se(chmod(x, 0000) >= 0); assert_se(chmod(d, 0000) >= 0); assert_se(rm_rf(d, REMOVE_PHYSICAL|REMOVE_CHMOD|REMOVE_CHMOD_RESTORE) >= 0); assert_se(stat(d, &st) >= 0 && (st.st_mode & 07777) == 0000); assert_se(access(d, F_OK) >= 0); assert_se(chmod(d, 0700) >= 0); assert_se(access(x, F_OK) < 0 && errno == ENOENT); assert_se(mkdir(x, 0700) >= 0); assert_se(mknod(y, S_IFREG | 0600, 0) >= 0); assert_se(chmod(y, 0000) >= 0); assert_se(chmod(x, 0000) >= 0); assert_se(chmod(d, 0000) >= 0); assert_se(rm_rf(d, REMOVE_PHYSICAL|REMOVE_CHMOD|REMOVE_ROOT) >= 0); assert_se(access(d, F_OK) < 0 && errno == ENOENT); } TEST(rm_rf_chmod) { int r; if (getuid() == 0) { /* This test only works unpriv (as only then the access mask for the owning user matters), * hence drop privs here */ r = safe_fork("(setresuid)", FORK_DEATHSIG|FORK_WAIT, NULL); assert_se(r >= 0); if (r == 0) { /* child */ assert_se(setresuid(1, 1, 1) >= 0); test_rm_rf_chmod_inner(); _exit(EXIT_SUCCESS); } return; } test_rm_rf_chmod_inner(); } DEFINE_TEST_MAIN(LOG_DEBUG);
3,599
30.304348
117
c
null
systemd-main/src/test/test-sbat.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* We include efi_config.h after undefining PROJECT_VERSION which is also defined in config.h. */ #undef PROJECT_VERSION #include "efi_config.h" #include "build.h" #include "sbat.h" #include "tests.h" TEST(sbat_section_text) { log_info("---SBAT-----------&<----------------------------------------\n" "%s" "------------------>&-----------------------------------------", #ifdef SBAT_DISTRO SBAT_SECTION_TEXT #else "(not defined)" #endif ); } DEFINE_TEST_MAIN(LOG_INFO);
607
24.333333
97
c
null
systemd-main/src/test/test-sched-prio.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright Β© 2012 Holger Hans Peter Freyther ***/ #include <sched.h> #include "all-units.h" #include "macro.h" #include "manager.h" #include "rm-rf.h" #include "tests.h" int main(int argc, char *argv[]) { _cleanup_(rm_rf_physical_and_freep) char *runtime_dir = NULL; _cleanup_(manager_freep) Manager *m = NULL; Unit *idle_ok, *idle_bad, *rr_ok, *rr_bad, *rr_sched; Service *ser; int r; test_setup_logging(LOG_INFO); r = enter_cgroup_subroot(NULL); if (r == -ENOMEDIUM) return log_tests_skipped("cgroupfs not available"); /* prepare the test */ _cleanup_free_ char *unit_dir = NULL; assert_se(get_testdata_dir("units", &unit_dir) >= 0); assert_se(set_unit_path(unit_dir) >= 0); assert_se(runtime_dir = setup_fake_runtime_dir()); r = manager_new(RUNTIME_SCOPE_USER, MANAGER_TEST_RUN_BASIC, &m); if (manager_errno_skip_test(r)) return log_tests_skipped_errno(r, "manager_new"); assert_se(r >= 0); assert_se(manager_startup(m, NULL, NULL, NULL) >= 0); /* load idle ok */ assert_se(manager_load_startable_unit_or_warn(m, "sched_idle_ok.service", NULL, &idle_ok) >= 0); ser = SERVICE(idle_ok); assert_se(ser->exec_context.cpu_sched_policy == SCHED_OTHER); assert_se(ser->exec_context.cpu_sched_priority == 0); /* * load idle bad. This should print a warning but we have no way to look at it. */ assert_se(manager_load_startable_unit_or_warn(m, "sched_idle_bad.service", NULL, &idle_bad) >= 0); ser = SERVICE(idle_ok); assert_se(ser->exec_context.cpu_sched_policy == SCHED_OTHER); assert_se(ser->exec_context.cpu_sched_priority == 0); /* * load rr ok. * Test that the default priority is moving from 0 to 1. */ assert_se(manager_load_startable_unit_or_warn(m, "sched_rr_ok.service", NULL, &rr_ok) >= 0); ser = SERVICE(rr_ok); assert_se(ser->exec_context.cpu_sched_policy == SCHED_RR); assert_se(ser->exec_context.cpu_sched_priority == 1); /* * load rr bad. * Test that the value of 0 and 100 is ignored. */ assert_se(manager_load_startable_unit_or_warn(m, "sched_rr_bad.service", NULL, &rr_bad) >= 0); ser = SERVICE(rr_bad); assert_se(ser->exec_context.cpu_sched_policy == SCHED_RR); assert_se(ser->exec_context.cpu_sched_priority == 1); /* * load rr change. * Test that anything between 1 and 99 can be set. */ assert_se(manager_load_startable_unit_or_warn(m, "sched_rr_change.service", NULL, &rr_sched) >= 0); ser = SERVICE(rr_sched); assert_se(ser->exec_context.cpu_sched_policy == SCHED_RR); assert_se(ser->exec_context.cpu_sched_priority == 99); return EXIT_SUCCESS; }
3,010
35.719512
107
c
null
systemd-main/src/test/test-sd-hwdb.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "sd-hwdb.h" #include "alloc-util.h" #include "errno-util.h" #include "errno.h" #include "hwdb-internal.h" #include "nulstr-util.h" #include "tests.h" TEST(failed_enumerate) { _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL; const char *key, *value; assert_se(sd_hwdb_new(&hwdb) == 0); assert_se(sd_hwdb_seek(hwdb, "no-such-modalias-should-exist") == 0); assert_se(sd_hwdb_enumerate(hwdb, &key, &value) == 0); assert_se(sd_hwdb_enumerate(hwdb, &key, NULL) == -EINVAL); assert_se(sd_hwdb_enumerate(hwdb, NULL, &value) == -EINVAL); } #define DELL_MODALIAS \ "evdev:atkbd:dmi:bvnXXX:bvrYYY:bdZZZ:svnDellXXX:pnYYY:" TEST(basic_enumerate) { _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL; const char *key, *value; size_t len1 = 0, len2 = 0; int r; assert_se(sd_hwdb_new(&hwdb) == 0); assert_se(sd_hwdb_seek(hwdb, DELL_MODALIAS) == 0); for (;;) { r = sd_hwdb_enumerate(hwdb, &key, &value); assert_se(IN_SET(r, 0, 1)); if (r == 0) break; assert_se(key); assert_se(value); log_debug("A: \"%s\" β†’ \"%s\"", key, value); len1 += strlen(key) + strlen(value); } SD_HWDB_FOREACH_PROPERTY(hwdb, DELL_MODALIAS, key, value) { log_debug("B: \"%s\" β†’ \"%s\"", key, value); len2 += strlen(key) + strlen(value); } assert_se(len1 == len2); } TEST(sd_hwdb_new_from_path) { _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL; int r; assert_se(sd_hwdb_new_from_path(NULL, &hwdb) == -EINVAL); assert_se(sd_hwdb_new_from_path("", &hwdb) == -EINVAL); assert_se(sd_hwdb_new_from_path("/path/that/should/not/exist", &hwdb) < 0); NULSTR_FOREACH(hwdb_bin_path, hwdb_bin_paths) { r = sd_hwdb_new_from_path(hwdb_bin_path, &hwdb); if (r >= 0) break; } assert_se(r >= 0); } static int intro(void) { _cleanup_(sd_hwdb_unrefp) sd_hwdb *hwdb = NULL; int r; r = sd_hwdb_new(&hwdb); if (r == -ENOENT || ERRNO_IS_PRIVILEGE(r)) return log_tests_skipped_errno(r, "cannot open hwdb"); return EXIT_SUCCESS; } DEFINE_TEST_MAIN_WITH_INTRO(LOG_DEBUG, intro);
2,479
27.837209
83
c
null
systemd-main/src/test/test-sd-path.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "sd-path.h" #include "alloc-util.h" #include "string-util.h" #include "strv.h" #include "tests.h" TEST(sd_path_lookup) { for (uint64_t i = 0; i < _SD_PATH_MAX; i++) { _cleanup_free_ char *t = NULL, *s = NULL; int r; r = sd_path_lookup(i, NULL, &t); if (i == SD_PATH_USER_RUNTIME && r == -ENXIO) continue; assert_se(r == 0); assert_se(t); log_info("%02"PRIu64": \"%s\"", i, t); assert_se(sd_path_lookup(i, "suffix", &s) == 0); assert_se(s); log_info("%02"PRIu64": \"%s\"", i, s); assert_se(endswith(s, "/suffix")); } char *tt; assert_se(sd_path_lookup(_SD_PATH_MAX, NULL, &tt) == -EOPNOTSUPP); } TEST(sd_path_lookup_strv) { for (uint64_t i = 0; i < _SD_PATH_MAX; i++) { _cleanup_strv_free_ char **t = NULL, **s = NULL; int r; r = sd_path_lookup_strv(i, NULL, &t); if (i == SD_PATH_USER_RUNTIME && r == -ENXIO) continue; assert_se(r == 0); assert_se(t); log_info("%02"PRIu64":", i); STRV_FOREACH(item, t) log_debug(" %s", *item); assert_se(sd_path_lookup_strv(i, "suffix", &s) == 0); assert_se(s); log_info("%02"PRIu64":", i); STRV_FOREACH(item, s) { assert_se(endswith(*item, "/suffix")); log_debug(" %s", *item); } } char *tt; assert_se(sd_path_lookup(_SD_PATH_MAX, NULL, &tt) == -EOPNOTSUPP); } DEFINE_TEST_MAIN(LOG_DEBUG);
1,864
30.083333
74
c
null
systemd-main/src/test/test-secure-bits.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include "securebits-util.h" #include "strv.h" #include "tests.h" #include "unit-file.h" static const char * const string_bits[] = { "keep-caps", "keep-caps-locked", "no-setuid-fixup", "no-setuid-fixup-locked", "noroot", "noroot-locked", NULL }; TEST(secure_bits_basic) { _cleanup_free_ char *joined = NULL, *str = NULL; int r; /* Check if converting each bit from string and back to string yields * the same value */ STRV_FOREACH(bit, string_bits) { _cleanup_free_ char *s = NULL; r = secure_bits_from_string(*bit); assert_se(r > 0); assert_se(secure_bits_is_valid(r)); assert_se(secure_bits_to_string_alloc(r, &s) >= 0); printf("%s = 0x%x = %s\n", *bit, (unsigned)r, s); assert_se(streq(*bit, s)); } /* Ditto, but with all bits at once */ joined = strv_join((char**)string_bits, " "); assert_se(joined); r = secure_bits_from_string(joined); assert_se(r > 0); assert_se(secure_bits_is_valid(r)); assert_se(secure_bits_to_string_alloc(r, &str) >= 0); printf("%s = 0x%x = %s\n", joined, (unsigned)r, str); assert_se(streq(joined, str)); str = mfree(str); /* Empty string */ assert_se(secure_bits_from_string("") == 0); assert_se(secure_bits_from_string(" ") == 0); /* Only invalid entries */ assert_se(secure_bits_from_string("foo bar baz") == 0); /* Empty secure bits */ assert_se(secure_bits_to_string_alloc(0, &str) >= 0); assert_se(isempty(str)); str = mfree(str); /* Bits to string with check */ assert_se(secure_bits_to_string_alloc_with_check(INT_MAX, &str) == -EINVAL); assert_se(str == NULL); assert_se(secure_bits_to_string_alloc_with_check( (1 << SECURE_KEEP_CAPS) | (1 << SECURE_KEEP_CAPS_LOCKED), &str) >= 0); assert_se(streq(str, "keep-caps keep-caps-locked")); } TEST(secure_bits_mix) { static struct sbit_table { const char *input; const char *expected; } sbit_table[] = { { "keep-caps keep-caps keep-caps", "keep-caps" }, { "keep-caps noroot keep-caps", "keep-caps noroot" }, { "noroot foo bar baz noroot", "noroot" }, { "noroot \"foo\" \"bar keep-caps", "noroot" }, { "\"noroot foo\" bar keep-caps", "keep-caps" }, {} }; for (const struct sbit_table *s = sbit_table; s->input; s++) { _cleanup_free_ char *str = NULL; int r; r = secure_bits_from_string(s->input); assert_se(r > 0); assert_se(secure_bits_is_valid(r)); assert_se(secure_bits_to_string_alloc(r, &str) >= 0); printf("%s = 0x%x = %s\n", s->input, (unsigned)r, str); assert_se(streq(s->expected, str)); } } DEFINE_TEST_MAIN(LOG_DEBUG);
3,283
32.510204
89
c
null
systemd-main/src/test/test-selinux.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/stat.h> #include "alloc-util.h" #include "fd-util.h" #include "log.h" #include "selinux-util.h" #include "string-util.h" #include "tests.h" #include "time-util.h" static void test_testing(void) { bool b; log_info("============ %s ==========", __func__); b = mac_selinux_use(); log_info("mac_selinux_use β†’ %s", yes_no(b)); b = mac_selinux_use(); log_info("mac_selinux_use β†’ %s", yes_no(b)); mac_selinux_retest(); b = mac_selinux_use(); log_info("mac_selinux_use β†’ %s", yes_no(b)); b = mac_selinux_use(); log_info("mac_selinux_use β†’ %s", yes_no(b)); } static void test_loading(void) { usec_t n1, n2; int r; log_info("============ %s ==========", __func__); n1 = now(CLOCK_MONOTONIC); r = mac_selinux_init(); n2 = now(CLOCK_MONOTONIC); log_info_errno(r, "mac_selinux_init β†’ %d %.2fs (%m)", r, (n2 - n1)/1e6); } static void test_cleanup(void) { usec_t n1, n2; log_info("============ %s ==========", __func__); n1 = now(CLOCK_MONOTONIC); mac_selinux_finish(); n2 = now(CLOCK_MONOTONIC); log_info("mac_selinux_finish β†’ %.2fs", (n2 - n1)/1e6); } static void test_misc(const char* fname) { _cleanup_(mac_selinux_freep) char *label = NULL, *label2 = NULL, *label3 = NULL; int r; _cleanup_close_ int fd = -EBADF; log_info("============ %s ==========", __func__); r = mac_selinux_get_our_label(&label); log_info_errno(r, "mac_selinux_get_our_label β†’ %d, \"%s\" (%m)", r, strnull(label)); r = mac_selinux_get_create_label_from_exe(fname, &label2); log_info_errno(r, "mac_selinux_create_label_from_exe β†’ %d, \"%s\" (%m)", r, strnull(label2)); fd = socket(AF_INET, SOCK_DGRAM, 0); assert_se(fd >= 0); r = mac_selinux_get_child_mls_label(fd, fname, label2, &label3); log_info_errno(r, "mac_selinux_get_child_mls_label β†’ %d, \"%s\" (%m)", r, strnull(label3)); } static void test_create_file_prepare(const char* fname) { int r; log_info("============ %s ==========", __func__); r = mac_selinux_create_file_prepare(fname, S_IRWXU); log_info_errno(r, "mac_selinux_create_file_prepare β†’ %d (%m)", r); mac_selinux_create_file_clear(); } int main(int argc, char **argv) { const char *path = SYSTEMD_BINARY_PATH; if (argc >= 2) path = argv[1]; test_setup_logging(LOG_DEBUG); test_testing(); test_loading(); test_misc(path); test_create_file_prepare(path); test_cleanup(); return 0; }
2,838
26.038095
88
c
null
systemd-main/src/test/test-serialize.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "escape.h" #include "fd-util.h" #include "fileio.h" #include "fs-util.h" #include "log.h" #include "serialize.h" #include "strv.h" #include "tests.h" #include "tmpfile-util.h" static char long_string[LONG_LINE_MAX+1]; TEST(serialize_item) { _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-serialize.XXXXXX"; _cleanup_fclose_ FILE *f = NULL; assert_se(fmkostemp_safe(fn, "r+", &f) == 0); log_info("/* %s (%s) */", __func__, fn); assert_se(serialize_item(f, "a", NULL) == 0); assert_se(serialize_item(f, "a", "bbb") == 1); assert_se(serialize_item(f, "a", "bbb") == 1); assert_se(serialize_item(f, "a", long_string) == -EINVAL); assert_se(serialize_item(f, long_string, "a") == -EINVAL); assert_se(serialize_item(f, long_string, long_string) == -EINVAL); rewind(f); _cleanup_free_ char *line1 = NULL, *line2 = NULL, *line3 = NULL; assert_se(read_line(f, LONG_LINE_MAX, &line1) > 0); assert_se(streq(line1, "a=bbb")); assert_se(read_line(f, LONG_LINE_MAX, &line2) > 0); assert_se(streq(line2, "a=bbb")); assert_se(read_line(f, LONG_LINE_MAX, &line3) == 0); assert_se(streq(line3, "")); } TEST(serialize_item_escaped) { _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-serialize.XXXXXX"; _cleanup_fclose_ FILE *f = NULL; assert_se(fmkostemp_safe(fn, "r+", &f) == 0); log_info("/* %s (%s) */", __func__, fn); assert_se(serialize_item_escaped(f, "a", NULL) == 0); assert_se(serialize_item_escaped(f, "a", "bbb") == 1); assert_se(serialize_item_escaped(f, "a", "bbb") == 1); assert_se(serialize_item_escaped(f, "a", long_string) == -EINVAL); assert_se(serialize_item_escaped(f, long_string, "a") == -EINVAL); assert_se(serialize_item_escaped(f, long_string, long_string) == -EINVAL); rewind(f); _cleanup_free_ char *line1 = NULL, *line2 = NULL, *line3 = NULL; assert_se(read_line(f, LONG_LINE_MAX, &line1) > 0); assert_se(streq(line1, "a=bbb")); assert_se(read_line(f, LONG_LINE_MAX, &line2) > 0); assert_se(streq(line2, "a=bbb")); assert_se(read_line(f, LONG_LINE_MAX, &line3) == 0); assert_se(streq(line3, "")); } TEST(serialize_usec) { _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-serialize.XXXXXX"; _cleanup_fclose_ FILE *f = NULL; assert_se(fmkostemp_safe(fn, "r+", &f) == 0); log_info("/* %s (%s) */", __func__, fn); assert_se(serialize_usec(f, "usec1", USEC_INFINITY) == 0); assert_se(serialize_usec(f, "usec2", 0) == 1); assert_se(serialize_usec(f, "usec3", USEC_INFINITY-1) == 1); rewind(f); _cleanup_free_ char *line1 = NULL, *line2 = NULL; usec_t x; assert_se(read_line(f, LONG_LINE_MAX, &line1) > 0); assert_se(streq(line1, "usec2=0")); assert_se(deserialize_usec(line1 + 6, &x) == 0); assert_se(x == 0); assert_se(read_line(f, LONG_LINE_MAX, &line2) > 0); assert_se(startswith(line2, "usec3=")); assert_se(deserialize_usec(line2 + 6, &x) == 0); assert_se(x == USEC_INFINITY-1); } TEST(serialize_strv) { _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-serialize.XXXXXX"; _cleanup_fclose_ FILE *f = NULL; char **strv = STRV_MAKE("a", "b", "foo foo", "nasty1 \"", "\"nasty2 ", "nasty3 '", "\"nasty4 \"", "nasty5\n", "\nnasty5\nfoo=bar", "\nnasty5\nfoo=bar"); assert_se(fmkostemp_safe(fn, "r+", &f) == 0); log_info("/* %s (%s) */", __func__, fn); assert_se(serialize_strv(f, "strv1", NULL) == 0); assert_se(serialize_strv(f, "strv2", STRV_MAKE_EMPTY) == 0); assert_se(serialize_strv(f, "strv3", strv) == 1); assert_se(serialize_strv(f, "strv4", STRV_MAKE(long_string)) == -EINVAL); rewind(f); _cleanup_strv_free_ char **strv2 = NULL; for (;;) { _cleanup_free_ char *line = NULL; int r; r = read_line(f, LONG_LINE_MAX, &line); if (r == 0) break; assert_se(r > 0); const char *t = startswith(line, "strv3="); assert_se(t); assert_se(deserialize_strv(&strv2, t) >= 0); } assert_se(strv_equal(strv, strv2)); } TEST(deserialize_environment) { _cleanup_strv_free_ char **env; assert_se(env = strv_new("A=1")); assert_se(deserialize_environment("B=2", &env) >= 0); assert_se(deserialize_environment("FOO%%=a\\177b\\nc\\td e", &env) >= 0); assert_se(strv_equal(env, STRV_MAKE("A=1", "B=2", "FOO%%=a\177b\nc\td e"))); assert_se(deserialize_environment("foo\\", &env) < 0); assert_se(deserialize_environment("bar\\_baz", &env) < 0); } TEST(serialize_environment) { _cleanup_strv_free_ char **env = NULL, **env2 = NULL; _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-env-util.XXXXXXX"; _cleanup_fclose_ FILE *f = NULL; int r; assert_se(fmkostemp_safe(fn, "r+", &f) == 0); log_info("/* %s (%s) */", __func__, fn); assert_se(env = strv_new("A=1", "B=2", "C=Δ…Δ™Γ³Ε‚Ε„", "D=D=a\\x0Ab", "FOO%%=a\177b\nc\td e")); assert_se(serialize_strv(f, "env", env) == 1); assert_se(fflush_and_check(f) == 0); rewind(f); for (;;) { _cleanup_free_ char *line = NULL; const char *l; r = read_line(f, LONG_LINE_MAX, &line); assert_se(r >= 0); if (r == 0) break; l = strstrip(line); assert_se(startswith(l, "env=")); r = deserialize_environment(l+4, &env2); assert_se(r >= 0); } assert_se(feof(f)); assert_se(strv_equal(env, env2)); } static int intro(void) { memset(long_string, 'x', sizeof(long_string)-1); char_array_0(long_string); return EXIT_SUCCESS; } DEFINE_TEST_MAIN_WITH_INTRO(LOG_INFO, intro);
6,605
32.704082
84
c
null
systemd-main/src/test/test-set-disable-mempool.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <pthread.h> #include "mempool.h" #include "process-util.h" #include "set.h" #include "tests.h" #define NUM 100 static void* thread(void *p) { Set **s = p; assert_se(s); assert_se(*s); assert_se(!is_main_thread()); assert_se(mempool_enabled); assert_se(!mempool_enabled()); assert_se(set_size(*s) == NUM); *s = set_free(*s); return NULL; } static void test_one(const char *val) { pthread_t t; int x[NUM] = {}; unsigned i; Set *s; log_info("Testing with SYSTEMD_MEMPOOL=%s", val); assert_se(setenv("SYSTEMD_MEMPOOL", val, true) == 0); assert_se(is_main_thread()); assert_se(mempool_enabled); /* It is a weak symbol, but we expect it to be available */ assert_se(!mempool_enabled()); assert_se(s = set_new(NULL)); for (i = 0; i < NUM; i++) assert_se(set_put(s, &x[i])); assert_se(pthread_create(&t, NULL, thread, &s) == 0); assert_se(pthread_join(t, NULL) == 0); assert_se(!s); } TEST(disable_mempool) { test_one("0"); /* The value $SYSTEMD_MEMPOOL= is cached. So the following * test should also succeed. */ test_one("1"); } DEFINE_TEST_MAIN(LOG_DEBUG);
1,362
22.101695
98
c
null
systemd-main/src/test/test-set.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "random-util.h" #include "set.h" #include "strv.h" #include "tests.h" TEST(set_steal_first) { _cleanup_set_free_ Set *m = NULL; int seen[3] = {}; char *val; m = set_new(&string_hash_ops); assert_se(m); assert_se(set_put(m, (void*) "1") == 1); assert_se(set_put(m, (void*) "22") == 1); assert_se(set_put(m, (void*) "333") == 1); while ((val = set_steal_first(m))) seen[strlen(val) - 1]++; assert_se(seen[0] == 1 && seen[1] == 1 && seen[2] == 1); assert_se(set_isempty(m)); } typedef struct Item { int seen; } Item; static void item_seen(Item *item) { item->seen++; } TEST(set_free_with_destructor) { Set *m; struct Item items[4] = {}; assert_se(m = set_new(NULL)); for (size_t i = 0; i < ELEMENTSOF(items) - 1; i++) assert_se(set_put(m, items + i) == 1); m = set_free_with_destructor(m, item_seen); assert_se(items[0].seen == 1); assert_se(items[1].seen == 1); assert_se(items[2].seen == 1); assert_se(items[3].seen == 0); } DEFINE_PRIVATE_HASH_OPS_WITH_VALUE_DESTRUCTOR(item_hash_ops, void, trivial_hash_func, trivial_compare_func, Item, item_seen); TEST(set_free_with_hash_ops) { Set *m; struct Item items[4] = {}; assert_se(m = set_new(&item_hash_ops)); for (size_t i = 0; i < ELEMENTSOF(items) - 1; i++) assert_se(set_put(m, items + i) == 1); m = set_free(m); assert_se(items[0].seen == 1); assert_se(items[1].seen == 1); assert_se(items[2].seen == 1); assert_se(items[3].seen == 0); } TEST(set_put) { _cleanup_set_free_ Set *m = NULL; m = set_new(&string_hash_ops); assert_se(m); assert_se(set_put(m, (void*) "1") == 1); assert_se(set_put(m, (void*) "22") == 1); assert_se(set_put(m, (void*) "333") == 1); assert_se(set_put(m, (void*) "333") == 0); assert_se(set_remove(m, (void*) "333")); assert_se(set_put(m, (void*) "333") == 1); assert_se(set_put(m, (void*) "333") == 0); assert_se(set_put(m, (void*) "22") == 0); _cleanup_free_ char **t = set_get_strv(m); assert_se(strv_contains(t, "1")); assert_se(strv_contains(t, "22")); assert_se(strv_contains(t, "333")); assert_se(strv_length(t) == 3); } TEST(set_put_strndup) { _cleanup_set_free_ Set *m = NULL; assert_se(set_put_strndup(&m, "12345", 0) == 1); assert_se(set_put_strndup(&m, "12345", 1) == 1); assert_se(set_put_strndup(&m, "12345", 2) == 1); assert_se(set_put_strndup(&m, "12345", 3) == 1); assert_se(set_put_strndup(&m, "12345", 4) == 1); assert_se(set_put_strndup(&m, "12345", 5) == 1); assert_se(set_put_strndup(&m, "12345", 6) == 0); assert_se(set_contains(m, "")); assert_se(set_contains(m, "1")); assert_se(set_contains(m, "12")); assert_se(set_contains(m, "123")); assert_se(set_contains(m, "1234")); assert_se(set_contains(m, "12345")); assert_se(set_size(m) == 6); } TEST(set_put_strdup) { _cleanup_set_free_ Set *m = NULL; assert_se(set_put_strdup(&m, "aaa") == 1); assert_se(set_put_strdup(&m, "aaa") == 0); assert_se(set_put_strdup(&m, "bbb") == 1); assert_se(set_put_strdup(&m, "bbb") == 0); assert_se(set_put_strdup(&m, "aaa") == 0); assert_se(set_contains(m, "aaa")); assert_se(set_contains(m, "bbb")); assert_se(set_size(m) == 2); } TEST(set_put_strdupv) { _cleanup_set_free_ Set *m = NULL; assert_se(set_put_strdupv(&m, STRV_MAKE("aaa", "aaa", "bbb", "bbb", "aaa")) == 2); assert_se(set_put_strdupv(&m, STRV_MAKE("aaa", "aaa", "bbb", "bbb", "ccc")) == 1); assert_se(set_contains(m, "aaa")); assert_se(set_contains(m, "bbb")); assert_se(set_contains(m, "ccc")); assert_se(set_size(m) == 3); } TEST(set_ensure_allocated) { _cleanup_set_free_ Set *m = NULL; assert_se(set_ensure_allocated(&m, &string_hash_ops) == 1); assert_se(set_ensure_allocated(&m, &string_hash_ops) == 0); assert_se(set_ensure_allocated(&m, NULL) == 0); assert_se(set_size(m) == 0); } TEST(set_copy) { _cleanup_set_free_ Set *s = NULL; _cleanup_set_free_free_ Set *copy = NULL; char *key1, *key2, *key3, *key4; key1 = strdup("key1"); assert_se(key1); key2 = strdup("key2"); assert_se(key2); key3 = strdup("key3"); assert_se(key3); key4 = strdup("key4"); assert_se(key4); s = set_new(&string_hash_ops); assert_se(s); assert_se(set_put(s, key1) >= 0); assert_se(set_put(s, key2) >= 0); assert_se(set_put(s, key3) >= 0); assert_se(set_put(s, key4) >= 0); copy = set_copy(s); assert_se(copy); assert_se(set_equal(s, copy)); } TEST(set_ensure_put) { _cleanup_set_free_ Set *m = NULL; assert_se(set_ensure_put(&m, &string_hash_ops, "a") == 1); assert_se(set_ensure_put(&m, &string_hash_ops, "a") == 0); assert_se(set_ensure_put(&m, NULL, "a") == 0); assert_se(set_ensure_put(&m, &string_hash_ops, "b") == 1); assert_se(set_ensure_put(&m, &string_hash_ops, "b") == 0); assert_se(set_ensure_put(&m, &string_hash_ops, "a") == 0); assert_se(set_size(m) == 2); } TEST(set_ensure_consume) { _cleanup_set_free_ Set *m = NULL; char *s, *t; assert_se(s = strdup("a")); assert_se(set_ensure_consume(&m, &string_hash_ops_free, s) == 1); assert_se(t = strdup("a")); assert_se(set_ensure_consume(&m, &string_hash_ops_free, t) == 0); assert_se(t = strdup("a")); assert_se(set_ensure_consume(&m, &string_hash_ops_free, t) == 0); assert_se(t = strdup("b")); assert_se(set_ensure_consume(&m, &string_hash_ops_free, t) == 1); assert_se(t = strdup("b")); assert_se(set_ensure_consume(&m, &string_hash_ops_free, t) == 0); assert_se(set_size(m) == 2); } TEST(set_strjoin) { _cleanup_set_free_ Set *m = NULL; _cleanup_free_ char *joined = NULL; /* Empty set */ assert_se(set_strjoin(m, NULL, false, &joined) >= 0); assert_se(!joined); assert_se(set_strjoin(m, "", false, &joined) >= 0); assert_se(!joined); assert_se(set_strjoin(m, " ", false, &joined) >= 0); assert_se(!joined); assert_se(set_strjoin(m, "xxx", false, &joined) >= 0); assert_se(!joined); assert_se(set_strjoin(m, NULL, true, &joined) >= 0); assert_se(!joined); assert_se(set_strjoin(m, "", true, &joined) >= 0); assert_se(!joined); assert_se(set_strjoin(m, " ", true, &joined) >= 0); assert_se(!joined); assert_se(set_strjoin(m, "xxx", true, &joined) >= 0); assert_se(!joined); /* Single entry */ assert_se(set_put_strdup(&m, "aaa") == 1); assert_se(set_strjoin(m, NULL, false, &joined) >= 0); assert_se(streq(joined, "aaa")); joined = mfree(joined); assert_se(set_strjoin(m, "", false, &joined) >= 0); assert_se(streq(joined, "aaa")); joined = mfree(joined); assert_se(set_strjoin(m, " ", false, &joined) >= 0); assert_se(streq(joined, "aaa")); joined = mfree(joined); assert_se(set_strjoin(m, "xxx", false, &joined) >= 0); assert_se(streq(joined, "aaa")); joined = mfree(joined); assert_se(set_strjoin(m, NULL, true, &joined) >= 0); assert_se(streq(joined, "aaa")); joined = mfree(joined); assert_se(set_strjoin(m, "", true, &joined) >= 0); assert_se(streq(joined, "aaa")); joined = mfree(joined); assert_se(set_strjoin(m, " ", true, &joined) >= 0); assert_se(streq(joined, " aaa ")); joined = mfree(joined); assert_se(set_strjoin(m, "xxx", true, &joined) >= 0); assert_se(streq(joined, "xxxaaaxxx")); /* Two entries */ assert_se(set_put_strdup(&m, "bbb") == 1); assert_se(set_put_strdup(&m, "aaa") == 0); joined = mfree(joined); assert_se(set_strjoin(m, NULL, false, &joined) >= 0); assert_se(STR_IN_SET(joined, "aaabbb", "bbbaaa")); joined = mfree(joined); assert_se(set_strjoin(m, "", false, &joined) >= 0); assert_se(STR_IN_SET(joined, "aaabbb", "bbbaaa")); joined = mfree(joined); assert_se(set_strjoin(m, " ", false, &joined) >= 0); assert_se(STR_IN_SET(joined, "aaa bbb", "bbb aaa")); joined = mfree(joined); assert_se(set_strjoin(m, "xxx", false, &joined) >= 0); assert_se(STR_IN_SET(joined, "aaaxxxbbb", "bbbxxxaaa")); joined = mfree(joined); assert_se(set_strjoin(m, NULL, true, &joined) >= 0); assert_se(STR_IN_SET(joined, "aaabbb", "bbbaaa")); joined = mfree(joined); assert_se(set_strjoin(m, "", true, &joined) >= 0); assert_se(STR_IN_SET(joined, "aaabbb", "bbbaaa")); joined = mfree(joined); assert_se(set_strjoin(m, " ", true, &joined) >= 0); assert_se(STR_IN_SET(joined, " aaa bbb ", " bbb aaa ")); joined = mfree(joined); assert_se(set_strjoin(m, "xxx", true, &joined) >= 0); assert_se(STR_IN_SET(joined, "xxxaaaxxxbbbxxx", "xxxbbbxxxaaaxxx")); } TEST(set_equal) { _cleanup_set_free_ Set *a = NULL, *b = NULL; void *p; int r; assert_se(a = set_new(NULL)); assert_se(b = set_new(NULL)); assert_se(set_equal(a, a)); assert_se(set_equal(b, b)); assert_se(set_equal(a, b)); assert_se(set_equal(b, a)); assert_se(set_equal(NULL, a)); assert_se(set_equal(NULL, b)); assert_se(set_equal(a, NULL)); assert_se(set_equal(b, NULL)); assert_se(set_equal(NULL, NULL)); for (unsigned i = 0; i < 333; i++) { p = INT32_TO_PTR(1 + (random_u32() & 0xFFFU)); r = set_put(a, p); assert_se(r >= 0 || r == -EEXIST); } assert_se(set_put(a, INT32_TO_PTR(0x1000U)) >= 0); assert_se(set_size(a) >= 2); assert_se(set_size(a) <= 334); assert_se(!set_equal(a, b)); assert_se(!set_equal(b, a)); assert_se(!set_equal(a, NULL)); SET_FOREACH(p, a) assert_se(set_put(b, p) >= 0); assert_se(set_equal(a, b)); assert_se(set_equal(b, a)); assert_se(set_remove(a, INT32_TO_PTR(0x1000U)) == INT32_TO_PTR(0x1000U)); assert_se(!set_equal(a, b)); assert_se(!set_equal(b, a)); assert_se(set_remove(b, INT32_TO_PTR(0x1000U)) == INT32_TO_PTR(0x1000U)); assert_se(set_equal(a, b)); assert_se(set_equal(b, a)); assert_se(set_put(b, INT32_TO_PTR(0x1001U)) >= 0); assert_se(!set_equal(a, b)); assert_se(!set_equal(b, a)); assert_se(set_put(a, INT32_TO_PTR(0x1001U)) >= 0); assert_se(set_equal(a, b)); assert_se(set_equal(b, a)); set_clear(a); assert_se(!set_equal(a, b)); assert_se(!set_equal(b, a)); set_clear(b); assert_se(set_equal(a, b)); assert_se(set_equal(b, a)); } TEST(set_fnmatch) { _cleanup_set_free_ Set *match = NULL, *nomatch = NULL; assert_se(set_put_strdup(&match, "aaa") >= 0); assert_se(set_put_strdup(&match, "bbb*") >= 0); assert_se(set_put_strdup(&match, "*ccc") >= 0); assert_se(set_put_strdup(&nomatch, "a*") >= 0); assert_se(set_put_strdup(&nomatch, "bbb") >= 0); assert_se(set_put_strdup(&nomatch, "ccc*") >= 0); assert_se(set_fnmatch(NULL, NULL, "")); assert_se(set_fnmatch(NULL, NULL, "hoge")); assert_se(set_fnmatch(match, NULL, "aaa")); assert_se(set_fnmatch(match, NULL, "bbb")); assert_se(set_fnmatch(match, NULL, "bbbXXX")); assert_se(set_fnmatch(match, NULL, "ccc")); assert_se(set_fnmatch(match, NULL, "XXXccc")); assert_se(!set_fnmatch(match, NULL, "")); assert_se(!set_fnmatch(match, NULL, "aaaa")); assert_se(!set_fnmatch(match, NULL, "XXbbb")); assert_se(!set_fnmatch(match, NULL, "cccXX")); assert_se(set_fnmatch(NULL, nomatch, "")); assert_se(set_fnmatch(NULL, nomatch, "Xa")); assert_se(set_fnmatch(NULL, nomatch, "bbbb")); assert_se(set_fnmatch(NULL, nomatch, "XXXccc")); assert_se(!set_fnmatch(NULL, nomatch, "a")); assert_se(!set_fnmatch(NULL, nomatch, "aXXXX")); assert_se(!set_fnmatch(NULL, nomatch, "bbb")); assert_se(!set_fnmatch(NULL, nomatch, "ccc")); assert_se(!set_fnmatch(NULL, nomatch, "cccXXX")); assert_se(set_fnmatch(match, nomatch, "bbbbb")); assert_se(set_fnmatch(match, nomatch, "XXccc")); assert_se(!set_fnmatch(match, nomatch, "")); assert_se(!set_fnmatch(match, nomatch, "a")); assert_se(!set_fnmatch(match, nomatch, "aaa")); assert_se(!set_fnmatch(match, nomatch, "b")); assert_se(!set_fnmatch(match, nomatch, "bbb")); assert_se(!set_fnmatch(match, nomatch, "ccc")); assert_se(!set_fnmatch(match, nomatch, "ccccc")); assert_se(!set_fnmatch(match, nomatch, "cccXX")); } DEFINE_TEST_MAIN(LOG_INFO);
13,675
32.851485
125
c
null
systemd-main/src/test/test-sha256.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "hexdecoct.h" #include "sha256.h" #include "string-util.h" #include "tests.h" static void sha256_process_string(const char *key, struct sha256_ctx *ctx) { sha256_process_bytes(key, strlen(key), ctx); } static void test_sha256_one(const char *key, const char *expect) { uint8_t result[SHA256_DIGEST_SIZE + 3]; _cleanup_free_ char *str = NULL; struct sha256_ctx ctx; log_debug("\"%s\" β†’ %s", key, expect); assert_se(str = new(char, strlen(key) + 4)); /* This tests unaligned buffers. */ for (size_t i = 0; i < 4; i++) { strcpy(str + i, key); for (size_t j = 0; j < 4; j++) { _cleanup_free_ char *hex_result = NULL; sha256_init_ctx(&ctx); sha256_process_string(str + i, &ctx); sha256_finish_ctx(&ctx, result + j); hex_result = hexmem(result + j, SHA256_DIGEST_SIZE); assert_se(streq_ptr(hex_result, expect)); } } } TEST(sha256) { /* Results compared with output of 'echo -n "<input>" | sha256sum -' */ test_sha256_one("abcdefghijklmnopqrstuvwxyz", "71c480df93d6ae2f1efad1447c66c9525e316218cf51fc8d9ed832f2daf18b73"); test_sha256_one("γ»γ’γ»γ’γ‚γ£γ‘γ‚‡γ‚“γΆγ‚Šγ‘", "ce7225683653be3b74861c5a4323b6baf3c3ceb361413ca99e3a5b52c04411bd"); test_sha256_one("0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789", "9cfe7faff7054298ca87557e15a10262de8d3eee77827417fbdfea1c41b9ec23"); } DEFINE_TEST_MAIN(LOG_INFO);
1,773
33.784314
127
c
null
systemd-main/src/test/test-sigbus.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <sys/mman.h> #include <unistd.h> #if HAVE_VALGRIND_VALGRIND_H # include <valgrind/valgrind.h> #endif #include "fd-util.h" #include "fs-util.h" #include "memory-util.h" #include "sigbus.h" #include "tests.h" int main(int argc, char *argv[]) { _cleanup_close_ int fd = -EBADF; char template[] = "/tmp/sigbus-test-XXXXXX"; void *addr = NULL; uint8_t *p; test_setup_logging(LOG_INFO); #if HAS_FEATURE_ADDRESS_SANITIZER return log_tests_skipped("address-sanitizer is enabled"); #endif #if HAVE_VALGRIND_VALGRIND_H if (RUNNING_ON_VALGRIND) return log_tests_skipped("This test cannot run on valgrind"); #endif sigbus_install(); assert_se(sigbus_pop(&addr) == 0); assert_se((fd = mkostemp(template, O_RDWR|O_CREAT|O_EXCL)) >= 0); assert_se(unlink(template) >= 0); assert_se(posix_fallocate_loop(fd, 0, page_size() * 8) >= 0); p = mmap(NULL, page_size() * 16, PROT_READ|PROT_WRITE, MAP_SHARED, fd, 0); assert_se(p != MAP_FAILED); assert_se(sigbus_pop(&addr) == 0); p[0] = 0xFF; assert_se(sigbus_pop(&addr) == 0); p[page_size()] = 0xFF; assert_se(sigbus_pop(&addr) == 0); p[page_size()*8] = 0xFF; p[page_size()*8+1] = 0xFF; p[page_size()*10] = 0xFF; assert_se(sigbus_pop(&addr) > 0); assert_se(addr == p + page_size() * 8); assert_se(sigbus_pop(&addr) > 0); assert_se(addr == p + page_size() * 10); assert_se(sigbus_pop(&addr) == 0); sigbus_reset(); }
1,675
25.603175
82
c
null
systemd-main/src/test/test-signal-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include "log.h" #include "macro.h" #include "signal-util.h" #include "stdio-util.h" #include "string-util.h" #include "tests.h" #include "process-util.h" #define info(sig) log_info(#sig " = " STRINGIFY(sig) " = %d", sig) TEST(rt_signals) { info(SIGRTMIN); info(SIGRTMAX); /* We use signals SIGRTMIN+0 to SIGRTMIN+24 unconditionally */ assert_se(SIGRTMAX - SIGRTMIN >= 24); } static void test_signal_to_string_one(int val) { const char *p; assert_se(p = signal_to_string(val)); assert_se(signal_from_string(p) == val); p = strjoina("SIG", p); assert_se(signal_from_string(p) == val); } static void test_signal_from_string_one(const char *s, int val) { const char *p; assert_se(signal_from_string(s) == val); p = strjoina("SIG", s); assert_se(signal_from_string(p) == val); } static void test_signal_from_string_number(const char *s, int val) { const char *p; assert_se(signal_from_string(s) == val); p = strjoina("SIG", s); assert_se(signal_from_string(p) == -EINVAL); } TEST(signal_from_string) { char buf[STRLEN("RTMIN+") + DECIMAL_STR_MAX(int) + 1]; test_signal_to_string_one(SIGHUP); test_signal_to_string_one(SIGTERM); test_signal_to_string_one(SIGRTMIN); test_signal_to_string_one(SIGRTMIN+3); test_signal_to_string_one(SIGRTMAX-4); test_signal_from_string_one("RTMIN", SIGRTMIN); test_signal_from_string_one("RTMAX", SIGRTMAX); xsprintf(buf, "RTMIN+%d", SIGRTMAX-SIGRTMIN); test_signal_from_string_one(buf, SIGRTMAX); xsprintf(buf, "RTMIN+%d", INT_MAX); test_signal_from_string_one(buf, -ERANGE); xsprintf(buf, "RTMAX-%d", SIGRTMAX-SIGRTMIN); test_signal_from_string_one(buf, SIGRTMIN); xsprintf(buf, "RTMAX-%d", INT_MAX); test_signal_from_string_one(buf, -ERANGE); test_signal_from_string_one("", -EINVAL); test_signal_from_string_one("hup", -EINVAL); test_signal_from_string_one("HOGEHOGE", -EINVAL); test_signal_from_string_one("RTMIN-5", -EINVAL); test_signal_from_string_one("RTMIN- 5", -EINVAL); test_signal_from_string_one("RTMIN -5", -EINVAL); test_signal_from_string_one("RTMIN+ 5", -EINVAL); test_signal_from_string_one("RTMIN +5", -EINVAL); test_signal_from_string_one("RTMIN+100", -ERANGE); test_signal_from_string_one("RTMIN+-3", -EINVAL); test_signal_from_string_one("RTMIN++3", -EINVAL); test_signal_from_string_one("RTMIN+HUP", -EINVAL); test_signal_from_string_one("RTMIN3", -EINVAL); test_signal_from_string_one("RTMAX+5", -EINVAL); test_signal_from_string_one("RTMAX+ 5", -EINVAL); test_signal_from_string_one("RTMAX +5", -EINVAL); test_signal_from_string_one("RTMAX- 5", -EINVAL); test_signal_from_string_one("RTMAX -5", -EINVAL); test_signal_from_string_one("RTMAX-100", -ERANGE); test_signal_from_string_one("RTMAX-+3", -EINVAL); test_signal_from_string_one("RTMAX--3", -EINVAL); test_signal_from_string_one("RTMAX-HUP", -EINVAL); test_signal_from_string_number("3", 3); test_signal_from_string_number("+5", 5); test_signal_from_string_number(" +5", 5); test_signal_from_string_number("10000", -ERANGE); test_signal_from_string_number("-2", -ERANGE); } TEST(block_signals) { assert_se(signal_is_blocked(SIGUSR1) == 0); assert_se(signal_is_blocked(SIGALRM) == 0); assert_se(signal_is_blocked(SIGVTALRM) == 0); { BLOCK_SIGNALS(SIGUSR1, SIGVTALRM); assert_se(signal_is_blocked(SIGUSR1) > 0); assert_se(signal_is_blocked(SIGALRM) == 0); assert_se(signal_is_blocked(SIGVTALRM) > 0); } assert_se(signal_is_blocked(SIGUSR1) == 0); assert_se(signal_is_blocked(SIGALRM) == 0); assert_se(signal_is_blocked(SIGVTALRM) == 0); } TEST(ignore_signals) { assert_se(ignore_signals(SIGINT) >= 0); assert_se(kill(getpid_cached(), SIGINT) >= 0); assert_se(ignore_signals(SIGUSR1, SIGUSR2, SIGTERM, SIGPIPE) >= 0); assert_se(kill(getpid_cached(), SIGUSR1) >= 0); assert_se(kill(getpid_cached(), SIGUSR2) >= 0); assert_se(kill(getpid_cached(), SIGTERM) >= 0); assert_se(kill(getpid_cached(), SIGPIPE) >= 0); assert_se(default_signals(SIGINT, SIGUSR1, SIGUSR2, SIGTERM, SIGPIPE) >= 0); } TEST(pop_pending_signal) { assert_se(signal_is_blocked(SIGUSR1) == 0); assert_se(signal_is_blocked(SIGUSR2) == 0); assert_se(pop_pending_signal(SIGUSR1) == 0); assert_se(pop_pending_signal(SIGUSR2) == 0); { BLOCK_SIGNALS(SIGUSR1, SIGUSR2); assert_se(signal_is_blocked(SIGUSR1) > 0); assert_se(signal_is_blocked(SIGUSR2) > 0); assert_se(pop_pending_signal(SIGUSR1) == 0); assert_se(pop_pending_signal(SIGUSR2) == 0); assert_se(raise(SIGUSR1) >= 0); assert_se(pop_pending_signal(SIGUSR2) == 0); assert_se(pop_pending_signal(SIGUSR1) == SIGUSR1); assert_se(pop_pending_signal(SIGUSR1) == 0); assert_se(raise(SIGUSR1) >= 0); assert_se(raise(SIGUSR2) >= 0); assert_cc(SIGUSR1 < SIGUSR2); assert_se(pop_pending_signal(SIGUSR1, SIGUSR2) == SIGUSR1); assert_se(pop_pending_signal(SIGUSR1, SIGUSR2) == SIGUSR2); assert_se(pop_pending_signal(SIGUSR1, SIGUSR2) == 0); } assert_se(signal_is_blocked(SIGUSR1) == 0); assert_se(signal_is_blocked(SIGUSR2) == 0); assert_se(pop_pending_signal(SIGUSR1) == 0); assert_se(pop_pending_signal(SIGUSR2) == 0); } DEFINE_TEST_MAIN(LOG_INFO);
6,090
33.607955
84
c
null
systemd-main/src/test/test-siphash24.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "memory-util.h" #include "siphash24.h" #include "tests.h" #define ITERATIONS 10000000ULL static void test_alignment_one(const uint8_t *in, size_t len, const uint8_t *key) { struct siphash state = {}; uint64_t out; unsigned i, j; out = siphash24(in, len, key); assert_se(out == 0xa129ca6149be45e5); /* verify the internal state as given in the above paper */ siphash24_init(&state, key); assert_se(state.v0 == 0x7469686173716475); assert_se(state.v1 == 0x6b617f6d656e6665); assert_se(state.v2 == 0x6b7f62616d677361); assert_se(state.v3 == 0x7b6b696e727e6c7b); siphash24_compress(in, len, &state); assert_se(state.v0 == 0x4a017198de0a59e0); assert_se(state.v1 == 0x0d52f6f62a4f59a4); assert_se(state.v2 == 0x634cb3577b01fd3d); assert_se(state.v3 == 0xa5224d6f55c7d9c8); out = siphash24_finalize(&state); assert_se(out == 0xa129ca6149be45e5); assert_se(state.v0 == 0xf6bcd53893fecff1); assert_se(state.v1 == 0x54b9964c7ea0d937); assert_se(state.v2 == 0x1b38329c099bb55a); assert_se(state.v3 == 0x1814bb89ad7be679); /* verify that decomposing the input in three chunks gives the same result */ for (i = 0; i < len; i++) { for (j = i; j < len; j++) { siphash24_init(&state, key); siphash24_compress(in, i, &state); siphash24_compress(&in[i], j - i, &state); siphash24_compress(&in[j], len - j, &state); out = siphash24_finalize(&state); assert_se(out == 0xa129ca6149be45e5); } } } TEST(alignment) { const uint8_t in[15] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e }; const uint8_t key[16] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f}; uint8_t in_buf[20]; /* Test with same input but different alignments. */ memcpy(in_buf, in, sizeof(in)); test_alignment_one(in_buf, sizeof(in), key); memcpy(in_buf + 1, in, sizeof(in)); test_alignment_one(in_buf + 1, sizeof(in), key); memcpy(in_buf + 2, in, sizeof(in)); test_alignment_one(in_buf + 2, sizeof(in), key); memcpy(in_buf + 4, in, sizeof(in)); test_alignment_one(in_buf + 4, sizeof(in), key); } TEST(short_hashes) { const uint8_t one[] = { 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16 }; const uint8_t key[16] = { 0x22, 0x24, 0x41, 0x22, 0x55, 0x77, 0x88, 0x07, 0x23, 0x09, 0x23, 0x14, 0x0c, 0x33, 0x0e, 0x0f}; uint8_t two[sizeof one] = {}; struct siphash state1 = {}, state2 = {}; unsigned i, j; siphash24_init(&state1, key); siphash24_init(&state2, key); /* hashing 1, 2, 3, 4, 5, ..., 16 bytes, with the byte after the buffer different */ for (i = 1; i <= sizeof one; i++) { siphash24_compress(one, i, &state1); two[i-1] = one[i-1]; siphash24_compress(two, i, &state2); assert_se(memcmp(&state1, &state2, sizeof state1) == 0); } /* hashing n and 1, n and 2, n and 3, ..., n-1 and 1, n-2 and 2, ... */ for (i = sizeof one; i > 0; i--) { zero(two); for (j = 1; j <= sizeof one; j++) { siphash24_compress(one, i, &state1); siphash24_compress(one, j, &state1); siphash24_compress(one, i, &state2); two[j-1] = one[j-1]; siphash24_compress(two, j, &state2); assert_se(memcmp(&state1, &state2, sizeof state1) == 0); } } } /* see https://131002.net/siphash/siphash.pdf, Appendix A */ DEFINE_TEST_MAIN(LOG_INFO);
4,260
38.091743
92
c
null
systemd-main/src/test/test-sizeof.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sched.h> #include <stdio.h> #include <string.h> #include <sys/resource.h> #include <sys/socket.h> #include <sys/types.h> #define __STDC_WANT_IEC_60559_TYPES_EXT__ #include <float.h> #include "time-util.h" /* Print information about various types. Useful when diagnosing * gcc diagnostics on an unfamiliar architecture. */ DISABLE_WARNING_TYPE_LIMITS; #define info_no_sign(t) \ printf("%s β†’ %zu bits, %zu byte alignment\n", STRINGIFY(t), \ sizeof(t)*CHAR_BIT, \ alignof(t)) #define info(t) \ printf("%s β†’ %zu bits%s, %zu byte alignment\n", STRINGIFY(t), \ sizeof(t)*CHAR_BIT, \ strstr(STRINGIFY(t), "signed") ? "" : \ (t)-1 < (t)0 ? ", signed" : ", unsigned", \ alignof(t)) #define check_no_sign(t, size) \ do { \ info_no_sign(t); \ assert_se(sizeof(t) == size); \ } while (false) #define check(t, size) \ do { \ info(t); \ assert_se(sizeof(t) == size); \ } while (false) enum Enum { enum_value, }; enum BigEnum { big_enum_value = UINT64_C(1), }; enum BigEnum2 { big_enum2_pos = UINT64_C(1), big_enum2_neg = UINT64_C(-1), }; int main(void) { int (*function_pointer)(void); check_no_sign(dev_t, SIZEOF_DEV_T); check_no_sign(ino_t, SIZEOF_INO_T); check_no_sign(rlim_t, SIZEOF_RLIM_T); check(time_t, SIZEOF_TIME_T); check(typeof(((struct timex *)0)->freq), SIZEOF_TIMEX_MEMBER); info_no_sign(typeof(function_pointer)); info_no_sign(void*); info(char*); info(char); info(signed char); info(unsigned char); info(short unsigned); info(unsigned); info(unsigned long); info(unsigned long long); #ifdef __GLIBC__ info(__syscall_ulong_t); info(__syscall_slong_t); #endif info(intmax_t); info(uintmax_t); info(float); info(double); info(long double); #ifdef FLT128_MAX info(_Float128); info(_Float64); info(_Float64x); info(_Float32); info(_Float32x); #endif info(size_t); info(ssize_t); info(usec_t); #ifdef __GLIBC__ info(__time_t); #endif info(pid_t); info(uid_t); info(gid_t); info(socklen_t); #ifdef __GLIBC__ info(__cpu_mask); #endif info(enum Enum); info(enum BigEnum); info(enum BigEnum2); assert_cc(sizeof(enum BigEnum2) == 8); printf("big_enum2_pos β†’ %zu\n", sizeof(big_enum2_pos)); printf("big_enum2_neg β†’ %zu\n", sizeof(big_enum2_neg)); printf("timeval: %zu\n", sizeof(struct timeval)); printf("timespec: %zu\n", sizeof(struct timespec)); void *x = malloc(100); printf("local variable: %p\n", &function_pointer); printf("glibc function: %p\n", memcpy); printf("heap allocation: %p\n", x); free(x); return 0; }
3,507
25.984615
73
c
null
systemd-main/src/test/test-sleep.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <inttypes.h> #include <linux/fiemap.h> #include <stdio.h> #include <sys/types.h> #include <unistd.h> #include "efivars.h" #include "errno-util.h" #include "fd-util.h" #include "log.h" #include "memory-util.h" #include "sleep-util.h" #include "strv.h" #include "tests.h" TEST(parse_sleep_config) { _cleanup_(free_sleep_configp) SleepConfig *sleep_config = NULL; assert_se(parse_sleep_config(&sleep_config) == 0); _cleanup_free_ char *sum = NULL, *sus = NULL, *him = NULL, *his = NULL, *hym = NULL, *hys = NULL; sum = strv_join(sleep_config->modes[SLEEP_SUSPEND], ", "); sus = strv_join(sleep_config->states[SLEEP_SUSPEND], ", "); him = strv_join(sleep_config->modes[SLEEP_HIBERNATE], ", "); his = strv_join(sleep_config->states[SLEEP_HIBERNATE], ", "); hym = strv_join(sleep_config->modes[SLEEP_HYBRID_SLEEP], ", "); hys = strv_join(sleep_config->states[SLEEP_HYBRID_SLEEP], ", "); log_debug(" allow_suspend: %s", yes_no(sleep_config->allow[SLEEP_SUSPEND])); log_debug(" allow_hibernate: %s", yes_no(sleep_config->allow[SLEEP_HIBERNATE])); log_debug(" allow_s2h: %s", yes_no(sleep_config->allow[SLEEP_SUSPEND_THEN_HIBERNATE])); log_debug(" allow_hybrid_sleep: %s", yes_no(sleep_config->allow[SLEEP_HYBRID_SLEEP])); log_debug(" suspend modes: %s", sum); log_debug(" states: %s", sus); log_debug(" hibernate modes: %s", him); log_debug(" states: %s", his); log_debug(" hybrid modes: %s", hym); log_debug(" states: %s", hys); } static int test_fiemap_one(const char *path) { _cleanup_free_ struct fiemap *fiemap = NULL; _cleanup_close_ int fd = -EBADF; int r; log_info("/* %s */", __func__); fd = open(path, O_RDONLY | O_CLOEXEC | O_NONBLOCK); if (fd < 0) return log_error_errno(errno, "failed to open %s: %m", path); r = read_fiemap(fd, &fiemap); if (r == -EOPNOTSUPP) exit(log_tests_skipped("Not supported")); if (r < 0) return log_error_errno(r, "Unable to read extent map for '%s': %m", path); log_info("extent map information for %s:", path); log_info("\t start: %" PRIu64, (uint64_t) fiemap->fm_start); log_info("\t length: %" PRIu64, (uint64_t) fiemap->fm_length); log_info("\t flags: %" PRIu32, fiemap->fm_flags); log_info("\t number of mapped extents: %" PRIu32, fiemap->fm_mapped_extents); log_info("\t extent count: %" PRIu32, fiemap->fm_extent_count); if (fiemap->fm_extent_count > 0) log_info("\t first extent location: %" PRIu64, (uint64_t) (fiemap->fm_extents[0].fe_physical / page_size())); return 0; } TEST_RET(fiemap) { int r = 0; assert_se(test_fiemap_one(saved_argv[0]) == 0); for (int i = 1; i < saved_argc; i++) { int k = test_fiemap_one(saved_argv[i]); if (r == 0) r = k; } return r; } TEST(sleep) { _cleanup_strv_free_ char **standby = strv_new("standby"), **mem = strv_new("mem"), **disk = strv_new("disk"), **suspend = strv_new("suspend"), **reboot = strv_new("reboot"), **platform = strv_new("platform"), **shutdown = strv_new("shutdown"), **freeze = strv_new("freeze"); int r; printf("Secure boot: %sd\n", enable_disable(is_efi_secure_boot())); log_info("/= individual sleep modes =/"); log_info("Standby configured: %s", yes_no(can_sleep_state(standby) > 0)); log_info("Suspend configured: %s", yes_no(can_sleep_state(mem) > 0)); log_info("Hibernate configured: %s", yes_no(can_sleep_state(disk) > 0)); log_info("Hibernate+Suspend (Hybrid-Sleep) configured: %s", yes_no(can_sleep_disk(suspend) > 0)); log_info("Hibernate+Reboot configured: %s", yes_no(can_sleep_disk(reboot) > 0)); log_info("Hibernate+Platform configured: %s", yes_no(can_sleep_disk(platform) > 0)); log_info("Hibernate+Shutdown configured: %s", yes_no(can_sleep_disk(shutdown) > 0)); log_info("Freeze configured: %s", yes_no(can_sleep_state(freeze) > 0)); log_info("/= high-level sleep verbs =/"); r = can_sleep(SLEEP_SUSPEND); log_info("Suspend configured and possible: %s", r >= 0 ? yes_no(r) : STRERROR(r)); r = can_sleep(SLEEP_HIBERNATE); log_info("Hibernation configured and possible: %s", r >= 0 ? yes_no(r) : STRERROR(r)); r = can_sleep(SLEEP_HYBRID_SLEEP); log_info("Hybrid-sleep configured and possible: %s", r >= 0 ? yes_no(r) : STRERROR(r)); r = can_sleep(SLEEP_SUSPEND_THEN_HIBERNATE); log_info("Suspend-then-Hibernate configured and possible: %s", r >= 0 ? yes_no(r) : STRERROR(r)); } TEST(fetch_batteries_capacity_by_name) { _cleanup_hashmap_free_ Hashmap *capacity = NULL; int r; assert_se(fetch_batteries_capacity_by_name(&capacity) >= 0); log_debug("fetch_batteries_capacity_by_name: %u entries", hashmap_size(capacity)); const char *name; void *cap; HASHMAP_FOREACH_KEY(cap, name, capacity) { assert(cap); /* Anything non-null is fine. */ log_info("Battery %s: capacity = %i", name, get_capacity_by_name(capacity, name)); } for (int i = 0; i < 2; i++) { usec_t interval; if (i > 0) sleep(1); r = get_total_suspend_interval(capacity, &interval); assert_se(r >= 0 || r == -ENOENT); log_info("%d: get_total_suspend_interval: %s", i, r < 0 ? STRERROR(r) : FORMAT_TIMESPAN(interval, USEC_PER_SEC)); } } static int intro(void) { if (getuid() != 0) log_warning("This program is unlikely to work for unprivileged users"); return EXIT_SUCCESS; } DEFINE_TEST_MAIN_WITH_INTRO(LOG_DEBUG, intro);
6,273
39.477419
105
c
null
systemd-main/src/test/test-stat-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <linux/magic.h> #include <sched.h> #include <unistd.h> #include "alloc-util.h" #include "errno-list.h" #include "fd-util.h" #include "fs-util.h" #include "macro.h" #include "mountpoint-util.h" #include "namespace-util.h" #include "path-util.h" #include "rm-rf.h" #include "stat-util.h" #include "tests.h" #include "tmpfile-util.h" TEST(null_or_empty_path) { assert_se(null_or_empty_path("/dev/null") == 1); assert_se(null_or_empty_path("/dev/tty") == 1); /* We assume that any character device is "empty", bleh. */ assert_se(null_or_empty_path("../../../../../../../../../../../../../../../../../../../../dev/null") == 1); assert_se(null_or_empty_path("/proc/self/exe") == 0); assert_se(null_or_empty_path("/nosuchfileordir") == -ENOENT); } TEST(null_or_empty_path_with_root) { assert_se(null_or_empty_path_with_root("/dev/null", NULL) == 1); assert_se(null_or_empty_path_with_root("/dev/null", "/") == 1); assert_se(null_or_empty_path_with_root("/dev/null", "/.././../") == 1); assert_se(null_or_empty_path_with_root("/dev/null", "/.././..") == 1); assert_se(null_or_empty_path_with_root("../../../../../../../../../../../../../../../../../../../../dev/null", NULL) == 1); assert_se(null_or_empty_path_with_root("../../../../../../../../../../../../../../../../../../../../dev/null", "/") == 1); assert_se(null_or_empty_path_with_root("/proc/self/exe", NULL) == 0); assert_se(null_or_empty_path_with_root("/proc/self/exe", "/") == 0); assert_se(null_or_empty_path_with_root("/nosuchfileordir", NULL) == -ENOENT); assert_se(null_or_empty_path_with_root("/nosuchfileordir", "/.././../") == -ENOENT); assert_se(null_or_empty_path_with_root("/nosuchfileordir", "/.././..") == -ENOENT); assert_se(null_or_empty_path_with_root("/foobar/barbar/dev/null", "/foobar/barbar") == 1); assert_se(null_or_empty_path_with_root("/foobar/barbar/dev/null", "/foobar/barbar/") == 1); } TEST(inode_same) { _cleanup_close_ int fd = -EBADF; _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-files_same.XXXXXX"; _cleanup_(unlink_tempfilep) char name_alias[] = "/tmp/test-files_same.alias"; fd = mkostemp_safe(name); assert_se(fd >= 0); assert_se(symlink(name, name_alias) >= 0); assert_se(inode_same(name, name, 0)); assert_se(inode_same(name, name, AT_SYMLINK_NOFOLLOW)); assert_se(inode_same(name, name_alias, 0)); assert_se(!inode_same(name, name_alias, AT_SYMLINK_NOFOLLOW)); } TEST(is_symlink) { _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-is_symlink.XXXXXX"; _cleanup_(unlink_tempfilep) char name_link[] = "/tmp/test-is_symlink.link"; _cleanup_close_ int fd = -EBADF; fd = mkostemp_safe(name); assert_se(fd >= 0); assert_se(symlink(name, name_link) >= 0); assert_se(is_symlink(name) == 0); assert_se(is_symlink(name_link) == 1); assert_se(is_symlink("/a/file/which/does/not/exist/i/guess") < 0); } TEST(path_is_fs_type) { /* run might not be a mount point in build chroots */ if (path_is_mount_point("/run", NULL, AT_SYMLINK_FOLLOW) > 0) { assert_se(path_is_fs_type("/run", TMPFS_MAGIC) > 0); assert_se(path_is_fs_type("/run", BTRFS_SUPER_MAGIC) == 0); } if (path_is_mount_point("/proc", NULL, AT_SYMLINK_FOLLOW) > 0) { assert_se(path_is_fs_type("/proc", PROC_SUPER_MAGIC) > 0); assert_se(path_is_fs_type("/proc", BTRFS_SUPER_MAGIC) == 0); } assert_se(path_is_fs_type("/i-dont-exist", BTRFS_SUPER_MAGIC) == -ENOENT); } TEST(path_is_temporary_fs) { int r; FOREACH_STRING(s, "/", "/run", "/sys", "/sys/", "/proc", "/i-dont-exist", "/var", "/var/lib") { r = path_is_temporary_fs(s); log_info_errno(r, "path_is_temporary_fs(\"%s\"): %d, %s", s, r, r < 0 ? errno_to_name(r) : yes_no(r)); } /* run might not be a mount point in build chroots */ if (path_is_mount_point("/run", NULL, AT_SYMLINK_FOLLOW) > 0) assert_se(path_is_temporary_fs("/run") > 0); assert_se(path_is_temporary_fs("/proc") == 0); assert_se(path_is_temporary_fs("/i-dont-exist") == -ENOENT); } TEST(path_is_read_only_fs) { int r; FOREACH_STRING(s, "/", "/run", "/sys", "/sys/", "/proc", "/i-dont-exist", "/var", "/var/lib") { r = path_is_read_only_fs(s); log_info_errno(r, "path_is_read_only_fs(\"%s\"): %d, %s", s, r, r < 0 ? errno_to_name(r) : yes_no(r)); } if (path_is_mount_point("/sys", NULL, AT_SYMLINK_FOLLOW) > 0) assert_se(IN_SET(path_is_read_only_fs("/sys"), 0, 1)); assert_se(path_is_read_only_fs("/proc") == 0); assert_se(path_is_read_only_fs("/i-dont-exist") == -ENOENT); } TEST(fd_is_ns) { _cleanup_close_ int fd = -EBADF; assert_se(fd_is_ns(STDIN_FILENO, CLONE_NEWNET) == 0); assert_se(fd_is_ns(STDERR_FILENO, CLONE_NEWNET) == 0); assert_se(fd_is_ns(STDOUT_FILENO, CLONE_NEWNET) == 0); fd = open("/proc/self/ns/mnt", O_CLOEXEC|O_RDONLY); if (fd < 0) { assert_se(errno == ENOENT); log_notice("Path %s not found, skipping test", "/proc/self/ns/mnt"); return; } assert_se(fd >= 0); assert_se(IN_SET(fd_is_ns(fd, CLONE_NEWNET), 0, -EUCLEAN)); fd = safe_close(fd); assert_se((fd = open("/proc/self/ns/ipc", O_CLOEXEC|O_RDONLY)) >= 0); assert_se(IN_SET(fd_is_ns(fd, CLONE_NEWIPC), 1, -EUCLEAN)); fd = safe_close(fd); assert_se((fd = open("/proc/self/ns/net", O_CLOEXEC|O_RDONLY)) >= 0); assert_se(IN_SET(fd_is_ns(fd, CLONE_NEWNET), 1, -EUCLEAN)); } TEST(dir_is_empty) { _cleanup_(rm_rf_physical_and_freep) char *empty_dir = NULL; _cleanup_free_ char *j = NULL, *jj = NULL, *jjj = NULL; assert_se(dir_is_empty_at(AT_FDCWD, "/proc", /* ignore_hidden_or_backup= */ true) == 0); assert_se(dir_is_empty_at(AT_FDCWD, "/icertainlydontexistdoi", /* ignore_hidden_or_backup= */ true) == -ENOENT); assert_se(mkdtemp_malloc("/tmp/emptyXXXXXX", &empty_dir) >= 0); assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ true) > 0); j = path_join(empty_dir, "zzz"); assert_se(j); assert_se(touch(j) >= 0); assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ true) == 0); jj = path_join(empty_dir, "ppp"); assert_se(jj); assert_se(touch(jj) >= 0); jjj = path_join(empty_dir, ".qqq"); assert_se(jjj); assert_se(touch(jjj) >= 0); assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ true) == 0); assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ false) == 0); assert_se(unlink(j) >= 0); assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ true) == 0); assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ false) == 0); assert_se(unlink(jj) >= 0); assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ true) > 0); assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ false) == 0); assert_se(unlink(jjj) >= 0); assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ true) > 0); assert_se(dir_is_empty_at(AT_FDCWD, empty_dir, /* ignore_hidden_or_backup= */ false) > 0); } static int intro(void) { log_show_color(true); return EXIT_SUCCESS; } DEFINE_TEST_MAIN_WITH_INTRO(LOG_INFO, intro);
8,043
41.560847
131
c
null
systemd-main/src/test/test-static-destruct.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "static-destruct.h" #include "strv.h" #include "tests.h" static int foo = 0; static int bar = 0; static int baz = 0; static char *memory = NULL; static char **strings = NULL; static size_t n_strings = 0; static int *integers = NULL; static size_t n_integers = 0; static void test_destroy(int *b) { (*b)++; } static void test_strings_destroy(char **array, size_t n) { assert_se(n == 3); assert_se(strv_equal(array, STRV_MAKE("a", "bbb", "ccc"))); strv_free(array); } static void test_integers_destroy(int *array, size_t n) { assert_se(n == 10); for (size_t i = 0; i < n; i++) assert_se(array[i] == (int)(i * i)); free(array); } STATIC_DESTRUCTOR_REGISTER(foo, test_destroy); STATIC_DESTRUCTOR_REGISTER(bar, test_destroy); STATIC_DESTRUCTOR_REGISTER(bar, test_destroy); STATIC_DESTRUCTOR_REGISTER(baz, test_destroy); STATIC_DESTRUCTOR_REGISTER(baz, test_destroy); STATIC_DESTRUCTOR_REGISTER(baz, test_destroy); STATIC_DESTRUCTOR_REGISTER(memory, freep); STATIC_ARRAY_DESTRUCTOR_REGISTER(strings, n_strings, test_strings_destroy); STATIC_ARRAY_DESTRUCTOR_REGISTER(integers, n_integers, test_integers_destroy); TEST(static_destruct) { assert_se(foo == 0 && bar == 0 && baz == 0); assert_se(memory = strdup("hallo")); assert_se(strings = strv_new("a", "bbb", "ccc")); n_strings = strv_length(strings); n_integers = 10; assert_se(integers = new(int, n_integers)); for (size_t i = 0; i < n_integers; i++) integers[i] = i * i; static_destruct(); assert_se(foo == 1 && bar == 2 && baz == 3); assert_se(!memory); assert_se(!strings); assert_se(n_strings == 0); assert_se(!integers); assert_se(n_integers == 0); } DEFINE_TEST_MAIN(LOG_INFO);
1,926
27.338235
78
c
null
systemd-main/src/test/test-strbuf.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdlib.h> #include "nulstr-util.h" #include "strbuf.h" #include "string-util.h" #include "strv.h" #include "tests.h" static ssize_t add_string(struct strbuf *sb, const char *s) { return strbuf_add_string(sb, s, strlen(s)); } TEST(strbuf) { _cleanup_(strbuf_freep) struct strbuf *sb = NULL; _cleanup_strv_free_ char **l = NULL; ssize_t a, b, c, d, e, f, g, h; sb = strbuf_new(); a = add_string(sb, "waldo"); b = add_string(sb, "foo"); c = add_string(sb, "bar"); d = add_string(sb, "waldo"); /* duplicate */ e = add_string(sb, "aldo"); /* duplicate */ f = add_string(sb, "do"); /* duplicate */ g = add_string(sb, "waldorf"); /* not a duplicate: matches from tail */ h = add_string(sb, ""); /* check the content of the buffer directly */ l = strv_parse_nulstr(sb->buf, sb->len); assert_se(l); assert_se(streq(l[0], "")); /* root */ assert_se(streq(l[1], "waldo")); assert_se(streq(l[2], "foo")); assert_se(streq(l[3], "bar")); assert_se(streq(l[4], "waldorf")); assert_se(l[5] == NULL); assert_se(sb->nodes_count == 5); /* root + 4 non-duplicates */ assert_se(sb->dedup_count == 4); assert_se(sb->in_count == 8); assert_se(sb->in_len == 29); /* length of all strings added */ assert_se(sb->dedup_len == 11); /* length of all strings duplicated */ assert_se(sb->len == 23); /* buffer length: in - dedup + \0 for each node */ /* check the returned offsets and the respective content in the buffer */ assert_se(a == 1); assert_se(b == 7); assert_se(c == 11); assert_se(d == 1); assert_se(e == 2); assert_se(f == 4); assert_se(g == 15); assert_se(h == 0); assert_se(streq(sb->buf + a, "waldo")); assert_se(streq(sb->buf + b, "foo")); assert_se(streq(sb->buf + c, "bar")); assert_se(streq(sb->buf + d, "waldo")); assert_se(streq(sb->buf + e, "aldo")); assert_se(streq(sb->buf + f, "do")); assert_se(streq(sb->buf + g, "waldorf")); assert_se(streq(sb->buf + h, "")); strbuf_complete(sb); assert_se(sb->root == NULL); } DEFINE_TEST_MAIN(LOG_INFO);
2,406
31.527027
90
c
null
systemd-main/src/test/test-strxcpyx.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdio.h> #include "string-util.h" #include "strxcpyx.h" #include "tests.h" TEST(strpcpy) { char target[25]; char *s = target; size_t space_left; bool truncated; space_left = sizeof(target); space_left = strpcpy_full(&s, space_left, "12345", &truncated); assert_se(!truncated); space_left = strpcpy_full(&s, space_left, "hey hey hey", &truncated); assert_se(!truncated); space_left = strpcpy_full(&s, space_left, "waldo", &truncated); assert_se(!truncated); space_left = strpcpy_full(&s, space_left, "ba", &truncated); assert_se(!truncated); space_left = strpcpy_full(&s, space_left, "r", &truncated); assert_se(!truncated); assert_se(space_left == 1); assert_se(streq(target, "12345hey hey heywaldobar")); space_left = strpcpy_full(&s, space_left, "", &truncated); assert_se(!truncated); assert_se(space_left == 1); assert_se(streq(target, "12345hey hey heywaldobar")); space_left = strpcpy_full(&s, space_left, "f", &truncated); assert_se(truncated); assert_se(space_left == 0); assert_se(streq(target, "12345hey hey heywaldobar")); space_left = strpcpy_full(&s, space_left, "", &truncated); assert_se(!truncated); assert_se(space_left == 0); assert_se(streq(target, "12345hey hey heywaldobar")); space_left = strpcpy_full(&s, space_left, "foo", &truncated); assert_se(truncated); assert_se(space_left == 0); assert_se(streq(target, "12345hey hey heywaldobar")); } TEST(strpcpyf) { char target[25]; char *s = target; size_t space_left; bool truncated; space_left = sizeof(target); space_left = strpcpyf_full(&s, space_left, &truncated, "space left: %zu. ", space_left); assert_se(!truncated); space_left = strpcpyf_full(&s, space_left, &truncated, "foo%s", "bar"); assert_se(!truncated); assert_se(space_left == 3); assert_se(streq(target, "space left: 25. foobar")); space_left = strpcpyf_full(&s, space_left, &truncated, "%i", 42); assert_se(!truncated); assert_se(space_left == 1); assert_se(streq(target, "space left: 25. foobar42")); space_left = strpcpyf_full(&s, space_left, &truncated, "%s", ""); assert_se(!truncated); assert_se(space_left == 1); assert_se(streq(target, "space left: 25. foobar42")); space_left = strpcpyf_full(&s, space_left, &truncated, "%c", 'x'); assert_se(truncated); assert_se(space_left == 0); assert_se(streq(target, "space left: 25. foobar42")); space_left = strpcpyf_full(&s, space_left, &truncated, "%s", ""); assert_se(!truncated); assert_se(space_left == 0); assert_se(streq(target, "space left: 25. foobar42")); space_left = strpcpyf_full(&s, space_left, &truncated, "abc%s", "hoge"); assert_se(truncated); assert_se(space_left == 0); assert_se(streq(target, "space left: 25. foobar42")); /* test overflow */ s = target; space_left = strpcpyf_full(&s, 12, &truncated, "00 left: %i. ", 999); assert_se(truncated); assert_se(streq(target, "00 left: 99")); assert_se(space_left == 0); assert_se(target[12] == '2'); } TEST(strpcpyl) { char target[25]; char *s = target; size_t space_left; bool truncated; space_left = sizeof(target); space_left = strpcpyl_full(&s, space_left, &truncated, "waldo", " test", " waldo. ", NULL); assert_se(!truncated); space_left = strpcpyl_full(&s, space_left, &truncated, "Banana", NULL); assert_se(!truncated); assert_se(space_left == 1); assert_se(streq(target, "waldo test waldo. Banana")); space_left = strpcpyl_full(&s, space_left, &truncated, "", "", "", NULL); assert_se(!truncated); assert_se(space_left == 1); assert_se(streq(target, "waldo test waldo. Banana")); space_left = strpcpyl_full(&s, space_left, &truncated, "", "x", "", NULL); assert_se(truncated); assert_se(space_left == 0); assert_se(streq(target, "waldo test waldo. Banana")); space_left = strpcpyl_full(&s, space_left, &truncated, "hoge", NULL); assert_se(truncated); assert_se(space_left == 0); assert_se(streq(target, "waldo test waldo. Banana")); } TEST(strscpy) { char target[25]; size_t space_left; bool truncated; space_left = sizeof(target); space_left = strscpy_full(target, space_left, "12345", &truncated); assert_se(!truncated); assert_se(streq(target, "12345")); assert_se(space_left == 20); } TEST(strscpyl) { char target[25]; size_t space_left; bool truncated; space_left = sizeof(target); space_left = strscpyl_full(target, space_left, &truncated, "12345", "waldo", "waldo", NULL); assert_se(!truncated); assert_se(streq(target, "12345waldowaldo")); assert_se(space_left == 10); } TEST(sd_event_code_migration) { char b[100 * DECIMAL_STR_MAX(unsigned) + 1]; char c[100 * DECIMAL_STR_MAX(unsigned) + 1], *p; unsigned i; size_t l; int o, r; for (i = o = 0; i < 100; i++) { r = snprintf(&b[o], sizeof(b) - o, "%u ", i); assert_se(r >= 0 && r < (int) sizeof(b) - o); o += r; } p = c; l = sizeof(c); for (i = 0; i < 100; i++) l = strpcpyf(&p, l, "%u ", i); assert_se(streq(b, c)); } DEFINE_TEST_MAIN(LOG_INFO);
5,889
32.465909
100
c
null
systemd-main/src/test/test-sysctl-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <sys/utsname.h> #include "sd-id128.h" #include "errno-util.h" #include "hostname-util.h" #include "strv.h" #include "sysctl-util.h" #include "tests.h" static const char* const cases[] = { "a.b.c", "a/b/c", "a/b/c", "a/b/c", "a/b.c/d", "a/b.c/d", "a.b/c.d", "a/b.c/d", "net.ipv4.conf.enp3s0/200.forwarding", "net/ipv4/conf/enp3s0.200/forwarding", "net/ipv4/conf/enp3s0.200/forwarding", "net/ipv4/conf/enp3s0.200/forwarding", "a...b...c", "a/b/c", "a///b///c", "a/b/c", ".a...b...c", "a/b/c", "/a///b///c", "a/b/c", NULL, }; TEST(sysctl_normalize) { STRV_FOREACH_PAIR(s, expected, cases) { _cleanup_free_ char *t; assert_se(t = strdup(*s)); assert_se(sysctl_normalize(t) == t); log_info("\"%s\" β†’ \"%s\", expected \"%s\"", *s, t, *expected); assert_se(streq(t, *expected)); } } TEST(sysctl_read) { _cleanup_free_ char *s = NULL; struct utsname u; sd_id128_t a, b; int r; assert_se(sysctl_read("kernel/random/boot_id", &s) >= 0); assert_se(sd_id128_from_string(s, &a) >= 0); assert_se(sd_id128_get_boot(&b) >= 0); assert_se(sd_id128_equal(a, b)); s = mfree(s); assert_se(sysctl_read_ip_property(AF_INET, "lo", "forwarding", &s)); assert_se(STR_IN_SET(s, "0", "1")); r = sysctl_write_ip_property(AF_INET, "lo", "forwarding", s); assert_se(r >= 0 || ERRNO_IS_PRIVILEGE(r) || r == -EROFS); s = mfree(s); assert_se(sysctl_read_ip_property(AF_INET, NULL, "ip_forward", &s)); assert_se(STR_IN_SET(s, "0", "1")); r = sysctl_write_ip_property(AF_INET, NULL, "ip_forward", s); assert_se(r >= 0 || ERRNO_IS_PRIVILEGE(r) || r == -EROFS); s = mfree(s); assert_se(sysctl_read("kernel/hostname", &s) >= 0); assert_se(uname(&u) >= 0); assert_se(streq_ptr(s, u.nodename)); r = sysctl_write("kernel/hostname", s); assert_se(r >= 0 || ERRNO_IS_PRIVILEGE(r) || r == -EROFS); } DEFINE_TEST_MAIN(LOG_INFO);
2,235
28.421053
85
c
null
systemd-main/src/test/test-tables.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "architecture.h" #include "automount.h" #include "cgroup.h" #include "cgroup-util.h" #include "compress.h" #include "condition.h" #include "confidential-virt.h" #include "device-private.h" #include "device.h" #include "discover-image.h" #include "execute.h" #include "import-util.h" #include "install.h" #include "job.h" #include "journald-server.h" #include "kill.h" #include "link-config.h" #include "locale-util.h" #include "log.h" #include "logs-show.h" #include "mount.h" #include "path.h" #include "process-util.h" #include "resolve-util.h" #include "rlimit-util.h" #include "scope.h" #include "service.h" #include "show-status.h" #include "slice.h" #include "socket-util.h" #include "socket.h" #include "swap.h" #include "target.h" #include "test-tables.h" #include "timer.h" #include "unit-name.h" #include "unit.h" #include "virt.h" int main(int argc, char **argv) { test_table(architecture, ARCHITECTURE); test_table(assert_type, CONDITION_TYPE); test_table(automount_result, AUTOMOUNT_RESULT); test_table(automount_state, AUTOMOUNT_STATE); test_table(cgroup_controller, CGROUP_CONTROLLER); test_table(cgroup_device_policy, CGROUP_DEVICE_POLICY); test_table(cgroup_io_limit_type, CGROUP_IO_LIMIT_TYPE); test_table(collect_mode, COLLECT_MODE); test_table(condition_result, CONDITION_RESULT); test_table(condition_type, CONDITION_TYPE); test_table(confidential_virtualization, CONFIDENTIAL_VIRTUALIZATION); test_table(device_action, SD_DEVICE_ACTION); test_table(device_state, DEVICE_STATE); test_table(dns_over_tls_mode, DNS_OVER_TLS_MODE); test_table(dnssec_mode, DNSSEC_MODE); test_table(emergency_action, EMERGENCY_ACTION); test_table(exec_directory_type, EXEC_DIRECTORY_TYPE); test_table(exec_input, EXEC_INPUT); test_table(exec_keyring_mode, EXEC_KEYRING_MODE); test_table(exec_output, EXEC_OUTPUT); test_table(exec_preserve_mode, EXEC_PRESERVE_MODE); test_table(exec_utmp_mode, EXEC_UTMP_MODE); test_table(image_type, IMAGE_TYPE); test_table(import_verify, IMPORT_VERIFY); test_table(job_mode, JOB_MODE); test_table(job_result, JOB_RESULT); test_table(job_state, JOB_STATE); test_table(job_type, JOB_TYPE); test_table(kill_mode, KILL_MODE); test_table(kill_who, KILL_WHO); test_table(locale_variable, VARIABLE_LC); test_table(log_target, LOG_TARGET); test_table(mac_address_policy, MAC_ADDRESS_POLICY); test_table(managed_oom_mode, MANAGED_OOM_MODE); test_table(managed_oom_preference, MANAGED_OOM_PREFERENCE); test_table(manager_state, MANAGER_STATE); test_table(manager_timestamp, MANAGER_TIMESTAMP); test_table(mount_exec_command, MOUNT_EXEC_COMMAND); test_table(mount_result, MOUNT_RESULT); test_table(mount_state, MOUNT_STATE); test_table(name_policy, NAMEPOLICY); test_table(namespace_type, NAMESPACE_TYPE); test_table(notify_access, NOTIFY_ACCESS); test_table(notify_state, NOTIFY_STATE); test_table(output_mode, OUTPUT_MODE); test_table(partition_designator, PARTITION_DESIGNATOR); test_table(path_result, PATH_RESULT); test_table(path_state, PATH_STATE); test_table(path_type, PATH_TYPE); test_table(protect_home, PROTECT_HOME); test_table(protect_system, PROTECT_SYSTEM); test_table(resolve_support, RESOLVE_SUPPORT); test_table(rlimit, RLIMIT); test_table(scope_result, SCOPE_RESULT); test_table(scope_state, SCOPE_STATE); test_table(service_exec_command, SERVICE_EXEC_COMMAND); test_table(service_restart, SERVICE_RESTART); test_table(service_restart_mode, SERVICE_RESTART_MODE); test_table(service_result, SERVICE_RESULT); test_table(service_state, SERVICE_STATE); test_table(service_type, SERVICE_TYPE); test_table(show_status, SHOW_STATUS); test_table(slice_state, SLICE_STATE); test_table(socket_address_bind_ipv6_only, SOCKET_ADDRESS_BIND_IPV6_ONLY); test_table(socket_exec_command, SOCKET_EXEC_COMMAND); test_table(socket_result, SOCKET_RESULT); test_table(socket_state, SOCKET_STATE); test_table(split_mode, SPLIT); test_table(storage, STORAGE); test_table(swap_exec_command, SWAP_EXEC_COMMAND); test_table(swap_result, SWAP_RESULT); test_table(swap_state, SWAP_STATE); test_table(target_state, TARGET_STATE); test_table(timer_base, TIMER_BASE); test_table(timer_result, TIMER_RESULT); test_table(timer_state, TIMER_STATE); test_table(unit_active_state, UNIT_ACTIVE_STATE); test_table(unit_dependency, UNIT_DEPENDENCY); test_table(install_change_type, INSTALL_CHANGE_TYPE); test_table(unit_file_preset_mode, UNIT_FILE_PRESET_MODE); test_table(unit_file_state, UNIT_FILE_STATE); test_table(unit_load_state, UNIT_LOAD_STATE); test_table(unit_type, UNIT_TYPE); test_table(virtualization, VIRTUALIZATION); test_table(compression, COMPRESSION); assert_cc(sizeof(sd_device_action_t) == sizeof(int64_t)); return EXIT_SUCCESS; }
5,413
39.706767
81
c
null
systemd-main/src/test/test-terminal-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <stdbool.h> #include <stdio.h> #include <sys/stat.h> #include <unistd.h> #include "alloc-util.h" #include "fd-util.h" #include "fs-util.h" #include "macro.h" #include "path-util.h" #include "strv.h" #include "terminal-util.h" #include "tests.h" #include "tmpfile-util.h" #define LOREM_IPSUM "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor " \ "incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation " \ "ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit " \ "in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat " \ "non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." TEST(default_term_for_tty) { puts(default_term_for_tty("/dev/tty23")); puts(default_term_for_tty("/dev/ttyS23")); puts(default_term_for_tty("/dev/tty0")); puts(default_term_for_tty("/dev/pty0")); puts(default_term_for_tty("/dev/pts/0")); puts(default_term_for_tty("/dev/console")); puts(default_term_for_tty("tty23")); puts(default_term_for_tty("ttyS23")); puts(default_term_for_tty("tty0")); puts(default_term_for_tty("pty0")); puts(default_term_for_tty("pts/0")); puts(default_term_for_tty("console")); } TEST(read_one_char) { _cleanup_fclose_ FILE *file = NULL; char r; bool need_nl; _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-read_one_char.XXXXXX"; assert_se(fmkostemp_safe(name, "r+", &file) == 0); assert_se(fputs("c\n", file) >= 0); rewind(file); assert_se(read_one_char(file, &r, 1000000, &need_nl) >= 0); assert_se(!need_nl); assert_se(r == 'c'); assert_se(read_one_char(file, &r, 1000000, &need_nl) < 0); rewind(file); assert_se(fputs("foobar\n", file) >= 0); rewind(file); assert_se(read_one_char(file, &r, 1000000, &need_nl) < 0); rewind(file); assert_se(fputs("\n", file) >= 0); rewind(file); assert_se(read_one_char(file, &r, 1000000, &need_nl) < 0); } TEST(getttyname_malloc) { _cleanup_free_ char *ttyname = NULL; _cleanup_close_ int master = -EBADF; assert_se((master = posix_openpt(O_RDWR|O_NOCTTY)) >= 0); assert_se(getttyname_malloc(master, &ttyname) >= 0); log_info("ttyname = %s", ttyname); assert_se(PATH_IN_SET(ttyname, "ptmx", "pts/ptmx")); } typedef struct { const char *name; const char* (*func)(void); } Color; static const Color colors[] = { { "normal", ansi_normal }, { "highlight", ansi_highlight }, { "black", ansi_black }, { "red", ansi_red }, { "green", ansi_green }, { "yellow", ansi_yellow }, { "blue", ansi_blue }, { "magenta", ansi_magenta }, { "cyan", ansi_cyan }, { "white", ansi_white }, { "grey", ansi_grey }, { "bright-black", ansi_bright_black }, { "bright-red", ansi_bright_red }, { "bright-green", ansi_bright_green }, { "bright-yellow", ansi_bright_yellow }, { "bright-blue", ansi_bright_blue }, { "bright-magenta", ansi_bright_magenta }, { "bright-cyan", ansi_bright_cyan }, { "bright-white", ansi_bright_white }, { "highlight-black", ansi_highlight_black }, { "highlight-red", ansi_highlight_red }, { "highlight-green", ansi_highlight_green }, { "highlight-yellow (original)", _ansi_highlight_yellow }, { "highlight-yellow (replacement)", ansi_highlight_yellow }, { "highlight-blue", ansi_highlight_blue }, { "highlight-magenta", ansi_highlight_magenta }, { "highlight-cyan", ansi_highlight_cyan }, { "highlight-white", ansi_highlight_white }, { "highlight-grey", ansi_highlight_grey }, { "underline", ansi_underline }, { "highlight-underline", ansi_highlight_underline }, { "highlight-red-underline", ansi_highlight_red_underline }, { "highlight-green-underline", ansi_highlight_green_underline }, { "highlight-yellow-underline", ansi_highlight_yellow_underline }, { "highlight-blue-underline", ansi_highlight_blue_underline }, { "highlight-magenta-underline", ansi_highlight_magenta_underline }, { "highlight-grey-underline", ansi_highlight_grey_underline }, }; TEST(colors) { for (size_t i = 0; i < ELEMENTSOF(colors); i++) printf("<%s%s%s>\n", colors[i].func(), colors[i].name, ansi_normal()); } TEST(text) { for (size_t i = 0; !streq(colors[i].name, "underline"); i++) { bool blwh = strstr(colors[i].name, "black") || strstr(colors[i].name, "white"); printf("\n" "Testing color %s%s\n%s%s%s\n", colors[i].name, blwh ? "" : ", this text should be readable", colors[i].func(), LOREM_IPSUM, ansi_normal()); } } TEST(get_ctty) { _cleanup_free_ char *ctty = NULL; struct stat st; dev_t devnr; int r; r = get_ctty(0, &devnr, &ctty); if (r < 0) { log_notice_errno(r, "Apparently called without a controlling TTY, cutting get_ctty() test short: %m"); return; } /* In almost all cases STDIN will match our controlling TTY. Let's verify that and then compare paths */ assert_se(fstat(STDIN_FILENO, &st) >= 0); if (S_ISCHR(st.st_mode) && st.st_rdev == devnr) { _cleanup_free_ char *stdin_name = NULL; assert_se(getttyname_malloc(STDIN_FILENO, &stdin_name) >= 0); assert_se(path_equal(stdin_name, ctty)); } else log_notice("Not invoked with stdin == ctty, cutting get_ctty() test short"); } DEFINE_TEST_MAIN(LOG_INFO);
6,190
35.633136
118
c
null
systemd-main/src/test/test-tmpfile-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "errno-util.h" #include "fd-util.h" #include "fileio.h" #include "format-util.h" #include "fs-util.h" #include "log.h" #include "path-util.h" #include "process-util.h" #include "string-util.h" #include "tests.h" #include "tmpfile-util.h" static void test_tempfn_random_one(const char *p, const char *extra, const char *expect, int ret) { _cleanup_free_ char *s = NULL; int r; r = tempfn_random(p, extra, &s); log_info("%s+%s β†’ %s vs. %s (%i/%s vs. %i/%s)", p, strna(extra), strna(s), strna(expect), r, STRERROR(r), ret, STRERROR(ret)); assert_se(!s == !expect); if (s) { const char *suffix; assert_se(suffix = startswith(s, expect)); assert_se(in_charset(suffix, HEXDIGITS)); assert_se(strlen(suffix) == 16); } assert_se(ret == r); } TEST(tempfn_random) { _cleanup_free_ char *dir = NULL, *p = NULL, *q = NULL; test_tempfn_random_one("", NULL, NULL, -EINVAL); test_tempfn_random_one(".", NULL, NULL, -EADDRNOTAVAIL); test_tempfn_random_one("..", NULL, NULL, -EINVAL); test_tempfn_random_one("/", NULL, NULL, -EADDRNOTAVAIL); test_tempfn_random_one("foo", "hoge/aaa", NULL, -EINVAL); test_tempfn_random_one("foo", NULL, ".#foo", 0); test_tempfn_random_one("foo", "bar", ".#barfoo", 0); test_tempfn_random_one("/tmp/foo", NULL, "/tmp/.#foo", 0); test_tempfn_random_one("/tmp/foo", "bar", "/tmp/.#barfoo", 0); test_tempfn_random_one("./foo", NULL, ".#foo", 0); test_tempfn_random_one("./foo", "bar", ".#barfoo", 0); test_tempfn_random_one("../foo", NULL, "../.#foo", 0); test_tempfn_random_one("../foo", "bar", "../.#barfoo", 0); test_tempfn_random_one("foo/", NULL, ".#foo", 0); test_tempfn_random_one("foo/", "bar", ".#barfoo", 0); test_tempfn_random_one("/tmp/foo/", NULL, "/tmp/.#foo", 0); test_tempfn_random_one("/tmp/foo/", "bar", "/tmp/.#barfoo", 0); test_tempfn_random_one("./foo/", NULL, ".#foo", 0); test_tempfn_random_one("./foo/", "bar", ".#barfoo", 0); test_tempfn_random_one("../foo/", NULL, "../.#foo", 0); test_tempfn_random_one("../foo/", "bar", "../.#barfoo", 0); assert_se(dir = new(char, PATH_MAX - 20)); memset(dir, 'x', PATH_MAX - 21); dir[PATH_MAX - 21] = '\0'; for (size_t i = 0; i < PATH_MAX - 21; i += NAME_MAX + 1) dir[i] = '/'; assert_se(p = path_join(dir, "a")); assert_se(q = path_join(dir, ".#a")); test_tempfn_random_one(p, NULL, q, 0); test_tempfn_random_one(p, "b", NULL, -EINVAL); p = mfree(p); q = mfree(q); assert_se(p = new(char, NAME_MAX + 1)); memset(p, 'x', NAME_MAX); p[NAME_MAX] = '\0'; assert_se(q = new(char, NAME_MAX + 1)); memset(stpcpy(q, ".#"), 'x', NAME_MAX - STRLEN(".#") - 16); q[NAME_MAX - 16] = '\0'; test_tempfn_random_one(p, NULL, q, 0); memset(stpcpy(q, ".#hoge"), 'x', NAME_MAX - STRLEN(".#hoge") - 16); q[NAME_MAX - 16] = '\0'; test_tempfn_random_one(p, "hoge", q, 0); } static void test_tempfn_xxxxxx_one(const char *p, const char *extra, const char *expect, int ret) { _cleanup_free_ char *s = NULL; int r; r = tempfn_xxxxxx(p, extra, &s); log_info("%s+%s β†’ %s vs. %s (%i/%s vs. %i/%s)", p, strna(extra), strna(s), strna(expect), r, STRERROR(r), ret, STRERROR(ret)); assert_se(!s == !expect); if (s) { const char *suffix; assert_se(suffix = startswith(s, expect)); assert_se(streq(suffix, "XXXXXX")); } assert_se(ret == r); } TEST(tempfn_xxxxxx) { _cleanup_free_ char *dir = NULL, *p = NULL, *q = NULL; test_tempfn_xxxxxx_one("", NULL, NULL, -EINVAL); test_tempfn_xxxxxx_one(".", NULL, NULL, -EADDRNOTAVAIL); test_tempfn_xxxxxx_one("..", NULL, NULL, -EINVAL); test_tempfn_xxxxxx_one("/", NULL, NULL, -EADDRNOTAVAIL); test_tempfn_xxxxxx_one("foo", "hoge/aaa", NULL, -EINVAL); test_tempfn_xxxxxx_one("foo", NULL, ".#foo", 0); test_tempfn_xxxxxx_one("foo", "bar", ".#barfoo", 0); test_tempfn_xxxxxx_one("/tmp/foo", NULL, "/tmp/.#foo", 0); test_tempfn_xxxxxx_one("/tmp/foo", "bar", "/tmp/.#barfoo", 0); test_tempfn_xxxxxx_one("./foo", NULL, ".#foo", 0); test_tempfn_xxxxxx_one("./foo", "bar", ".#barfoo", 0); test_tempfn_xxxxxx_one("../foo", NULL, "../.#foo", 0); test_tempfn_xxxxxx_one("../foo", "bar", "../.#barfoo", 0); test_tempfn_xxxxxx_one("foo/", NULL, ".#foo", 0); test_tempfn_xxxxxx_one("foo/", "bar", ".#barfoo", 0); test_tempfn_xxxxxx_one("/tmp/foo/", NULL, "/tmp/.#foo", 0); test_tempfn_xxxxxx_one("/tmp/foo/", "bar", "/tmp/.#barfoo", 0); test_tempfn_xxxxxx_one("./foo/", NULL, ".#foo", 0); test_tempfn_xxxxxx_one("./foo/", "bar", ".#barfoo", 0); test_tempfn_xxxxxx_one("../foo/", NULL, "../.#foo", 0); test_tempfn_xxxxxx_one("../foo/", "bar", "../.#barfoo", 0); assert_se(dir = new(char, PATH_MAX - 10)); memset(dir, 'x', PATH_MAX - 11); dir[PATH_MAX - 11] = '\0'; for (size_t i = 0; i < PATH_MAX - 11; i += NAME_MAX + 1) dir[i] = '/'; assert_se(p = path_join(dir, "a")); assert_se(q = path_join(dir, ".#a")); test_tempfn_xxxxxx_one(p, NULL, q, 0); test_tempfn_xxxxxx_one(p, "b", NULL, -EINVAL); p = mfree(p); q = mfree(q); assert_se(p = new(char, NAME_MAX + 1)); memset(p, 'x', NAME_MAX); p[NAME_MAX] = '\0'; assert_se(q = new(char, NAME_MAX + 1)); memset(stpcpy(q, ".#"), 'x', NAME_MAX - STRLEN(".#") - 6); q[NAME_MAX - 6] = '\0'; test_tempfn_xxxxxx_one(p, NULL, q, 0); memset(stpcpy(q, ".#hoge"), 'x', NAME_MAX - STRLEN(".#hoge") - 6); q[NAME_MAX - 6] = '\0'; test_tempfn_xxxxxx_one(p, "hoge", q, 0); } static void test_tempfn_random_child_one(const char *p, const char *extra, const char *expect, int ret) { _cleanup_free_ char *s = NULL; int r; r = tempfn_random_child(p, extra, &s); log_info_errno(r, "%s+%s β†’ %s vs. %s (%i/%s vs. %i/%s)", p, strna(extra), strna(s), strna(expect), r, STRERROR(r), ret, STRERROR(ret)); assert_se(!s == !expect); if (s) { const char *suffix; assert_se(suffix = startswith(s, expect)); assert_se(in_charset(suffix, HEXDIGITS)); assert_se(strlen(suffix) == 16); } assert_se(ret == r); } TEST(tempfn_random_child) { _cleanup_free_ char *dir = NULL, *p = NULL, *q = NULL; test_tempfn_random_child_one("", NULL, ".#", 0); test_tempfn_random_child_one(".", NULL, ".#", 0); test_tempfn_random_child_one("..", NULL, "../.#", 0); test_tempfn_random_child_one("/", NULL, "/.#", 0); test_tempfn_random_child_one("foo", "hoge/aaa", NULL, -EINVAL); test_tempfn_random_child_one("foo", NULL, "foo/.#", 0); test_tempfn_random_child_one("foo", "bar", "foo/.#bar", 0); test_tempfn_random_child_one("/tmp/foo", NULL, "/tmp/foo/.#", 0); test_tempfn_random_child_one("/tmp/foo", "bar", "/tmp/foo/.#bar", 0); test_tempfn_random_child_one("./foo", NULL, "foo/.#", 0); test_tempfn_random_child_one("./foo", "bar", "foo/.#bar", 0); test_tempfn_random_child_one("../foo", NULL, "../foo/.#", 0); test_tempfn_random_child_one("../foo", "bar", "../foo/.#bar", 0); test_tempfn_random_child_one("foo/", NULL, "foo/.#", 0); test_tempfn_random_child_one("foo/", "bar", "foo/.#bar", 0); test_tempfn_random_child_one("/tmp/foo/", NULL, "/tmp/foo/.#", 0); test_tempfn_random_child_one("/tmp/foo/", "bar", "/tmp/foo/.#bar", 0); test_tempfn_random_child_one("./foo/", NULL, "foo/.#", 0); test_tempfn_random_child_one("./foo/", "bar", "foo/.#bar", 0); test_tempfn_random_child_one("../foo/", NULL, "../foo/.#", 0); test_tempfn_random_child_one("../foo/", "bar", "../foo/.#bar", 0); assert_se(dir = new(char, PATH_MAX - 21)); memset(dir, 'x', PATH_MAX - 22); dir[PATH_MAX - 22] = '\0'; for (size_t i = 0; i < PATH_MAX - 22; i += NAME_MAX + 1) dir[i] = '/'; assert_se(p = path_join(dir, "a")); assert_se(q = path_join(p, ".#")); test_tempfn_random_child_one(p, NULL, q, 0); test_tempfn_random_child_one(p, "b", NULL, -EINVAL); p = mfree(p); q = mfree(q); assert_se(p = new(char, NAME_MAX + 1)); memset(p, 'x', NAME_MAX); p[NAME_MAX] = '\0'; assert_se(q = path_join(p, ".#")); test_tempfn_random_child_one(p, NULL, q, 0); assert_se(strextend(&q, "hoge")); test_tempfn_random_child_one(p, "hoge", q, 0); } TEST(link_tmpfile) { _cleanup_free_ char *cmd = NULL, *cmd2 = NULL, *ans = NULL, *ans2 = NULL, *d = NULL, *tmp = NULL, *line = NULL; _cleanup_close_ int fd = -EBADF, fd2 = -EBADF; const char *p = saved_argv[1] ?: "/tmp"; char *pattern; pattern = strjoina(p, "/systemd-test-XXXXXX"); fd = open_tmpfile_unlinkable(p, O_RDWR|O_CLOEXEC); assert_se(fd >= 0); assert_se(asprintf(&cmd, "ls -l /proc/"PID_FMT"/fd/%d", getpid_cached(), fd) > 0); (void) system(cmd); assert_se(readlink_malloc(cmd + 6, &ans) >= 0); log_debug("link1: %s", ans); assert_se(endswith(ans, " (deleted)")); fd2 = mkostemp_safe(pattern); assert_se(fd2 >= 0); assert_se(unlink(pattern) == 0); assert_se(asprintf(&cmd2, "ls -l /proc/"PID_FMT"/fd/%d", getpid_cached(), fd2) > 0); (void) system(cmd2); assert_se(readlink_malloc(cmd2 + 6, &ans2) >= 0); log_debug("link2: %s", ans2); assert_se(endswith(ans2, " (deleted)")); pattern = strjoina(p, "/tmpfiles-test"); assert_se(tempfn_random(pattern, NULL, &d) >= 0); fd = safe_close(fd); fd = open_tmpfile_linkable(d, O_RDWR|O_CLOEXEC, &tmp); assert_se(fd >= 0); assert_se(write(fd, "foobar\n", 7) == 7); assert_se(touch(d) >= 0); assert_se(link_tmpfile(fd, tmp, d, /* flags= */ 0) == -EEXIST); assert_se(unlink(d) >= 0); assert_se(link_tmpfile(fd, tmp, d, /* flags= */ 0) >= 0); assert_se(read_one_line_file(d, &line) >= 0); assert_se(streq(line, "foobar")); fd = safe_close(fd); tmp = mfree(tmp); fd = open_tmpfile_linkable(d, O_RDWR|O_CLOEXEC, &tmp); assert_se(fd >= 0); assert_se(write(fd, "waumiau\n", 8) == 8); assert_se(link_tmpfile(fd, tmp, d, /* flags= */ 0) == -EEXIST); assert_se(link_tmpfile(fd, tmp, d, LINK_TMPFILE_REPLACE) >= 0); line = mfree(line); assert_se(read_one_line_file(d, &line) >= 0); assert_se(streq(line, "waumiau")); assert_se(unlink(d) >= 0); } DEFINE_TEST_MAIN(LOG_DEBUG);
11,490
36.429967
119
c
null
systemd-main/src/test/test-uid-alloc-range.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <unistd.h> #include <sys/types.h> #include "fd-util.h" #include "fileio.h" #include "format-util.h" #include "fs-util.h" #include "tests.h" #include "tmpfile-util.h" #include "uid-alloc-range.h" static void test_read_login_defs_one(const char *path) { log_info("/* %s(\"%s\") */", __func__, path ?: "<custom>"); _cleanup_(unlink_tempfilep) char name[] = "/tmp/test-user-record.XXXXXX"; _cleanup_fclose_ FILE *f = NULL; if (!path) { assert_se(fmkostemp_safe(name, "r+", &f) == 0); fprintf(f, "SYS_UID_MIN "UID_FMT"\n" "SYS_UID_MAX "UID_FMT"\n" "SYS_GID_MIN "GID_FMT"\n" "SYS_GID_MAX "GID_FMT"\n", (uid_t) (SYSTEM_ALLOC_UID_MIN + 5), (uid_t) (SYSTEM_UID_MAX + 5), (gid_t) (SYSTEM_ALLOC_GID_MIN + 5), (gid_t) (SYSTEM_GID_MAX + 5)); assert_se(fflush_and_check(f) >= 0); } UGIDAllocationRange defs; assert_se(read_login_defs(&defs, path ?: name, NULL) >= 0); log_info("system_alloc_uid_min="UID_FMT, defs.system_alloc_uid_min); log_info("system_uid_max="UID_FMT, defs.system_uid_max); log_info("system_alloc_gid_min="GID_FMT, defs.system_alloc_gid_min); log_info("system_gid_max="GID_FMT, defs.system_gid_max); if (!path) { uid_t offset = ENABLE_COMPAT_MUTABLE_UID_BOUNDARIES ? 5 : 0; assert_se(defs.system_alloc_uid_min == SYSTEM_ALLOC_UID_MIN + offset); assert_se(defs.system_uid_max == SYSTEM_UID_MAX + offset); assert_se(defs.system_alloc_gid_min == SYSTEM_ALLOC_GID_MIN + offset); assert_se(defs.system_gid_max == SYSTEM_GID_MAX + offset); } else if (streq(path, "/dev/null")) { assert_se(defs.system_alloc_uid_min == SYSTEM_ALLOC_UID_MIN); assert_se(defs.system_uid_max == SYSTEM_UID_MAX); assert_se(defs.system_alloc_gid_min == SYSTEM_ALLOC_GID_MIN); assert_se(defs.system_gid_max == SYSTEM_GID_MAX); } } TEST(read_login_defs) { test_read_login_defs_one("/dev/null"); test_read_login_defs_one("/etc/login.defs"); test_read_login_defs_one(NULL); } TEST(acquire_ugid_allocation_range) { const UGIDAllocationRange *defs; assert_se(defs = acquire_ugid_allocation_range()); log_info("system_alloc_uid_min="UID_FMT, defs->system_alloc_uid_min); log_info("system_uid_max="UID_FMT, defs->system_uid_max); log_info("system_alloc_gid_min="GID_FMT, defs->system_alloc_gid_min); log_info("system_gid_max="GID_FMT, defs->system_gid_max); } TEST(uid_is_system) { uid_t uid = 0; log_info("uid_is_system("UID_FMT") = %s", uid, yes_no(uid_is_system(uid))); uid = 999; log_info("uid_is_system("UID_FMT") = %s", uid, yes_no(uid_is_system(uid))); uid = getuid(); log_info("uid_is_system("UID_FMT") = %s", uid, yes_no(uid_is_system(uid))); } TEST(gid_is_system) { gid_t gid = 0; log_info("gid_is_system("GID_FMT") = %s", gid, yes_no(gid_is_system(gid))); gid = 999; log_info("gid_is_system("GID_FMT") = %s", gid, yes_no(gid_is_system(gid))); gid = getgid(); log_info("gid_is_system("GID_FMT") = %s", gid, yes_no(gid_is_system(gid))); } DEFINE_TEST_MAIN(LOG_DEBUG);
3,585
37.148936
86
c
null
systemd-main/src/test/test-uid-range.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stddef.h> #include "alloc-util.h" #include "errno-util.h" #include "fd-util.h" #include "fileio.h" #include "fs-util.h" #include "tests.h" #include "tmpfile-util.h" #include "uid-range.h" #include "user-util.h" #include "virt.h" TEST(uid_range) { _cleanup_(uid_range_freep) UidRange *p = NULL; uid_t search; assert_se(uid_range_covers(p, 0, 0)); assert_se(!uid_range_covers(p, 0, 1)); assert_se(!uid_range_covers(p, 100, UINT32_MAX)); assert_se(uid_range_add_str(&p, "500-999") >= 0); assert_se(p); assert_se(p->n_entries == 1); assert_se(p->entries[0].start == 500); assert_se(p->entries[0].nr == 500); assert_se(!uid_range_contains(p, 499)); assert_se(uid_range_contains(p, 500)); assert_se(uid_range_contains(p, 999)); assert_se(!uid_range_contains(p, 1000)); assert_se(!uid_range_covers(p, 100, 150)); assert_se(!uid_range_covers(p, 400, 200)); assert_se(!uid_range_covers(p, 499, 1)); assert_se(uid_range_covers(p, 500, 1)); assert_se(uid_range_covers(p, 501, 10)); assert_se(uid_range_covers(p, 999, 1)); assert_se(!uid_range_covers(p, 999, 2)); assert_se(!uid_range_covers(p, 1000, 1)); assert_se(!uid_range_covers(p, 1000, 100)); assert_se(!uid_range_covers(p, 1001, 100)); search = UID_INVALID; assert_se(uid_range_next_lower(p, &search)); assert_se(search == 999); assert_se(uid_range_next_lower(p, &search)); assert_se(search == 998); search = 501; assert_se(uid_range_next_lower(p, &search)); assert_se(search == 500); assert_se(uid_range_next_lower(p, &search) == -EBUSY); assert_se(uid_range_add_str(&p, "1000") >= 0); assert_se(p->n_entries == 1); assert_se(p->entries[0].start == 500); assert_se(p->entries[0].nr == 501); assert_se(uid_range_add_str(&p, "30-40") >= 0); assert_se(p->n_entries == 2); assert_se(p->entries[0].start == 30); assert_se(p->entries[0].nr == 11); assert_se(p->entries[1].start == 500); assert_se(p->entries[1].nr == 501); assert_se(uid_range_add_str(&p, "60-70") >= 0); assert_se(p->n_entries == 3); assert_se(p->entries[0].start == 30); assert_se(p->entries[0].nr == 11); assert_se(p->entries[1].start == 60); assert_se(p->entries[1].nr == 11); assert_se(p->entries[2].start == 500); assert_se(p->entries[2].nr == 501); assert_se(uid_range_add_str(&p, "20-2000") >= 0); assert_se(p->n_entries == 1); assert_se(p->entries[0].start == 20); assert_se(p->entries[0].nr == 1981); assert_se(uid_range_add_str(&p, "2002") >= 0); assert_se(p->n_entries == 2); assert_se(p->entries[0].start == 20); assert_se(p->entries[0].nr == 1981); assert_se(p->entries[1].start == 2002); assert_se(p->entries[1].nr == 1); assert_se(uid_range_add_str(&p, "2001") >= 0); assert_se(p->n_entries == 1); assert_se(p->entries[0].start == 20); assert_se(p->entries[0].nr == 1983); } TEST(load_userns) { _cleanup_(uid_range_freep) UidRange *p = NULL; _cleanup_(unlink_and_freep) char *fn = NULL; _cleanup_fclose_ FILE *f = NULL; int r; r = uid_range_load_userns(&p, NULL); if (r < 0 && ERRNO_IS_NOT_SUPPORTED(r)) return; assert_se(r >= 0); assert_se(uid_range_contains(p, getuid())); r = running_in_userns(); if (r == 0) { assert_se(p->n_entries == 1); assert_se(p->entries[0].start == 0); assert_se(p->entries[0].nr == UINT32_MAX); assert_se(uid_range_covers(p, 0, UINT32_MAX)); } assert_se(fopen_temporary_child(NULL, &f, &fn) >= 0); fputs("0 0 20\n" "100 0 20\n", f); assert_se(fflush_and_check(f) >= 0); p = uid_range_free(p); assert_se(uid_range_load_userns(&p, fn) >= 0); assert_se(uid_range_contains(p, 0)); assert_se(uid_range_contains(p, 19)); assert_se(!uid_range_contains(p, 20)); assert_se(!uid_range_contains(p, 99)); assert_se(uid_range_contains(p, 100)); assert_se(uid_range_contains(p, 119)); assert_se(!uid_range_contains(p, 120)); } TEST(uid_range_coalesce) { _cleanup_(uid_range_freep) UidRange *p = NULL; for (size_t i = 0; i < 10; i++) { assert_se(uid_range_add_internal(&p, i * 10, 10, /* coalesce = */ false) >= 0); assert_se(uid_range_add_internal(&p, i * 10 + 5, 10, /* coalesce = */ false) >= 0); } assert_se(uid_range_add_internal(&p, 100, 1, /* coalesce = */ true) >= 0); assert_se(p->n_entries == 1); assert_se(p->entries[0].start == 0); assert_se(p->entries[0].nr == 105); p = uid_range_free(p); for (size_t i = 0; i < 10; i++) { assert_se(uid_range_add_internal(&p, (10 - i) * 10, 10, /* coalesce = */ false) >= 0); assert_se(uid_range_add_internal(&p, (10 - i) * 10 + 5, 10, /* coalesce = */ false) >= 0); } assert_se(uid_range_add_internal(&p, 100, 1, /* coalesce = */ true) >= 0); assert_se(p->n_entries == 1); assert_se(p->entries[0].start == 10); assert_se(p->entries[0].nr == 105); p = uid_range_free(p); for (size_t i = 0; i < 10; i++) { assert_se(uid_range_add_internal(&p, i * 10, 10, /* coalesce = */ false) >= 0); assert_se(uid_range_add_internal(&p, i * 10 + 5, 10, /* coalesce = */ false) >= 0); assert_se(uid_range_add_internal(&p, (10 - i) * 10, 10, /* coalesce = */ false) >= 0); assert_se(uid_range_add_internal(&p, (10 - i) * 10 + 5, 10, /* coalesce = */ false) >= 0); } assert_se(uid_range_add_internal(&p, 100, 1, /* coalesce = */ true) >= 0); assert_se(p->n_entries == 1); assert_se(p->entries[0].start == 0); assert_se(p->entries[0].nr == 115); } DEFINE_TEST_MAIN(LOG_DEBUG);
6,329
34.965909
106
c
null
systemd-main/src/test/test-unaligned.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "memory-util.h" #include "sparse-endian.h" #include "tests.h" #include "unaligned.h" static uint8_t data[] = { 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f, }; TEST(be) { uint8_t scratch[16]; assert_se(unaligned_read_be16(&data[0]) == 0x0001); assert_se(unaligned_read_be16(&data[1]) == 0x0102); assert_se(unaligned_read_be32(&data[0]) == 0x00010203); assert_se(unaligned_read_be32(&data[1]) == 0x01020304); assert_se(unaligned_read_be32(&data[2]) == 0x02030405); assert_se(unaligned_read_be32(&data[3]) == 0x03040506); assert_se(unaligned_read_be64(&data[0]) == 0x0001020304050607); assert_se(unaligned_read_be64(&data[1]) == 0x0102030405060708); assert_se(unaligned_read_be64(&data[2]) == 0x0203040506070809); assert_se(unaligned_read_be64(&data[3]) == 0x030405060708090a); assert_se(unaligned_read_be64(&data[4]) == 0x0405060708090a0b); assert_se(unaligned_read_be64(&data[5]) == 0x05060708090a0b0c); assert_se(unaligned_read_be64(&data[6]) == 0x060708090a0b0c0d); assert_se(unaligned_read_be64(&data[7]) == 0x0708090a0b0c0d0e); zero(scratch); unaligned_write_be16(&scratch[0], 0x0001); assert_se(memcmp(&scratch[0], &data[0], sizeof(uint16_t)) == 0); zero(scratch); unaligned_write_be16(&scratch[1], 0x0102); assert_se(memcmp(&scratch[1], &data[1], sizeof(uint16_t)) == 0); zero(scratch); unaligned_write_be32(&scratch[0], 0x00010203); assert_se(memcmp(&scratch[0], &data[0], sizeof(uint32_t)) == 0); zero(scratch); unaligned_write_be32(&scratch[1], 0x01020304); assert_se(memcmp(&scratch[1], &data[1], sizeof(uint32_t)) == 0); zero(scratch); unaligned_write_be32(&scratch[2], 0x02030405); assert_se(memcmp(&scratch[2], &data[2], sizeof(uint32_t)) == 0); zero(scratch); unaligned_write_be32(&scratch[3], 0x03040506); assert_se(memcmp(&scratch[3], &data[3], sizeof(uint32_t)) == 0); zero(scratch); unaligned_write_be64(&scratch[0], 0x0001020304050607); assert_se(memcmp(&scratch[0], &data[0], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_be64(&scratch[1], 0x0102030405060708); assert_se(memcmp(&scratch[1], &data[1], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_be64(&scratch[2], 0x0203040506070809); assert_se(memcmp(&scratch[2], &data[2], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_be64(&scratch[3], 0x030405060708090a); assert_se(memcmp(&scratch[3], &data[3], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_be64(&scratch[4], 0x0405060708090a0b); assert_se(memcmp(&scratch[4], &data[4], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_be64(&scratch[5], 0x05060708090a0b0c); assert_se(memcmp(&scratch[5], &data[5], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_be64(&scratch[6], 0x060708090a0b0c0d); assert_se(memcmp(&scratch[6], &data[6], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_be64(&scratch[7], 0x0708090a0b0c0d0e); assert_se(memcmp(&scratch[7], &data[7], sizeof(uint64_t)) == 0); } TEST(le) { uint8_t scratch[16]; assert_se(unaligned_read_le16(&data[0]) == 0x0100); assert_se(unaligned_read_le16(&data[1]) == 0x0201); assert_se(unaligned_read_le32(&data[0]) == 0x03020100); assert_se(unaligned_read_le32(&data[1]) == 0x04030201); assert_se(unaligned_read_le32(&data[2]) == 0x05040302); assert_se(unaligned_read_le32(&data[3]) == 0x06050403); assert_se(unaligned_read_le64(&data[0]) == 0x0706050403020100); assert_se(unaligned_read_le64(&data[1]) == 0x0807060504030201); assert_se(unaligned_read_le64(&data[2]) == 0x0908070605040302); assert_se(unaligned_read_le64(&data[3]) == 0x0a09080706050403); assert_se(unaligned_read_le64(&data[4]) == 0x0b0a090807060504); assert_se(unaligned_read_le64(&data[5]) == 0x0c0b0a0908070605); assert_se(unaligned_read_le64(&data[6]) == 0x0d0c0b0a09080706); assert_se(unaligned_read_le64(&data[7]) == 0x0e0d0c0b0a090807); zero(scratch); unaligned_write_le16(&scratch[0], 0x0100); assert_se(memcmp(&scratch[0], &data[0], sizeof(uint16_t)) == 0); zero(scratch); unaligned_write_le16(&scratch[1], 0x0201); assert_se(memcmp(&scratch[1], &data[1], sizeof(uint16_t)) == 0); zero(scratch); unaligned_write_le32(&scratch[0], 0x03020100); assert_se(memcmp(&scratch[0], &data[0], sizeof(uint32_t)) == 0); zero(scratch); unaligned_write_le32(&scratch[1], 0x04030201); assert_se(memcmp(&scratch[1], &data[1], sizeof(uint32_t)) == 0); zero(scratch); unaligned_write_le32(&scratch[2], 0x05040302); assert_se(memcmp(&scratch[2], &data[2], sizeof(uint32_t)) == 0); zero(scratch); unaligned_write_le32(&scratch[3], 0x06050403); assert_se(memcmp(&scratch[3], &data[3], sizeof(uint32_t)) == 0); zero(scratch); unaligned_write_le64(&scratch[0], 0x0706050403020100); assert_se(memcmp(&scratch[0], &data[0], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_le64(&scratch[1], 0x0807060504030201); assert_se(memcmp(&scratch[1], &data[1], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_le64(&scratch[2], 0x0908070605040302); assert_se(memcmp(&scratch[2], &data[2], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_le64(&scratch[3], 0x0a09080706050403); assert_se(memcmp(&scratch[3], &data[3], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_le64(&scratch[4], 0x0B0A090807060504); assert_se(memcmp(&scratch[4], &data[4], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_le64(&scratch[5], 0x0c0b0a0908070605); assert_se(memcmp(&scratch[5], &data[5], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_le64(&scratch[6], 0x0d0c0b0a09080706); assert_se(memcmp(&scratch[6], &data[6], sizeof(uint64_t)) == 0); zero(scratch); unaligned_write_le64(&scratch[7], 0x0e0d0c0b0a090807); assert_se(memcmp(&scratch[7], &data[7], sizeof(uint64_t)) == 0); } TEST(ne) { uint16_t x = 4711; uint32_t y = 123456; uint64_t z = 9876543210; /* Note that we don't bother actually testing alignment issues in this function, after all the _ne() functions * are just aliases for the _le() or _be() implementations, which we test extensively above. Hence, in this * function, just ensure that they map to the right version on the local architecture. */ assert_se(unaligned_read_ne16(&x) == 4711); assert_se(unaligned_read_ne32(&y) == 123456); assert_se(unaligned_read_ne64(&z) == 9876543210); unaligned_write_ne16(&x, 1); unaligned_write_ne32(&y, 2); unaligned_write_ne64(&z, 3); assert_se(x == 1); assert_se(y == 2); assert_se(z == 3); } DEFINE_TEST_MAIN(LOG_INFO);
7,454
43.112426
118
c
null
systemd-main/src/test/test-unit-file.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "initrd-util.h" #include "path-lookup.h" #include "set.h" #include "special.h" #include "strv.h" #include "tests.h" #include "unit-file.h" TEST(unit_validate_alias_symlink_and_warn) { assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/a.service", "/other/b.service") == 0); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/a.service", "/other/b.socket") == -EXDEV); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/a.service", "/other/b.foobar") == -EXDEV); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/[email protected]", "/other/[email protected]") == 0); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/[email protected]", "/other/[email protected]") == -EXDEV); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/[email protected]", "/other/[email protected]") == -EXDEV); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/[email protected]", "/other/[email protected]") == -EXDEV); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/[email protected]", "/other/[email protected]") == -EXDEV); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/[email protected]", "/other/[email protected]") == 0); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/[email protected]", "/other/[email protected]") == 0); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/[email protected]", "/other/b.service") == -EXDEV); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/a.service", "/other/[email protected]") == -EXDEV); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/[email protected]", "/other/b.slice") == -EINVAL); assert_se(unit_validate_alias_symlink_or_warn(LOG_INFO, "/path/a.slice", "/other/b.slice") == -EINVAL); } TEST(unit_file_build_name_map) { _cleanup_(lookup_paths_free) LookupPaths lp = {}; _cleanup_hashmap_free_ Hashmap *unit_ids = NULL; _cleanup_hashmap_free_ Hashmap *unit_names = NULL; const char *k, *dst; char **v, **ids; usec_t mtime = 0; int r; ids = strv_skip(saved_argv, 1); assert_se(lookup_paths_init(&lp, RUNTIME_SCOPE_SYSTEM, 0, NULL) >= 0); assert_se(unit_file_build_name_map(&lp, &mtime, &unit_ids, &unit_names, NULL) == 1); HASHMAP_FOREACH_KEY(dst, k, unit_ids) log_info("ids: %s β†’ %s", k, dst); HASHMAP_FOREACH_KEY(v, k, unit_names) { _cleanup_free_ char *j = strv_join(v, ", "); log_info("aliases: %s ← %s", k, j); } char buf[FORMAT_TIMESTAMP_MAX]; log_debug("Last modification time: %s", format_timestamp(buf, sizeof buf, mtime)); r = unit_file_build_name_map(&lp, &mtime, &unit_ids, &unit_names, NULL); assert_se(IN_SET(r, 0, 1)); if (r == 0) log_debug("Cache rebuild skipped based on mtime."); STRV_FOREACH(id, ids) { const char *fragment, *name; _cleanup_set_free_free_ Set *names = NULL; log_info("*** %s ***", *id); r = unit_file_find_fragment(unit_ids, unit_names, *id, &fragment, &names); assert_se(r == 0); log_info("fragment: %s", fragment); log_info("names:"); SET_FOREACH(name, names) log_info(" %s", name); } /* Make sure everything still works if we don't collect names. */ STRV_FOREACH(id, ids) { const char *fragment; log_info("*** %s ***", *id); r = unit_file_find_fragment(unit_ids, unit_names, *id, &fragment, NULL); assert_se(r == 0); log_info("fragment: %s", fragment); } } TEST(runlevel_to_target) { in_initrd_force(false); assert_se(streq_ptr(runlevel_to_target(NULL), NULL)); assert_se(streq_ptr(runlevel_to_target("unknown-runlevel"), NULL)); assert_se(streq_ptr(runlevel_to_target("rd.unknown-runlevel"), NULL)); assert_se(streq_ptr(runlevel_to_target("3"), SPECIAL_MULTI_USER_TARGET)); assert_se(streq_ptr(runlevel_to_target("rd.rescue"), NULL)); in_initrd_force(true); assert_se(streq_ptr(runlevel_to_target(NULL), NULL)); assert_se(streq_ptr(runlevel_to_target("unknown-runlevel"), NULL)); assert_se(streq_ptr(runlevel_to_target("rd.unknown-runlevel"), NULL)); assert_se(streq_ptr(runlevel_to_target("3"), NULL)); assert_se(streq_ptr(runlevel_to_target("rd.rescue"), SPECIAL_RESCUE_TARGET)); } static int intro(void) { log_show_color(true); return EXIT_SUCCESS; } DEFINE_TEST_MAIN_WITH_INTRO(LOG_DEBUG, intro);
5,202
45.873874
122
c
null
systemd-main/src/test/test-user-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "format-util.h" #include "libcrypt-util.h" #include "log.h" #include "macro.h" #include "memory-util.h" #include "path-util.h" #include "string-util.h" #include "tests.h" #include "user-util.h" static void test_uid_to_name_one(uid_t uid, const char *name) { _cleanup_free_ char *t = NULL; log_info("/* %s("UID_FMT", \"%s\") */", __func__, uid, name); assert_se(t = uid_to_name(uid)); if (!synthesize_nobody() && streq(name, NOBODY_USER_NAME)) { log_info("(skipping detailed tests because nobody is not synthesized)"); return; } assert_se(streq_ptr(t, name)); } TEST(uid_to_name) { test_uid_to_name_one(0, "root"); test_uid_to_name_one(UID_NOBODY, NOBODY_USER_NAME); test_uid_to_name_one(0xFFFF, "65535"); test_uid_to_name_one(0xFFFFFFFF, "4294967295"); } static void test_gid_to_name_one(gid_t gid, const char *name) { _cleanup_free_ char *t = NULL; log_info("/* %s("GID_FMT", \"%s\") */", __func__, gid, name); assert_se(t = gid_to_name(gid)); if (!synthesize_nobody() && streq(name, NOBODY_GROUP_NAME)) { log_info("(skipping detailed tests because nobody is not synthesized)"); return; } assert_se(streq_ptr(t, name)); } TEST(gid_to_name) { test_gid_to_name_one(0, "root"); test_gid_to_name_one(GID_NOBODY, NOBODY_GROUP_NAME); test_gid_to_name_one(TTY_GID, "tty"); test_gid_to_name_one(0xFFFF, "65535"); test_gid_to_name_one(0xFFFFFFFF, "4294967295"); } TEST(parse_uid) { int r; uid_t uid; r = parse_uid("0", &uid); assert_se(r == 0); assert_se(uid == 0); r = parse_uid("1", &uid); assert_se(r == 0); assert_se(uid == 1); r = parse_uid("01", &uid); assert_se(r == -EINVAL); assert_se(uid == 1); r = parse_uid("001", &uid); assert_se(r == -EINVAL); assert_se(uid == 1); r = parse_uid("100", &uid); assert_se(r == 0); assert_se(uid == 100); r = parse_uid("65535", &uid); assert_se(r == -ENXIO); assert_se(uid == 100); r = parse_uid("0x1234", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("0o1234", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("0b1234", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("+1234", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("-1234", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid(" 1234", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("01234", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("001234", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("0001234", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("-0", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("+0", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("00", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("000", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); r = parse_uid("asdsdas", &uid); assert_se(r == -EINVAL); assert_se(uid == 100); } TEST(uid_ptr) { assert_se(UID_TO_PTR(0) != NULL); assert_se(UID_TO_PTR(1000) != NULL); assert_se(PTR_TO_UID(UID_TO_PTR(0)) == 0); assert_se(PTR_TO_UID(UID_TO_PTR(1000)) == 1000); } TEST(valid_user_group_name_relaxed) { assert_se(!valid_user_group_name(NULL, VALID_USER_RELAX)); assert_se(!valid_user_group_name("", VALID_USER_RELAX)); assert_se(!valid_user_group_name("1", VALID_USER_RELAX)); assert_se(!valid_user_group_name("65535", VALID_USER_RELAX)); assert_se(!valid_user_group_name("-1", VALID_USER_RELAX)); assert_se(!valid_user_group_name("foo\nbar", VALID_USER_RELAX)); assert_se(!valid_user_group_name("0123456789012345678901234567890123456789", VALID_USER_RELAX)); assert_se(!valid_user_group_name("aaa:bbb", VALID_USER_RELAX|VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name(".aaa:bbb", VALID_USER_RELAX|VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name(".", VALID_USER_RELAX)); assert_se(!valid_user_group_name("..", VALID_USER_RELAX)); assert_se(valid_user_group_name("root", VALID_USER_RELAX)); assert_se(valid_user_group_name("lennart", VALID_USER_RELAX)); assert_se(valid_user_group_name("LENNART", VALID_USER_RELAX)); assert_se(valid_user_group_name("_kkk", VALID_USER_RELAX)); assert_se(valid_user_group_name("kkk-", VALID_USER_RELAX)); assert_se(valid_user_group_name("kk-k", VALID_USER_RELAX)); assert_se(valid_user_group_name("eff.eff", VALID_USER_RELAX)); assert_se(valid_user_group_name("eff.", VALID_USER_RELAX)); assert_se(valid_user_group_name("-kkk", VALID_USER_RELAX)); assert_se(valid_user_group_name("rΓΆΓΆt", VALID_USER_RELAX)); assert_se(valid_user_group_name(".eff", VALID_USER_RELAX)); assert_se(valid_user_group_name(".1", VALID_USER_RELAX)); assert_se(valid_user_group_name(".65535", VALID_USER_RELAX)); assert_se(valid_user_group_name(".-1", VALID_USER_RELAX)); assert_se(valid_user_group_name(".-kkk", VALID_USER_RELAX)); assert_se(valid_user_group_name(".rΓΆΓΆt", VALID_USER_RELAX)); assert_se(valid_user_group_name("...", VALID_USER_RELAX)); assert_se(valid_user_group_name("some5", VALID_USER_RELAX)); assert_se(valid_user_group_name("5some", VALID_USER_RELAX)); assert_se(valid_user_group_name("INNER5NUMBER", VALID_USER_RELAX)); assert_se(valid_user_group_name("[email protected]", VALID_USER_RELAX)); assert_se(valid_user_group_name("Dāvis", VALID_USER_RELAX)); } TEST(valid_user_group_name) { assert_se(!valid_user_group_name(NULL, 0)); assert_se(!valid_user_group_name("", 0)); assert_se(!valid_user_group_name("1", 0)); assert_se(!valid_user_group_name("65535", 0)); assert_se(!valid_user_group_name("-1", 0)); assert_se(!valid_user_group_name("-kkk", 0)); assert_se(!valid_user_group_name("rΓΆΓΆt", 0)); assert_se(!valid_user_group_name(".", 0)); assert_se(!valid_user_group_name(".eff", 0)); assert_se(!valid_user_group_name("foo\nbar", 0)); assert_se(!valid_user_group_name("0123456789012345678901234567890123456789", 0)); assert_se(!valid_user_group_name("aaa:bbb", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name(".", 0)); assert_se(!valid_user_group_name("..", 0)); assert_se(!valid_user_group_name("...", 0)); assert_se(!valid_user_group_name(".1", 0)); assert_se(!valid_user_group_name(".65535", 0)); assert_se(!valid_user_group_name(".-1", 0)); assert_se(!valid_user_group_name(".-kkk", 0)); assert_se(!valid_user_group_name(".rΓΆΓΆt", 0)); assert_se(!valid_user_group_name(".aaa:bbb", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("root", 0)); assert_se(valid_user_group_name("lennart", 0)); assert_se(valid_user_group_name("LENNART", 0)); assert_se(valid_user_group_name("_kkk", 0)); assert_se(valid_user_group_name("kkk-", 0)); assert_se(valid_user_group_name("kk-k", 0)); assert_se(!valid_user_group_name("eff.eff", 0)); assert_se(!valid_user_group_name("eff.", 0)); assert_se(valid_user_group_name("some5", 0)); assert_se(!valid_user_group_name("5some", 0)); assert_se(valid_user_group_name("INNER5NUMBER", 0)); assert_se(!valid_user_group_name("[email protected]", 0)); assert_se(!valid_user_group_name("Dāvis", 0)); } TEST(valid_user_group_name_or_numeric_relaxed) { assert_se(!valid_user_group_name(NULL, VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(!valid_user_group_name("", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("0", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("1", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("65534", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(!valid_user_group_name("65535", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("65536", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(!valid_user_group_name("-1", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(!valid_user_group_name("foo\nbar", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(!valid_user_group_name("0123456789012345678901234567890123456789", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(!valid_user_group_name("aaa:bbb", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(!valid_user_group_name(".", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(!valid_user_group_name("..", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("root", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("lennart", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("LENNART", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("_kkk", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("kkk-", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("kk-k", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("-kkk", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("rΓΆΓΆt", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name(".eff", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("eff.eff", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("eff.", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("...", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("some5", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("5some", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("INNER5NUMBER", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("[email protected]", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); assert_se(valid_user_group_name("Dāvis", VALID_USER_ALLOW_NUMERIC|VALID_USER_RELAX)); } TEST(valid_user_group_name_or_numeric) { assert_se(!valid_user_group_name(NULL, VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("0", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("1", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("65534", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("65535", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("65536", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("-1", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("-kkk", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("rΓΆΓΆt", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name(".", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("..", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("...", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name(".eff", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("eff.eff", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("eff.", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("foo\nbar", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("0123456789012345678901234567890123456789", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("aaa:bbb", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("root", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("lennart", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("LENNART", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("_kkk", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("kkk-", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("kk-k", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("some5", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("5some", VALID_USER_ALLOW_NUMERIC)); assert_se(valid_user_group_name("INNER5NUMBER", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("[email protected]", VALID_USER_ALLOW_NUMERIC)); assert_se(!valid_user_group_name("Dāvis", VALID_USER_ALLOW_NUMERIC)); } TEST(valid_gecos) { assert_se(!valid_gecos(NULL)); assert_se(valid_gecos("")); assert_se(valid_gecos("test")); assert_se(valid_gecos("ÜmlÀüt")); assert_se(!valid_gecos("In\nvalid")); assert_se(!valid_gecos("In:valid")); } TEST(valid_home) { assert_se(!valid_home(NULL)); assert_se(!valid_home("")); assert_se(!valid_home(".")); assert_se(!valid_home("/home/..")); assert_se(!valid_home("/home/../")); assert_se(!valid_home("/home\n/foo")); assert_se(!valid_home("./piep")); assert_se(!valid_home("piep")); assert_se(!valid_home("/home/user:lennart")); assert_se(valid_home("/")); assert_se(valid_home("/home")); assert_se(valid_home("/home/foo")); } static void test_get_user_creds_one(const char *id, const char *name, uid_t uid, gid_t gid, const char *home, const char *shell) { const char *rhome = NULL; const char *rshell = NULL; uid_t ruid = UID_INVALID; gid_t rgid = GID_INVALID; int r; log_info("/* %s(\"%s\", \"%s\", "UID_FMT", "GID_FMT", \"%s\", \"%s\") */", __func__, id, name, uid, gid, home, shell); r = get_user_creds(&id, &ruid, &rgid, &rhome, &rshell, 0); log_info_errno(r, "got \"%s\", "UID_FMT", "GID_FMT", \"%s\", \"%s\": %m", id, ruid, rgid, strnull(rhome), strnull(rshell)); if (!synthesize_nobody() && streq(name, NOBODY_USER_NAME)) { log_info("(skipping detailed tests because nobody is not synthesized)"); return; } assert_se(r == 0); assert_se(streq_ptr(id, name)); assert_se(ruid == uid); assert_se(rgid == gid); assert_se(path_equal(rhome, home)); assert_se(path_equal(rshell, shell)); } TEST(get_user_creds) { test_get_user_creds_one("root", "root", 0, 0, "/root", DEFAULT_USER_SHELL); test_get_user_creds_one("0", "root", 0, 0, "/root", DEFAULT_USER_SHELL); test_get_user_creds_one(NOBODY_USER_NAME, NOBODY_USER_NAME, UID_NOBODY, GID_NOBODY, "/", NOLOGIN); test_get_user_creds_one("65534", NOBODY_USER_NAME, UID_NOBODY, GID_NOBODY, "/", NOLOGIN); } static void test_get_group_creds_one(const char *id, const char *name, gid_t gid) { gid_t rgid = GID_INVALID; int r; log_info("/* %s(\"%s\", \"%s\", "GID_FMT") */", __func__, id, name, gid); r = get_group_creds(&id, &rgid, 0); log_info_errno(r, "got \"%s\", "GID_FMT": %m", id, rgid); if (!synthesize_nobody() && streq(name, NOBODY_GROUP_NAME)) { log_info("(skipping detailed tests because nobody is not synthesized)"); return; } assert_se(r == 0); assert_se(streq_ptr(id, name)); assert_se(rgid == gid); } TEST(get_group_creds) { test_get_group_creds_one("root", "root", 0); test_get_group_creds_one("0", "root", 0); test_get_group_creds_one(NOBODY_GROUP_NAME, NOBODY_GROUP_NAME, GID_NOBODY); test_get_group_creds_one("65534", NOBODY_GROUP_NAME, GID_NOBODY); } TEST(make_salt) { _cleanup_free_ char *s, *t; assert_se(make_salt(&s) == 0); log_info("got %s", s); assert_se(make_salt(&t) == 0); log_info("got %s", t); assert_se(!streq(s, t)); } TEST(in_gid) { assert_se(in_gid(getgid()) >= 0); assert_se(in_gid(getegid()) >= 0); assert_se(in_gid(GID_INVALID) < 0); assert_se(in_gid(TTY_GID) == 0); /* The TTY gid is for owning ttys, it would be really really weird if we were in it. */ } TEST(gid_lists_ops) { static const gid_t l1[] = { 5, 10, 15, 20, 25}; static const gid_t l2[] = { 1, 2, 3, 15, 20, 25}; static const gid_t l3[] = { 5, 10, 15, 20, 25, 26, 27}; static const gid_t l4[] = { 25, 26, 20, 15, 5, 27, 10}; static const gid_t result1[] = {1, 2, 3, 5, 10, 15, 20, 25, 26, 27}; static const gid_t result2[] = {5, 10, 15, 20, 25, 26, 27}; _cleanup_free_ gid_t *gids = NULL; _cleanup_free_ gid_t *res1 = NULL; _cleanup_free_ gid_t *res2 = NULL; _cleanup_free_ gid_t *res3 = NULL; _cleanup_free_ gid_t *res4 = NULL; int nresult; nresult = merge_gid_lists(l2, ELEMENTSOF(l2), l3, ELEMENTSOF(l3), &res1); assert_se(nresult >= 0); assert_se(memcmp_nn(res1, nresult, result1, ELEMENTSOF(result1)) == 0); nresult = merge_gid_lists(NULL, 0, l2, ELEMENTSOF(l2), &res2); assert_se(nresult >= 0); assert_se(memcmp_nn(res2, nresult, l2, ELEMENTSOF(l2)) == 0); nresult = merge_gid_lists(l1, ELEMENTSOF(l1), l1, ELEMENTSOF(l1), &res3); assert_se(nresult >= 0); assert_se(memcmp_nn(l1, ELEMENTSOF(l1), res3, nresult) == 0); nresult = merge_gid_lists(l1, ELEMENTSOF(l1), l4, ELEMENTSOF(l4), &res4); assert_se(nresult >= 0); assert_se(memcmp_nn(result2, ELEMENTSOF(result2), res4, nresult) == 0); nresult = getgroups_alloc(&gids); assert_se(nresult >= 0 || nresult == -EINVAL || nresult == -ENOMEM); assert_se(gids); } TEST(parse_uid_range) { uid_t a = 4711, b = 4711; assert_se(parse_uid_range("", &a, &b) == -EINVAL && a == 4711 && b == 4711); assert_se(parse_uid_range(" ", &a, &b) == -EINVAL && a == 4711 && b == 4711); assert_se(parse_uid_range("x", &a, &b) == -EINVAL && a == 4711 && b == 4711); assert_se(parse_uid_range("0", &a, &b) >= 0 && a == 0 && b == 0); assert_se(parse_uid_range("1", &a, &b) >= 0 && a == 1 && b == 1); assert_se(parse_uid_range("2-2", &a, &b) >= 0 && a == 2 && b == 2); assert_se(parse_uid_range("3-3", &a, &b) >= 0 && a == 3 && b == 3); assert_se(parse_uid_range("4-5", &a, &b) >= 0 && a == 4 && b == 5); assert_se(parse_uid_range("7-6", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("-1", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("01", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("001", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("+1", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("1--1", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range(" 1", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range(" 1-2", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("1 -2", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("1- 2", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("1-2 ", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("01-2", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("1-02", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("001-2", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range("1-002", &a, &b) == -EINVAL && a == 4 && b == 5); assert_se(parse_uid_range(" 01", &a, &b) == -EINVAL && a == 4 && b == 5); } static void test_mangle_gecos_one(const char *input, const char *expected) { _cleanup_free_ char *p = NULL; assert_se(p = mangle_gecos(input)); assert_se(streq(p, expected)); assert_se(valid_gecos(p)); } TEST(mangle_gecos) { test_mangle_gecos_one("", ""); test_mangle_gecos_one("root", "root"); test_mangle_gecos_one("wuff\nwuff", "wuff wuff"); test_mangle_gecos_one("wuff:wuff", "wuff wuff"); test_mangle_gecos_one("wuff\r\n:wuff", "wuff wuff"); test_mangle_gecos_one("\n--wΓΌff-wΓ€ff-wΓΆff::", " --wΓΌff-wΓ€ff-wΓΆff "); test_mangle_gecos_one("\xc3\x28", " ("); test_mangle_gecos_one("\xe2\x28\xa1", " ( "); } DEFINE_TEST_MAIN(LOG_INFO);
21,686
43.531828
130
c
null
systemd-main/src/test/test-utmp.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "format-util.h" #include "socket-util.h" #include "stdio-util.h" #include "string-util.h" #include "utmp-wtmp.h" #include "tests.h" #ifndef UT_LINESIZE # define UT_LINESIZE 32 #endif #ifndef UT_NAMESIZE # define UT_NAMESIZE 32 #endif #ifndef UT_HOSTSIZE # define UT_HOSTSIZE 256 #endif TEST(dump_run_utmp) { _unused_ _cleanup_(utxent_cleanup) bool utmpx = false; utmpx = utxent_start(); for (struct utmpx *u; (u = getutxent()); ) { char _type_buf[DECIMAL_STR_MAX(short)]; const char *type = u->ut_type == EMPTY ? "EMPTY" : u->ut_type == RUN_LVL ? "RUN_LVL" : u->ut_type == BOOT_TIME ? "BOOT_TIME" : u->ut_type == NEW_TIME ? "NEW_TIME" : u->ut_type == OLD_TIME ? "OLD_TIME" : u->ut_type == INIT_PROCESS ? "INIT_PROCESS" : u->ut_type == LOGIN_PROCESS ? "LOGIN_PROCESS" : u->ut_type == USER_PROCESS ? "USER_PROCESS" : u->ut_type == DEAD_PROCESS ? "DEAD_PROCESS" : u->ut_type == ACCOUNTING ? "ACCOUNTING" : _type_buf; if (type == _type_buf) xsprintf(_type_buf, "%hd", u->ut_type); union in_addr_union addr = {}; memcpy(&addr, u->ut_addr_v6, MIN(sizeof(addr), sizeof(u->ut_addr_v6))); bool is_ipv4 = memeqzero((const uint8_t*) &addr + 4, sizeof(addr) - 4); log_info("%14s %10"PID_PRI" line=%-7.*s id=%-4.4s name=%-8.*s session=%lu host=%.*s addr=%s", type, u->ut_pid, UT_LINESIZE, u->ut_line, u->ut_id, UT_NAMESIZE, u->ut_user, (long unsigned) u->ut_session, UT_HOSTSIZE, u->ut_host, IN_ADDR_TO_STRING(is_ipv4 ? AF_INET : AF_INET6, &addr)); } } DEFINE_TEST_MAIN(LOG_DEBUG);
2,218
36.610169
109
c
null
systemd-main/src/test/test-verbs.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include "macro.h" #include "strv.h" #include "tests.h" #include "verbs.h" static int noop_dispatcher(int argc, char *argv[], void *userdata) { return 0; } #define test_dispatch_one(argv, verbs, expected) \ optind = 0; \ assert_se(dispatch_verb(strv_length(argv), argv, verbs, NULL) == expected); TEST(verbs) { static const Verb verbs[] = { { "help", VERB_ANY, VERB_ANY, 0, noop_dispatcher }, { "list-images", VERB_ANY, 1, 0, noop_dispatcher }, { "list", VERB_ANY, 2, VERB_DEFAULT, noop_dispatcher }, { "status", 2, VERB_ANY, 0, noop_dispatcher }, { "show", VERB_ANY, VERB_ANY, 0, noop_dispatcher }, { "terminate", 2, VERB_ANY, 0, noop_dispatcher }, { "login", 2, 2, 0, noop_dispatcher }, { "copy-to", 3, 4, 0, noop_dispatcher }, {} }; /* not found */ test_dispatch_one(STRV_MAKE("command-not-found"), verbs, -EINVAL); /* found */ test_dispatch_one(STRV_MAKE("show"), verbs, 0); /* found, too few args */ test_dispatch_one(STRV_MAKE("copy-to", "foo"), verbs, -EINVAL); /* found, meets min args */ test_dispatch_one(STRV_MAKE("status", "foo", "bar"), verbs, 0); /* found, too many args */ test_dispatch_one(STRV_MAKE("copy-to", "foo", "bar", "baz", "quux", "qaax"), verbs, -EINVAL); /* no verb, but a default is set */ test_dispatch_one(STRV_MAKE_EMPTY, verbs, 0); } TEST(verbs_no_default) { static const Verb verbs[] = { { "help", VERB_ANY, VERB_ANY, 0, noop_dispatcher }, {}, }; test_dispatch_one(STRV_MAKE(NULL), verbs, -EINVAL); } DEFINE_TEST_MAIN(LOG_INFO);
2,052
33.216667
101
c
null
systemd-main/src/test/test-watch-pid.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "log.h" #include "manager.h" #include "rm-rf.h" #include "service.h" #include "tests.h" int main(int argc, char *argv[]) { _cleanup_(rm_rf_physical_and_freep) char *runtime_dir = NULL; _cleanup_(manager_freep) Manager *m = NULL; Unit *a, *b, *c, *u; int r; test_setup_logging(LOG_DEBUG); if (getuid() != 0) return log_tests_skipped("not root"); r = enter_cgroup_subroot(NULL); if (r == -ENOMEDIUM) return log_tests_skipped("cgroupfs not available"); _cleanup_free_ char *unit_dir = NULL; assert_se(get_testdata_dir("units/", &unit_dir) >= 0); assert_se(set_unit_path(unit_dir) >= 0); assert_se(runtime_dir = setup_fake_runtime_dir()); assert_se(manager_new(RUNTIME_SCOPE_USER, MANAGER_TEST_RUN_BASIC, &m) >= 0); assert_se(manager_startup(m, NULL, NULL, NULL) >= 0); assert_se(a = unit_new(m, sizeof(Service))); assert_se(unit_add_name(a, "a.service") >= 0); assert_se(set_isempty(a->pids)); assert_se(b = unit_new(m, sizeof(Service))); assert_se(unit_add_name(b, "b.service") >= 0); assert_se(set_isempty(b->pids)); assert_se(c = unit_new(m, sizeof(Service))); assert_se(unit_add_name(c, "c.service") >= 0); assert_se(set_isempty(c->pids)); assert_se(hashmap_isempty(m->watch_pids)); assert_se(manager_get_unit_by_pid(m, 4711) == NULL); assert_se(unit_watch_pid(a, 4711, false) >= 0); assert_se(manager_get_unit_by_pid(m, 4711) == a); assert_se(unit_watch_pid(a, 4711, false) >= 0); assert_se(manager_get_unit_by_pid(m, 4711) == a); assert_se(unit_watch_pid(b, 4711, false) >= 0); u = manager_get_unit_by_pid(m, 4711); assert_se(u == a || u == b); assert_se(unit_watch_pid(b, 4711, false) >= 0); u = manager_get_unit_by_pid(m, 4711); assert_se(u == a || u == b); assert_se(unit_watch_pid(c, 4711, false) >= 0); u = manager_get_unit_by_pid(m, 4711); assert_se(u == a || u == b || u == c); assert_se(unit_watch_pid(c, 4711, false) >= 0); u = manager_get_unit_by_pid(m, 4711); assert_se(u == a || u == b || u == c); unit_unwatch_pid(b, 4711); u = manager_get_unit_by_pid(m, 4711); assert_se(u == a || u == c); unit_unwatch_pid(b, 4711); u = manager_get_unit_by_pid(m, 4711); assert_se(u == a || u == c); unit_unwatch_pid(a, 4711); assert_se(manager_get_unit_by_pid(m, 4711) == c); unit_unwatch_pid(a, 4711); assert_se(manager_get_unit_by_pid(m, 4711) == c); unit_unwatch_pid(c, 4711); assert_se(manager_get_unit_by_pid(m, 4711) == NULL); unit_unwatch_pid(c, 4711); assert_se(manager_get_unit_by_pid(m, 4711) == NULL); return 0; }
2,989
31.857143
84
c
null
systemd-main/src/test/test-watchdog.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <string.h> #include <unistd.h> #include "log.h" #include "tests.h" #include "watchdog.h" int main(int argc, char *argv[]) { usec_t t; unsigned i, count; int r; bool slow; test_setup_logging(LOG_DEBUG); slow = slow_tests_enabled(); t = slow ? 10 * USEC_PER_SEC : 2 * USEC_PER_SEC; count = slow ? 5 : 3; r = watchdog_setup(t); if (r < 0) log_warning_errno(r, "Failed to open watchdog: %m"); for (i = 0; i < count; i++) { t = watchdog_runtime_wait(); log_info("Sleeping " USEC_FMT " microseconds...", t); usleep_safe(t); log_info("Pinging..."); r = watchdog_ping(); if (r < 0) log_warning_errno(r, "Failed to ping watchdog: %m"); } watchdog_close(true); return 0; }
978
23.475
76
c
null
systemd-main/src/test/test-web-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "macro.h" #include "tests.h" #include "web-util.h" TEST(is_valid_documentation_url) { assert_se(documentation_url_is_valid("https://www.freedesktop.org/wiki/Software/systemd")); assert_se(documentation_url_is_valid("https://www.kernel.org/doc/Documentation/binfmt_misc.txt")); /* dead */ assert_se(documentation_url_is_valid("https://www.kernel.org/doc/Documentation/admin-guide/binfmt-misc.rst")); assert_se(documentation_url_is_valid("https://docs.kernel.org/admin-guide/binfmt-misc.html")); assert_se(documentation_url_is_valid("file:/foo/foo")); assert_se(documentation_url_is_valid("man:systemd.special(7)")); assert_se(documentation_url_is_valid("info:bar")); assert_se(!documentation_url_is_valid("foo:")); assert_se(!documentation_url_is_valid("info:")); assert_se(!documentation_url_is_valid("")); } DEFINE_TEST_MAIN(LOG_INFO);
980
43.590909
118
c
null
systemd-main/src/test/test-xattr-util.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fcntl.h> #include <sys/types.h> #include <sys/xattr.h> #include <unistd.h> #include "alloc-util.h" #include "fd-util.h" #include "fs-util.h" #include "macro.h" #include "rm-rf.h" #include "string-util.h" #include "tests.h" #include "tmpfile-util.h" #include "xattr-util.h" TEST(getxattr_at_malloc) { _cleanup_(rm_rf_physical_and_freep) char *t = NULL; _cleanup_free_ char *value = NULL; _cleanup_close_ int fd = -EBADF; const char *x; int r; fd = mkdtemp_open("/var/tmp/test-xattrtestXXXXXX", O_RDONLY|O_NOCTTY, &t); assert_se(fd >= 0); x = strjoina(t, "/test"); assert_se(touch(x) >= 0); r = setxattr(x, "user.foo", "bar", 3, 0); if (r < 0 && ERRNO_IS_NOT_SUPPORTED(errno)) return (void) log_tests_skipped_errno(errno, "no xattrs supported on /var/tmp"); assert_se(r >= 0); assert_se(getxattr_at_malloc(fd, "test", "user.foo", 0, &value) == 3); assert_se(memcmp(value, "bar", 3) == 0); value = mfree(value); assert_se(getxattr_at_malloc(AT_FDCWD, x, "user.foo", 0, &value) == 3); assert_se(memcmp(value, "bar", 3) == 0); value = mfree(value); safe_close(fd); fd = open("/", O_RDONLY|O_DIRECTORY|O_CLOEXEC|O_NOCTTY); assert_se(fd >= 0); r = getxattr_at_malloc(fd, "usr", "user.idontexist", 0, &value); assert_se(r < 0 && ERRNO_IS_XATTR_ABSENT(r)); safe_close(fd); fd = open(x, O_PATH|O_CLOEXEC); assert_se(fd >= 0); assert_se(getxattr_at_malloc(fd, NULL, "user.foo", 0, &value) == 3); assert_se(streq(value, "bar")); } TEST(getcrtime) { _cleanup_(rm_rf_physical_and_freep) char *t = NULL; _cleanup_close_ int fd = -EBADF; usec_t usec, k; int r; fd = mkdtemp_open("/var/tmp/test-xattrtestXXXXXX", 0, &t); assert_se(fd >= 0); r = fd_getcrtime(fd, &usec); if (r < 0) log_debug_errno(r, "btime: %m"); else log_debug("btime: %s", FORMAT_TIMESTAMP(usec)); k = now(CLOCK_REALTIME); r = fd_setcrtime(fd, 1519126446UL * USEC_PER_SEC); if (!IN_SET(r, -EOPNOTSUPP, -ENOTTY)) { assert_se(fd_getcrtime(fd, &usec) >= 0); assert_se(k < 1519126446UL * USEC_PER_SEC || usec == 1519126446UL * USEC_PER_SEC); } } static void verify_xattr(int dfd, const char *expected) { _cleanup_free_ char *value = NULL; assert_se(getxattr_at_malloc(dfd, "test", "user.foo", 0, &value) == (int) strlen(expected)); assert_se(streq(value, expected)); } TEST(xsetxattr) { _cleanup_(rm_rf_physical_and_freep) char *t = NULL; _cleanup_close_ int dfd = -EBADF, fd = -EBADF; const char *x; int r; dfd = mkdtemp_open("/var/tmp/test-xattrtestXXXXXX", O_PATH, &t); assert_se(dfd >= 0); x = strjoina(t, "/test"); assert_se(touch(x) >= 0); /* by full path */ r = xsetxattr(AT_FDCWD, x, "user.foo", "fullpath", SIZE_MAX, 0); if (r < 0 && ERRNO_IS_NOT_SUPPORTED(r)) return (void) log_tests_skipped_errno(r, "no xattrs supported on /var/tmp"); assert_se(r >= 0); verify_xattr(dfd, "fullpath"); /* by dirfd */ assert_se(xsetxattr(dfd, "test", "user.foo", "dirfd", SIZE_MAX, 0) >= 0); verify_xattr(dfd, "dirfd"); /* by fd (O_PATH) */ fd = openat(dfd, "test", O_PATH|O_CLOEXEC); assert_se(fd >= 0); assert_se(xsetxattr(fd, NULL, "user.foo", "fd_opath", SIZE_MAX, 0) >= 0); verify_xattr(dfd, "fd_opath"); assert_se(xsetxattr(fd, "", "user.foo", "fd_opath", SIZE_MAX, 0) == -EINVAL); assert_se(xsetxattr(fd, "", "user.foo", "fd_opath_empty", SIZE_MAX, AT_EMPTY_PATH) >= 0); verify_xattr(dfd, "fd_opath_empty"); fd = safe_close(fd); fd = openat(dfd, "test", O_RDONLY|O_CLOEXEC); assert_se(xsetxattr(fd, NULL, "user.foo", "fd_regular", SIZE_MAX, 0) >= 0); verify_xattr(dfd, "fd_regular"); assert_se(xsetxattr(fd, "", "user.foo", "fd_regular_empty", SIZE_MAX, 0) == -EINVAL); assert_se(xsetxattr(fd, "", "user.foo", "fd_regular_empty", SIZE_MAX, AT_EMPTY_PATH) >= 0); verify_xattr(dfd, "fd_regular_empty"); } DEFINE_TEST_MAIN(LOG_DEBUG);
4,504
33.653846
100
c
null
systemd-main/src/test/test-xml.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdarg.h> #include "alloc-util.h" #include "string-util.h" #include "xml.h" static void test_one(const char *data, ...) { void *state = NULL; va_list ap; va_start(ap, data); for (;;) { _cleanup_free_ char *name = NULL; int t, tt; const char *nn; t = xml_tokenize(&data, &name, &state, NULL); assert_se(t >= 0); tt = va_arg(ap, int); assert_se(tt >= 0); assert_se(t == tt); if (t == XML_END) break; nn = va_arg(ap, const char *); assert_se(streq_ptr(nn, name)); } va_end(ap); } int main(int argc, char *argv[]) { test_one("", XML_END); test_one("<foo></foo>", XML_TAG_OPEN, "foo", XML_TAG_CLOSE, "foo", XML_END); test_one("<foo waldo=piep meh=\"huhu\"/>", XML_TAG_OPEN, "foo", XML_ATTRIBUTE_NAME, "waldo", XML_ATTRIBUTE_VALUE, "piep", XML_ATTRIBUTE_NAME, "meh", XML_ATTRIBUTE_VALUE, "huhu", XML_TAG_CLOSE_EMPTY, NULL, XML_END); test_one("xxxx\n" "<foo><?xml foo?> <!-- zzzz --> </foo>", XML_TEXT, "xxxx\n", XML_TAG_OPEN, "foo", XML_TEXT, " ", XML_TEXT, " ", XML_TAG_CLOSE, "foo", XML_END); return 0; }
1,663
24.212121
62
c
null
systemd-main/src/test/udev-rule-runner.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright Β© 2003-2004 Greg Kroah-Hartman <[email protected]> ***/ #include <errno.h> #include <sched.h> #include <stdio.h> #include <stdlib.h> #include <sys/mount.h> #include <sys/signalfd.h> #include <unistd.h> #include "device-private.h" #include "fs-util.h" #include "log.h" #include "main-func.h" #include "mkdir-label.h" #include "mount-util.h" #include "namespace-util.h" #include "parse-util.h" #include "selinux-util.h" #include "signal-util.h" #include "string-util.h" #include "tests.h" #include "udev-event.h" #include "version.h" static int device_new_from_synthetic_event(sd_device **ret, const char *syspath, const char *action) { _cleanup_(sd_device_unrefp) sd_device *dev = NULL; sd_device_action_t a; int r; assert(ret); assert(syspath); assert(action); a = device_action_from_string(action); if (a < 0) return a; r = sd_device_new_from_syspath(&dev, syspath); if (r < 0) return r; r = device_read_uevent_file(dev); if (r < 0) return r; r = device_set_action(dev, a); if (r < 0) return r; *ret = TAKE_PTR(dev); return 0; } static int fake_filesystems(void) { static const struct fakefs { const char *src; const char *target; const char *error; bool ignore_mount_error; } fakefss[] = { { "tmpfs/sys", "/sys", "Failed to mount test /sys", false }, { "tmpfs/dev", "/dev", "Failed to mount test /dev", false }, { "run", "/run", "Failed to mount test /run", false }, { "run", "/etc/udev/rules.d", "Failed to mount empty /etc/udev/rules.d", true }, { "run", UDEVLIBEXECDIR "/rules.d", "Failed to mount empty " UDEVLIBEXECDIR "/rules.d", true }, }; int r; r = detach_mount_namespace(); if (r < 0) return log_error_errno(r, "Failed to detach mount namespace: %m"); for (size_t i = 0; i < ELEMENTSOF(fakefss); i++) { r = mount_nofollow_verbose(fakefss[i].ignore_mount_error ? LOG_NOTICE : LOG_ERR, fakefss[i].src, fakefss[i].target, NULL, MS_BIND, NULL); if (r < 0 && !fakefss[i].ignore_mount_error) return r; } return 0; } static int run(int argc, char *argv[]) { _cleanup_(udev_rules_freep) UdevRules *rules = NULL; _cleanup_(udev_event_freep) UdevEvent *event = NULL; _cleanup_(sd_device_unrefp) sd_device *dev = NULL; const char *devpath, *devname, *action; int r; test_setup_logging(LOG_INFO); if (!IN_SET(argc, 2, 3, 4)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This program needs between one and three arguments, %d given", argc - 1); r = fake_filesystems(); if (r < 0) return r; /* Let's make sure the test runs with selinux assumed disabled. */ #if HAVE_SELINUX fini_selinuxmnt(); #endif mac_selinux_retest(); if (argc == 2) { if (!streq(argv[1], "check")) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown argument: %s", argv[1]); return 0; } log_debug("version %s", GIT_VERSION); r = mac_init(); if (r < 0) return r; action = argv[1]; devpath = argv[2]; if (argv[3]) { unsigned us; r = safe_atou(argv[3], &us); if (r < 0) return log_error_errno(r, "Invalid delay '%s': %m", argv[3]); usleep_safe(us); } assert_se(udev_rules_load(&rules, RESOLVE_NAME_EARLY) == 0); const char *syspath = strjoina("/sys", devpath); r = device_new_from_synthetic_event(&dev, syspath, action); if (r < 0) return log_debug_errno(r, "Failed to open device '%s'", devpath); assert_se(event = udev_event_new(dev, 0, NULL, log_get_max_level())); assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, SIGHUP, SIGCHLD, -1) >= 0); /* do what devtmpfs usually provides us */ if (sd_device_get_devname(dev, &devname) >= 0) { const char *subsystem; mode_t mode = 0600; if (sd_device_get_subsystem(dev, &subsystem) >= 0 && streq(subsystem, "block")) mode |= S_IFBLK; else mode |= S_IFCHR; if (!streq(action, "remove")) { dev_t devnum = makedev(0, 0); (void) mkdir_parents_label(devname, 0755); (void) sd_device_get_devnum(dev, &devnum); if (mknod(devname, mode, devnum) < 0) return log_error_errno(errno, "mknod() failed for '%s': %m", devname); } else { if (unlink(devname) < 0) return log_error_errno(errno, "unlink('%s') failed: %m", devname); (void) rmdir_parents(devname, "/dev"); } } udev_event_execute_rules(event, -1, 3 * USEC_PER_SEC, SIGKILL, NULL, rules); udev_event_execute_run(event, 3 * USEC_PER_SEC, SIGKILL); return 0; } DEFINE_MAIN_FUNCTION(run);
5,869
31.977528
118
c
null
systemd-main/src/timesync/timesyncd-conf.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "constants.h" #include "dns-domain.h" #include "extract-word.h" #include "string-util.h" #include "timesyncd-conf.h" #include "timesyncd-manager.h" #include "timesyncd-server.h" int manager_parse_server_string(Manager *m, ServerType type, const char *string) { ServerName *first; int r; assert(m); assert(string); first = type == SERVER_FALLBACK ? m->fallback_servers : m->system_servers; if (type == SERVER_FALLBACK) m->have_fallbacks = true; for (;;) { _cleanup_free_ char *word = NULL; bool found = false; r = extract_first_word(&string, &word, NULL, 0); if (r < 0) return log_error_errno(r, "Failed to parse timesyncd server syntax \"%s\": %m", string); if (r == 0) break; r = dns_name_is_valid_or_address(word); if (r < 0) return log_error_errno(r, "Failed to check validity of NTP server name or address '%s': %m", word); if (r == 0) { log_error("Invalid NTP server name or address, ignoring: %s", word); continue; } /* Filter out duplicates */ LIST_FOREACH(names, n, first) if (streq_ptr(n->string, word)) { found = true; break; } if (found) continue; r = server_name_new(m, NULL, type, word); if (r < 0) return r; } return 0; } int manager_parse_fallback_string(Manager *m, const char *string) { if (m->have_fallbacks) return 0; return manager_parse_server_string(m, SERVER_FALLBACK, string); } int config_parse_servers( 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) { Manager *m = userdata; int r; assert(filename); assert(lvalue); assert(rvalue); if (isempty(rvalue)) manager_flush_server_names(m, ltype); else { r = manager_parse_server_string(m, ltype, rvalue); if (r < 0) { log_syntax(unit, LOG_WARNING, filename, line, r, "Failed to parse NTP server string '%s', ignoring: %m", rvalue); return 0; } } return 0; } int manager_parse_config_file(Manager *m) { int r; assert(m); r = config_parse_config_file("timesyncd.conf", "Time\0", config_item_perf_lookup, timesyncd_gperf_lookup, CONFIG_PARSE_WARN, m); if (r < 0) return r; if (m->poll_interval_min_usec < 16 * USEC_PER_SEC) { log_warning("Invalid PollIntervalMinSec=. Using default value."); m->poll_interval_min_usec = NTP_POLL_INTERVAL_MIN_USEC; } if (m->poll_interval_max_usec < m->poll_interval_min_usec) { log_warning("PollIntervalMaxSec= is smaller than PollIntervalMinSec=. Using default value."); m->poll_interval_max_usec = MAX(NTP_POLL_INTERVAL_MAX_USEC, m->poll_interval_min_usec * 32); } if (m->connection_retry_usec < 1 * USEC_PER_SEC) { log_warning("Invalid ConnectionRetrySec=. Using default value."); m->connection_retry_usec = DEFAULT_CONNECTION_RETRY_USEC; } return r; }
4,073
30.828125
123
c
null
systemd-main/src/timesync/timesyncd-manager.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include <sys/timex.h> #include "sd-bus.h" #include "sd-event.h" #include "sd-network.h" #include "sd-resolve.h" #include "hashmap.h" #include "list.h" #include "ratelimit.h" #include "time-util.h" #include "timesyncd-ntp-message.h" typedef struct Manager Manager; #include "timesyncd-server.h" /* * "A client MUST NOT under any conditions use a poll interval less * than 15 seconds." */ #define NTP_POLL_INTERVAL_MIN_USEC (32 * USEC_PER_SEC) #define NTP_POLL_INTERVAL_MAX_USEC (2048 * USEC_PER_SEC) #define NTP_RETRY_INTERVAL_MIN_USEC (15 * USEC_PER_SEC) #define NTP_RETRY_INTERVAL_MAX_USEC (6 * 60 * USEC_PER_SEC) /* 6 minutes */ #define DEFAULT_CONNECTION_RETRY_USEC (30 * USEC_PER_SEC) #define DEFAULT_SAVE_TIME_INTERVAL_USEC (60 * USEC_PER_SEC) #define STATE_DIR "/var/lib/systemd/timesync" #define CLOCK_FILE STATE_DIR "/clock" struct Manager { sd_bus *bus; sd_event *event; sd_resolve *resolve; LIST_HEAD(ServerName, system_servers); LIST_HEAD(ServerName, link_servers); LIST_HEAD(ServerName, runtime_servers); LIST_HEAD(ServerName, fallback_servers); bool have_fallbacks:1; RateLimit ratelimit; bool exhausted_servers; /* network */ sd_event_source *network_event_source; sd_network_monitor *network_monitor; /* peer */ sd_resolve_query *resolve_query; sd_event_source *event_receive; ServerName *current_server_name; ServerAddress *current_server_address; int server_socket; int missed_replies; uint64_t packet_count; sd_event_source *event_timeout; bool talking; /* PolicyKit */ Hashmap *polkit_registry; /* last sent packet */ struct timespec trans_time_mon; struct timespec trans_time; usec_t retry_interval; usec_t connection_retry_usec; bool pending; /* poll timer */ sd_event_source *event_timer; usec_t poll_interval_usec; usec_t poll_interval_min_usec; usec_t poll_interval_max_usec; bool poll_resync; /* history data */ struct { double offset; double delay; } samples[8]; unsigned samples_idx; double samples_jitter; usec_t root_distance_max_usec; /* last change */ bool jumped; int64_t drift_freq; /* watch for time changes */ sd_event_source *event_clock_watch; /* Retry connections */ sd_event_source *event_retry; /* RTC runs in local time, leave it alone */ bool rtc_local_time; /* NTP response */ struct ntp_msg ntpmsg; struct timespec origin_time, dest_time; bool spike; /* Indicates whether we ever managed to set the local clock from NTP */ bool synchronized; /* save time event */ sd_event_source *event_save_time; usec_t save_time_interval_usec; bool save_on_exit; }; int manager_new(Manager **ret); Manager* manager_free(Manager *m); DEFINE_TRIVIAL_CLEANUP_FUNC(Manager*, manager_free); void manager_set_server_name(Manager *m, ServerName *n); void manager_set_server_address(Manager *m, ServerAddress *a); void manager_flush_server_names(Manager *m, ServerType t); void manager_flush_runtime_servers(Manager *m); int manager_connect(Manager *m); void manager_disconnect(Manager *m); bool manager_is_connected(Manager *m); int manager_setup_save_time_event(Manager *m);
3,648
25.830882
79
h
null
systemd-main/src/timesync/timesyncd-ntp-message.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "sparse-endian.h" /* NTP protocol, packet header */ #define NTP_LEAP_PLUSSEC 1 #define NTP_LEAP_MINUSSEC 2 #define NTP_LEAP_NOTINSYNC 3 #define NTP_MODE_CLIENT 3 #define NTP_MODE_SERVER 4 #define NTP_FIELD_LEAP(f) (((f) >> 6) & 3) #define NTP_FIELD_VERSION(f) (((f) >> 3) & 7) #define NTP_FIELD_MODE(f) ((f) & 7) #define NTP_FIELD(l, v, m) (((l) << 6) | ((v) << 3) | (m)) /* * "NTP timestamps are represented as a 64-bit unsigned fixed-point number, * in seconds relative to 0h on 1 January 1900." */ #define OFFSET_1900_1970 UINT64_C(2208988800) struct ntp_ts { be32_t sec; be32_t frac; } _packed_; struct ntp_ts_short { be16_t sec; be16_t frac; } _packed_; struct ntp_msg { uint8_t field; uint8_t stratum; int8_t poll; int8_t precision; struct ntp_ts_short root_delay; struct ntp_ts_short root_dispersion; char refid[4]; struct ntp_ts reference_time; struct ntp_ts origin_time; struct ntp_ts recv_time; struct ntp_ts trans_time; } _packed_;
1,276
26.76087
75
h
null
systemd-main/src/timesync/timesyncd-server.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "string-table.h" #include "timesyncd-server.h" static const char * const server_type_table[_SERVER_TYPE_MAX] = { [SERVER_SYSTEM] = "system", [SERVER_FALLBACK] = "fallback", [SERVER_LINK] = "link", [SERVER_RUNTIME] = "runtime", }; DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(server_type, ServerType); int server_address_new( ServerName *n, ServerAddress **ret, const union sockaddr_union *sockaddr, socklen_t socklen) { ServerAddress *a, *tail; assert(n); assert(sockaddr); assert(socklen >= offsetof(struct sockaddr, sa_data)); assert(socklen <= sizeof(union sockaddr_union)); a = new(ServerAddress, 1); if (!a) return -ENOMEM; *a = (ServerAddress) { .name = n, .socklen = socklen, }; memcpy(&a->sockaddr, sockaddr, socklen); tail = LIST_FIND_TAIL(addresses, n->addresses); LIST_INSERT_AFTER(addresses, n->addresses, tail, a); if (ret) *ret = a; return 0; } ServerAddress* server_address_free(ServerAddress *a) { if (!a) return NULL; if (a->name) { LIST_REMOVE(addresses, a->name->addresses, a); if (a->name->manager && a->name->manager->current_server_address == a) manager_set_server_address(a->name->manager, NULL); } return mfree(a); } int server_name_new( Manager *m, ServerName **ret, ServerType type, const char *string) { ServerName *n; assert(m); assert(string); n = new(ServerName, 1); if (!n) return -ENOMEM; *n = (ServerName) { .manager = m, .type = type, .string = strdup(string), }; if (!n->string) { free(n); return -ENOMEM; } switch (type) { case SERVER_SYSTEM: LIST_APPEND(names, m->system_servers, n); break; case SERVER_LINK: LIST_APPEND(names, m->link_servers, n); break; case SERVER_FALLBACK: LIST_APPEND(names, m->fallback_servers, n); break; case SERVER_RUNTIME: LIST_APPEND(names, m->runtime_servers, n); break; default: assert_not_reached(); } if (type != SERVER_FALLBACK && m->current_server_name && m->current_server_name->type == SERVER_FALLBACK) manager_set_server_name(m, NULL); log_debug("Added new %s server %s.", server_type_to_string(type), string); if (ret) *ret = n; return 0; } ServerName *server_name_free(ServerName *n) { if (!n) return NULL; server_name_flush_addresses(n); if (n->manager) { if (n->type == SERVER_SYSTEM) LIST_REMOVE(names, n->manager->system_servers, n); else if (n->type == SERVER_LINK) LIST_REMOVE(names, n->manager->link_servers, n); else if (n->type == SERVER_FALLBACK) LIST_REMOVE(names, n->manager->fallback_servers, n); else if (n->type == SERVER_RUNTIME) LIST_REMOVE(names, n->manager->runtime_servers, n); else assert_not_reached(); if (n->manager->current_server_name == n) manager_set_server_name(n->manager, NULL); } log_debug("Removed server %s.", n->string); free(n->string); return mfree(n); } void server_name_flush_addresses(ServerName *n) { assert(n); while (n->addresses) server_address_free(n->addresses); }
4,151
26.137255
86
c
null
systemd-main/src/timesync/timesyncd-server.h
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #pragma once #include "list.h" #include "socket-util.h" typedef struct ServerAddress ServerAddress; typedef struct ServerName ServerName; typedef enum ServerType { SERVER_SYSTEM, SERVER_FALLBACK, SERVER_LINK, SERVER_RUNTIME, _SERVER_TYPE_MAX, _SERVER_TYPE_INVALID = -EINVAL, } ServerType; #include "timesyncd-manager.h" struct ServerAddress { ServerName *name; union sockaddr_union sockaddr; socklen_t socklen; LIST_FIELDS(ServerAddress, addresses); }; struct ServerName { Manager *manager; ServerType type; char *string; bool marked:1; LIST_HEAD(ServerAddress, addresses); LIST_FIELDS(ServerName, names); }; int server_address_new(ServerName *n, ServerAddress **ret, const union sockaddr_union *sockaddr, socklen_t socklen); ServerAddress* server_address_free(ServerAddress *a); static inline int server_address_pretty(ServerAddress *a, char **pretty) { return sockaddr_pretty(&a->sockaddr.sa, a->socklen, true, true, pretty); } int server_name_new(Manager *m, ServerName **ret, ServerType type,const char *string); ServerName *server_name_free(ServerName *n); void server_name_flush_addresses(ServerName *n);
1,309
24.686275
116
h
null
systemd-main/src/timesync/wait-sync.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /* systemd service to wait until kernel realtime clock is synchronized */ #include <errno.h> #include <stdbool.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/inotify.h> #include <sys/timerfd.h> #include <sys/timex.h> #include <unistd.h> #include "sd-event.h" #include "fd-util.h" #include "inotify-util.h" #include "main-func.h" #include "signal-util.h" #include "time-util.h" typedef struct ClockState { int timerfd_fd; /* non-negative is descriptor from timerfd_create */ int adjtime_state; /* return value from last adjtimex(2) call */ sd_event_source *timerfd_event_source; /* non-null is the active io event source */ int inotify_fd; sd_event_source *inotify_event_source; int run_systemd_wd; int run_systemd_timesync_wd; bool has_watchfile; } ClockState; static void clock_state_release_timerfd(ClockState *sp) { sp->timerfd_event_source = sd_event_source_unref(sp->timerfd_event_source); sp->timerfd_fd = safe_close(sp->timerfd_fd); } static void clock_state_release(ClockState *sp) { clock_state_release_timerfd(sp); sp->inotify_event_source = sd_event_source_unref(sp->inotify_event_source); sp->inotify_fd = safe_close(sp->inotify_fd); } static int clock_state_update(ClockState *sp, sd_event *event); static int update_notify_run_systemd_timesync(ClockState *sp) { sp->run_systemd_timesync_wd = inotify_add_watch(sp->inotify_fd, "/run/systemd/timesync", IN_CREATE|IN_DELETE_SELF); return sp->run_systemd_timesync_wd; } static int timerfd_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) { ClockState *sp = userdata; return clock_state_update(sp, sd_event_source_get_event(s)); } static void process_inotify_event(sd_event *event, ClockState *sp, struct inotify_event *e) { if (e->wd == sp->run_systemd_wd) { /* Only thing we care about is seeing if we can start watching /run/systemd/timesync. */ if (sp->run_systemd_timesync_wd < 0) update_notify_run_systemd_timesync(sp); } else if (e->wd == sp->run_systemd_timesync_wd) { if (e->mask & IN_DELETE_SELF) { /* Somebody removed /run/systemd/timesync. */ (void) inotify_rm_watch(sp->inotify_fd, sp->run_systemd_timesync_wd); sp->run_systemd_timesync_wd = -1; } else /* Somebody might have created /run/systemd/timesync/synchronized. */ clock_state_update(sp, event); } } static int inotify_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) { sd_event *event = sd_event_source_get_event(s); ClockState *sp = userdata; union inotify_event_buffer buffer; ssize_t l; l = read(fd, &buffer, sizeof(buffer)); if (l < 0) { if (ERRNO_IS_TRANSIENT(errno)) return 0; return log_warning_errno(errno, "Lost access to inotify: %m"); } FOREACH_INOTIFY_EVENT_WARN(e, buffer, l) process_inotify_event(event, sp, e); return 0; } static int clock_state_update( ClockState *sp, sd_event *event) { struct timex tx = {}; usec_t t; int r; clock_state_release_timerfd(sp); /* The kernel supports cancelling timers whenever its realtime clock is "set" (which can happen in a variety of * ways, generally adjustments of at least 500 ms). The way this module works is we set up a timerfd that will * wake when the clock is set, and when that happens we read the clock synchronization state from the return * value of adjtimex(2), which supports the NTP time adjustment protocol. * * The kernel determines whether the clock is synchronized using driver-specific tests, based on time * information passed by an application, generally through adjtimex(2). If the application asserts the clock is * synchronized, but does not also do something that "sets the clock", the timer will not be cancelled and * synchronization will not be detected. * * Similarly, this service will never complete if the application sets the time without also providing * information that adjtimex(2) can use to determine that the clock is synchronized. This generally doesn't * happen, but can if the system has a hardware clock that is accurate enough that the adjustment is too small * to be a "set". * * Both these failure-to-detect situations are covered by having the presence/creation of * /run/systemd/timesync/synchronized, which is considered sufficient to indicate a synchronized clock even if * the kernel has not been updated. * * For timesyncd the initial setting of the time uses settimeofday(2), which sets the clock but does not mark * it synchronized. When an NTP source is selected it sets the clock again with clock_adjtime(2) which marks it * synchronized and also touches /run/systemd/timesync/synchronized which covers the case when the clock wasn't * "set". */ r = time_change_fd(); if (r < 0) { log_error_errno(r, "Failed to create timerfd: %m"); goto finish; } sp->timerfd_fd = r; r = adjtimex(&tx); if (r < 0) { log_error_errno(errno, "Failed to read adjtimex state: %m"); goto finish; } sp->adjtime_state = r; if (tx.status & STA_NANO) tx.time.tv_usec /= 1000; t = timeval_load(&tx.time); log_info("adjtime state %i status %x time %s", sp->adjtime_state, (unsigned) tx.status, FORMAT_TIMESTAMP_STYLE(t, TIMESTAMP_US_UTC) ?: "unrepresentable"); sp->has_watchfile = access("/run/systemd/timesync/synchronized", F_OK) >= 0; if (sp->has_watchfile) /* Presence of watch file overrides adjtime_state */ r = 0; else if (sp->adjtime_state == TIME_ERROR) { /* Not synchronized. Do a one-shot wait on the descriptor and inform the caller we need to keep * running. */ r = sd_event_add_io(event, &sp->timerfd_event_source, sp->timerfd_fd, EPOLLIN, timerfd_handler, sp); if (r < 0) { log_error_errno(r, "Failed to create time change monitor source: %m"); goto finish; } r = 1; } else /* Synchronized; we can exit. */ r = 0; finish: if (r <= 0) (void) sd_event_exit(event, r); return r; } static int run(int argc, char * argv[]) { _cleanup_(sd_event_unrefp) sd_event *event = NULL; _cleanup_(clock_state_release) ClockState state = { .timerfd_fd = -EBADF, .inotify_fd = -EBADF, .run_systemd_wd = -1, .run_systemd_timesync_wd = -1, }; int r; assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGTERM, SIGINT, -1) >= 0); r = sd_event_default(&event); if (r < 0) return log_error_errno(r, "Failed to allocate event loop: %m"); r = sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL); if (r < 0) return log_error_errno(r, "Failed to create sigterm event source: %m"); r = sd_event_add_signal(event, NULL, SIGINT, NULL, NULL); if (r < 0) return log_error_errno(r, "Failed to create sigint event source: %m"); r = sd_event_set_watchdog(event, true); if (r < 0) return log_error_errno(r, "Failed to create watchdog event source: %m"); r = inotify_init1(IN_NONBLOCK|IN_CLOEXEC); if (r < 0) return log_error_errno(errno, "Failed to create inotify descriptor: %m"); state.inotify_fd = r; r = sd_event_add_io(event, &state.inotify_event_source, state.inotify_fd, EPOLLIN, inotify_handler, &state); if (r < 0) return log_error_errno(r, "Failed to create notify event source: %m"); r = inotify_add_watch_and_warn(state.inotify_fd, "/run/systemd/", IN_CREATE); if (r < 0) return r; state.run_systemd_wd = r; (void) update_notify_run_systemd_timesync(&state); r = clock_state_update(&state, event); if (r > 0) { r = sd_event_loop(event); if (r < 0) log_error_errno(r, "Failed in event loop: %m"); } if (state.has_watchfile) log_debug("Exit enabled by: /run/systemd/timesync/synchronized"); if (state.adjtime_state == TIME_ERROR) log_info("Exit without adjtimex synchronized."); return r; } DEFINE_MAIN_FUNCTION(run);
9,466
38.282158
123
c
null
systemd-main/src/tmpfiles/offline-passwd.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "chase.h" #include "fd-util.h" #include "offline-passwd.h" #include "path-util.h" #include "user-util.h" DEFINE_PRIVATE_HASH_OPS_WITH_KEY_DESTRUCTOR(uid_gid_hash_ops, char, string_hash_func, string_compare_func, free); static int open_passwd_file(const char *root, const char *fname, FILE **ret_file) { _cleanup_free_ char *p = NULL; _cleanup_close_ int fd = -EBADF; _cleanup_fclose_ FILE *f = NULL; fd = chase_and_open(fname, root, CHASE_PREFIX_ROOT, O_RDONLY|O_CLOEXEC, &p); if (fd < 0) return fd; f = fdopen(fd, "r"); if (!f) return -errno; TAKE_FD(fd); if (DEBUG_LOGGING) { _cleanup_free_ char *bn = NULL; (void) path_extract_filename(fname, &bn); log_debug("Reading %s entries from %s...", strna(bn), p); } *ret_file = TAKE_PTR(f); return 0; } static int populate_uid_cache(const char *root, Hashmap **ret) { _cleanup_hashmap_free_ Hashmap *cache = NULL; int r; cache = hashmap_new(&uid_gid_hash_ops); if (!cache) return -ENOMEM; /* The directory list is hardcoded here: /etc is the standard, and rpm-ostree uses /usr/lib. This * could be made configurable, but I don't see the point right now. */ FOREACH_STRING(fname, "/etc/passwd", "/usr/lib/passwd") { _cleanup_fclose_ FILE *f = NULL; r = open_passwd_file(root, fname, &f); if (r == -ENOENT) continue; if (r < 0) return r; struct passwd *pw; while ((r = fgetpwent_sane(f, &pw)) > 0) { _cleanup_free_ char *n = NULL; n = strdup(pw->pw_name); if (!n) return -ENOMEM; r = hashmap_put(cache, n, UID_TO_PTR(pw->pw_uid)); if (IN_SET(r, 0, -EEXIST)) continue; if (r < 0) return r; TAKE_PTR(n); } } *ret = TAKE_PTR(cache); return 0; } static int populate_gid_cache(const char *root, Hashmap **ret) { _cleanup_hashmap_free_ Hashmap *cache = NULL; int r; cache = hashmap_new(&uid_gid_hash_ops); if (!cache) return -ENOMEM; FOREACH_STRING(fname, "/etc/group", "/usr/lib/group") { _cleanup_fclose_ FILE *f = NULL; r = open_passwd_file(root, fname, &f); if (r == -ENOENT) continue; if (r < 0) return r; struct group *gr; while ((r = fgetgrent_sane(f, &gr)) > 0) { _cleanup_free_ char *n = NULL; n = strdup(gr->gr_name); if (!n) return -ENOMEM; r = hashmap_put(cache, n, GID_TO_PTR(gr->gr_gid)); if (IN_SET(r, 0, -EEXIST)) continue; if (r < 0) return r; TAKE_PTR(n); } } *ret = TAKE_PTR(cache); return 0; } int name_to_uid_offline( const char *root, const char *user, uid_t *ret_uid, Hashmap **cache) { void *found; int r; assert(user); assert(ret_uid); assert(cache); if (!*cache) { r = populate_uid_cache(root, cache); if (r < 0) return r; } found = hashmap_get(*cache, user); if (!found) return -ESRCH; *ret_uid = PTR_TO_UID(found); return 0; } int name_to_gid_offline( const char *root, const char *group, gid_t *ret_gid, Hashmap **cache) { void *found; int r; assert(group); assert(ret_gid); assert(cache); if (!*cache) { r = populate_gid_cache(root, cache); if (r < 0) return r; } found = hashmap_get(*cache, group); if (!found) return -ESRCH; *ret_gid = PTR_TO_GID(found); return 0; }
4,682
26.710059
113
c
null
systemd-main/src/tmpfiles/test-offline-passwd.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include "offline-passwd.h" #include "user-util.h" #include "format-util.h" #include "tests.h" static char *arg_root = NULL; static void test_resolve_one(const char *name) { bool relaxed = name || arg_root; if (!name) name = "root"; log_info("/* %s(\"%s\") */", __func__, name); _cleanup_hashmap_free_ Hashmap *uid_cache = NULL, *gid_cache = NULL; uid_t uid = UID_INVALID; gid_t gid = GID_INVALID; int r; r = name_to_uid_offline(arg_root, name, &uid, &uid_cache); log_info_errno(r, "name_to_uid_offline: %s β†’ "UID_FMT": %m", name, uid); assert_se(relaxed || r == 0); r = name_to_uid_offline(arg_root, name, &uid, &uid_cache); log_info_errno(r, "name_to_uid_offline: %s β†’ "UID_FMT": %m", name, uid); assert_se(relaxed || r == 0); r = name_to_gid_offline(arg_root, name, &gid, &gid_cache); log_info_errno(r, "name_to_gid_offline: %s β†’ "GID_FMT": %m", name, gid); assert_se(relaxed || r == 0); r = name_to_gid_offline(arg_root, name, &gid, &gid_cache); log_info_errno(r, "name_to_gid_offline: %s β†’ "GID_FMT": %m", name, gid); assert_se(relaxed || r == 0); } static int parse_argv(int argc, char *argv[]) { static const struct option options[] = { { "root", required_argument, NULL, 'r' }, {} }; int c; assert_se(argc >= 0); assert_se(argv); while ((c = getopt_long(argc, argv, "r:", options, NULL)) >= 0) switch (c) { case 'r': arg_root = optarg; break; case '?': return -EINVAL; default: assert_not_reached(); } return 0; } int main(int argc, char **argv) { int r; test_setup_logging(LOG_DEBUG); r = parse_argv(argc, argv); if (r < 0) return r; if (optind >= argc) test_resolve_one(NULL); else while (optind < argc) test_resolve_one(argv[optind++]); return 0; }
2,324
26.034884
80
c
null
systemd-main/src/tty-ask-password-agent/tty-ask-password-agent.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ /*** Copyright Β© 2015 Werner Fink ***/ #include <errno.h> #include <fcntl.h> #include <getopt.h> #include <stdbool.h> #include <stddef.h> #include <sys/prctl.h> #include <sys/signalfd.h> #include <sys/stat.h> #include <sys/types.h> #include <sys/un.h> #include <sys/wait.h> #include <unistd.h> #include "alloc-util.h" #include "ask-password-api.h" #include "build.h" #include "conf-parser.h" #include "constants.h" #include "dirent-util.h" #include "exit-status.h" #include "fd-util.h" #include "fileio.h" #include "hashmap.h" #include "inotify-util.h" #include "io-util.h" #include "macro.h" #include "main-func.h" #include "memory-util.h" #include "mkdir-label.h" #include "path-util.h" #include "pretty-print.h" #include "process-util.h" #include "set.h" #include "signal-util.h" #include "socket-util.h" #include "string-util.h" #include "strv.h" #include "terminal-util.h" #include "utmp-wtmp.h" static enum { ACTION_LIST, ACTION_QUERY, ACTION_WATCH, ACTION_WALL, } arg_action = ACTION_QUERY; static bool arg_plymouth = false; static bool arg_console = false; static const char *arg_device = NULL; static int send_passwords(const char *socket_name, char **passwords) { _cleanup_(erase_and_freep) char *packet = NULL; _cleanup_close_ int socket_fd = -EBADF; union sockaddr_union sa; socklen_t sa_len; size_t packet_length = 1; char *d; ssize_t n; int r; assert(socket_name); r = sockaddr_un_set_path(&sa.un, socket_name); if (r < 0) return r; sa_len = r; STRV_FOREACH(p, passwords) packet_length += strlen(*p) + 1; packet = new(char, packet_length); if (!packet) return -ENOMEM; packet[0] = '+'; d = packet + 1; STRV_FOREACH(p, passwords) d = stpcpy(d, *p) + 1; socket_fd = socket(AF_UNIX, SOCK_DGRAM|SOCK_CLOEXEC, 0); if (socket_fd < 0) return log_debug_errno(errno, "socket(): %m"); n = sendto(socket_fd, packet, packet_length, MSG_NOSIGNAL, &sa.sa, sa_len); if (n < 0) return log_debug_errno(errno, "sendto(): %m"); return (int) n; } static bool wall_tty_match(const char *path, bool is_local, void *userdata) { _cleanup_free_ char *p = NULL; _cleanup_close_ int fd = -EBADF; struct stat st; assert(path_is_absolute(path)); if (lstat(path, &st) < 0) { log_debug_errno(errno, "Failed to stat %s: %m", path); return true; } if (!S_ISCHR(st.st_mode)) { log_debug("%s is not a character device.", path); return true; } /* We use named pipes to ensure that wall messages suggesting * password entry are not printed over password prompts * already shown. We use the fact here that opening a pipe in * non-blocking mode for write-only will succeed only if * there's some writer behind it. Using pipes has the * advantage that the block will automatically go away if the * process dies. */ if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(st.st_rdev), minor(st.st_rdev)) < 0) { log_oom(); return true; } fd = open(p, O_WRONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY); if (fd < 0) { log_debug_errno(errno, "Failed to open the wall pipe: %m"); return 1; } /* What, we managed to open the pipe? Then this tty is filtered. */ return 0; } static int agent_ask_password_tty( const char *message, usec_t until, AskPasswordFlags flags, const char *flag_file, char ***ret) { int tty_fd = -EBADF, r; const char *con = arg_device ?: "/dev/console"; if (arg_console) { tty_fd = acquire_terminal(con, ACQUIRE_TERMINAL_WAIT, USEC_INFINITY); if (tty_fd < 0) return log_error_errno(tty_fd, "Failed to acquire %s: %m", con); r = reset_terminal_fd(tty_fd, true); if (r < 0) log_warning_errno(r, "Failed to reset terminal, ignoring: %m"); log_info("Starting password query on %s.", con); } r = ask_password_tty(tty_fd, message, NULL, until, flags, flag_file, ret); if (arg_console) { tty_fd = safe_close(tty_fd); release_terminal(); if (r >= 0) log_info("Password query on %s finished successfully.", con); } return r; } static int process_one_password_file(const char *filename) { _cleanup_free_ char *socket_name = NULL, *message = NULL; bool accept_cached = false, echo = false, silent = false; uint64_t not_after = 0; pid_t pid = 0; const ConfigTableItem items[] = { { "Ask", "Socket", config_parse_string, CONFIG_PARSE_STRING_SAFE, &socket_name }, { "Ask", "NotAfter", config_parse_uint64, 0, &not_after }, { "Ask", "Message", config_parse_string, 0, &message }, { "Ask", "PID", config_parse_pid, 0, &pid }, { "Ask", "AcceptCached", config_parse_bool, 0, &accept_cached }, { "Ask", "Echo", config_parse_bool, 0, &echo }, { "Ask", "Silent", config_parse_bool, 0, &silent }, {} }; int r; assert(filename); r = config_parse(NULL, filename, NULL, NULL, config_item_table_lookup, items, CONFIG_PARSE_RELAXED|CONFIG_PARSE_WARN, NULL, NULL); if (r < 0) return r; if (!socket_name) return log_error_errno(SYNTHETIC_ERRNO(EBADMSG), "Invalid password file %s", filename); if (not_after > 0 && now(CLOCK_MONOTONIC) > not_after) return 0; if (pid > 0 && !pid_is_alive(pid)) return 0; switch (arg_action) { case ACTION_LIST: printf("'%s' (PID " PID_FMT ")\n", strna(message), pid); return 0; case ACTION_WALL: { _cleanup_free_ char *wall = NULL; if (asprintf(&wall, "Password entry required for \'%s\' (PID " PID_FMT ").\r\n" "Please enter password with the systemd-tty-ask-password-agent tool.", strna(message), pid) < 0) return log_oom(); (void) utmp_wall(wall, NULL, NULL, wall_tty_match, NULL); return 0; } case ACTION_QUERY: case ACTION_WATCH: { _cleanup_strv_free_erase_ char **passwords = NULL; AskPasswordFlags flags = 0; if (access(socket_name, W_OK) < 0) { if (arg_action == ACTION_QUERY) log_info("Not querying '%s' (PID " PID_FMT "), lacking privileges.", strna(message), pid); return 0; } SET_FLAG(flags, ASK_PASSWORD_ACCEPT_CACHED, accept_cached); SET_FLAG(flags, ASK_PASSWORD_CONSOLE_COLOR, arg_console); SET_FLAG(flags, ASK_PASSWORD_ECHO, echo); SET_FLAG(flags, ASK_PASSWORD_SILENT, silent); if (arg_plymouth) r = ask_password_plymouth(message, not_after, flags, filename, &passwords); else r = agent_ask_password_tty(message, not_after, flags, filename, &passwords); if (r < 0) { /* If the query went away, that's OK */ if (IN_SET(r, -ETIME, -ENOENT)) return 0; return log_error_errno(r, "Failed to query password: %m"); } if (strv_isempty(passwords)) return -ECANCELED; r = send_passwords(socket_name, passwords); if (r < 0) return log_error_errno(r, "Failed to send: %m"); break; }} return 0; } static int wall_tty_block(void) { _cleanup_free_ char *p = NULL; dev_t devnr; int fd, r; r = get_ctty_devnr(0, &devnr); if (r == -ENXIO) /* We have no controlling tty */ return -ENOTTY; if (r < 0) return log_error_errno(r, "Failed to get controlling TTY: %m"); if (asprintf(&p, "/run/systemd/ask-password-block/%u:%u", major(devnr), minor(devnr)) < 0) return log_oom(); (void) mkdir_parents_label(p, 0700); (void) mkfifo(p, 0600); fd = open(p, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY); if (fd < 0) return log_debug_errno(errno, "Failed to open %s: %m", p); return fd; } static int process_password_files(void) { _cleanup_closedir_ DIR *d = NULL; int r = 0; d = opendir("/run/systemd/ask-password"); if (!d) { if (errno == ENOENT) return 0; return log_error_errno(errno, "Failed to open /run/systemd/ask-password: %m"); } FOREACH_DIRENT(de, d, return log_error_errno(errno, "Failed to read directory: %m")) { _cleanup_free_ char *p = NULL; int q; /* We only support /run on tmpfs, hence we can rely on * d_type to be reliable */ if (de->d_type != DT_REG) continue; if (!startswith(de->d_name, "ask.")) continue; p = path_join("/run/systemd/ask-password", de->d_name); if (!p) return log_oom(); q = process_one_password_file(p); if (q < 0 && r == 0) r = q; } return r; } static int process_and_watch_password_files(bool watch) { enum { FD_SIGNAL, FD_INOTIFY, _FD_MAX }; _unused_ _cleanup_close_ int tty_block_fd = -EBADF; _cleanup_close_ int notify = -EBADF, signal_fd = -EBADF; struct pollfd pollfd[_FD_MAX]; sigset_t mask; int r; tty_block_fd = wall_tty_block(); (void) mkdir_p_label("/run/systemd/ask-password", 0755); assert_se(sigemptyset(&mask) >= 0); assert_se(sigset_add_many(&mask, SIGTERM, -1) >= 0); assert_se(sigprocmask(SIG_SETMASK, &mask, NULL) >= 0); if (watch) { signal_fd = signalfd(-1, &mask, SFD_NONBLOCK|SFD_CLOEXEC); if (signal_fd < 0) return log_error_errno(errno, "Failed to allocate signal file descriptor: %m"); pollfd[FD_SIGNAL] = (struct pollfd) { .fd = signal_fd, .events = POLLIN }; notify = inotify_init1(IN_CLOEXEC); if (notify < 0) return log_error_errno(errno, "Failed to allocate directory watch: %m"); r = inotify_add_watch_and_warn(notify, "/run/systemd/ask-password", IN_CLOSE_WRITE|IN_MOVED_TO); if (r < 0) return r; pollfd[FD_INOTIFY] = (struct pollfd) { .fd = notify, .events = POLLIN }; } for (;;) { usec_t timeout = USEC_INFINITY; r = process_password_files(); if (r < 0) { if (r == -ECANCELED) /* Disable poll() timeout since at least one password has * been skipped and therefore one file remains and is * unlikely to trigger any events. */ timeout = 0; else /* FIXME: we should do something here since otherwise the service * requesting the password won't notice the error and will wait * indefinitely. */ log_error_errno(r, "Failed to process password: %m"); } if (!watch) break; r = ppoll_usec(pollfd, _FD_MAX, timeout); if (r == -EINTR) continue; if (r < 0) return r; if (pollfd[FD_INOTIFY].revents != 0) (void) flush_fd(notify); if (pollfd[FD_SIGNAL].revents != 0) break; } return 0; } static int help(void) { _cleanup_free_ char *link = NULL; int r; r = terminal_urlify_man("systemd-tty-ask-password-agent", "1", &link); if (r < 0) return log_oom(); printf("%s [OPTIONS...]\n\n" "%sProcess system password requests.%s\n\n" " -h --help Show this help\n" " --version Show package version\n" " --list Show pending password requests\n" " --query Process pending password requests\n" " --watch Continuously process password requests\n" " --wall Continuously forward password requests to wall\n" " --plymouth Ask question with Plymouth instead of on TTY\n" " --console[=DEVICE] Ask question on /dev/console (or DEVICE if specified)\n" " instead of the current TTY\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_LIST = 0x100, ARG_QUERY, ARG_WATCH, ARG_WALL, ARG_PLYMOUTH, ARG_CONSOLE, ARG_VERSION }; static const struct option options[] = { { "help", no_argument, NULL, 'h' }, { "version", no_argument, NULL, ARG_VERSION }, { "list", no_argument, NULL, ARG_LIST }, { "query", no_argument, NULL, ARG_QUERY }, { "watch", no_argument, NULL, ARG_WATCH }, { "wall", no_argument, NULL, ARG_WALL }, { "plymouth", no_argument, NULL, ARG_PLYMOUTH }, { "console", optional_argument, NULL, ARG_CONSOLE }, {} }; int c; assert(argc >= 0); assert(argv); while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0) switch (c) { case 'h': return help(); case ARG_VERSION: return version(); case ARG_LIST: arg_action = ACTION_LIST; break; case ARG_QUERY: arg_action = ACTION_QUERY; break; case ARG_WATCH: arg_action = ACTION_WATCH; break; case ARG_WALL: arg_action = ACTION_WALL; break; case ARG_PLYMOUTH: arg_plymouth = true; break; case ARG_CONSOLE: arg_console = true; if (optarg) { if (isempty(optarg)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Empty console device path is not allowed."); arg_device = optarg; } break; case '?': return -EINVAL; default: assert_not_reached(); } if (optind != argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "%s takes no arguments.", program_invocation_short_name); if (arg_plymouth || arg_console) { if (!IN_SET(arg_action, ACTION_QUERY, ACTION_WATCH)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Options --query and --watch conflict."); if (arg_plymouth && arg_console) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Options --plymouth and --console conflict."); } return 1; } /* * To be able to ask on all terminal devices of /dev/console the devices are collected. If more than one * device is found, then on each of the terminals an inquiring task is forked. Every task has its own session * and its own controlling terminal. If one of the tasks does handle a password, the remaining tasks will be * terminated. */ static int ask_on_this_console(const char *tty, pid_t *ret_pid, char **arguments) { static const struct sigaction sigchld = { .sa_handler = nop_signal_handler, .sa_flags = SA_NOCLDSTOP | SA_RESTART, }; static const struct sigaction sighup = { .sa_handler = SIG_DFL, .sa_flags = SA_RESTART, }; int r; assert_se(sigaction(SIGCHLD, &sigchld, NULL) >= 0); assert_se(sigaction(SIGHUP, &sighup, NULL) >= 0); assert_se(sigprocmask_many(SIG_UNBLOCK, NULL, SIGHUP, SIGCHLD, -1) >= 0); r = safe_fork("(sd-passwd)", FORK_RESET_SIGNALS|FORK_LOG, ret_pid); if (r < 0) return r; if (r == 0) { assert_se(prctl(PR_SET_PDEATHSIG, SIGHUP) >= 0); STRV_FOREACH(i, arguments) { char *k; if (!streq(*i, "--console")) continue; k = strjoin("--console=", tty); if (!k) { log_oom(); _exit(EXIT_FAILURE); } free_and_replace(*i, k); } execv(SYSTEMD_TTY_ASK_PASSWORD_AGENT_BINARY_PATH, arguments); _exit(EXIT_FAILURE); } return 0; } static void terminate_agents(Set *pids) { sigset_t set; void *p; int r, signum; /* * Request termination of the remaining processes as those * are not required anymore. */ SET_FOREACH(p, pids) (void) kill(PTR_TO_PID(p), SIGTERM); /* * Collect the processes which have go away. */ assert_se(sigemptyset(&set) >= 0); assert_se(sigaddset(&set, SIGCHLD) >= 0); while (!set_isempty(pids)) { siginfo_t status = {}; r = waitid(P_ALL, 0, &status, WEXITED|WNOHANG); if (r < 0 && errno == EINTR) continue; if (r == 0 && status.si_pid > 0) { set_remove(pids, PID_TO_PTR(status.si_pid)); continue; } signum = sigtimedwait(&set, NULL, TIMESPEC_STORE(50 * USEC_PER_MSEC)); if (signum < 0) { if (errno != EAGAIN) log_error_errno(errno, "sigtimedwait() failed: %m"); break; } assert(signum == SIGCHLD); } /* * Kill hanging processes. */ SET_FOREACH(p, pids) { log_warning("Failed to terminate child %d, killing it", PTR_TO_PID(p)); (void) kill(PTR_TO_PID(p), SIGKILL); } } static int ask_on_consoles(char *argv[]) { _cleanup_set_free_ Set *pids = NULL; _cleanup_strv_free_ char **consoles = NULL, **arguments = NULL; siginfo_t status = {}; pid_t pid; int r; r = get_kernel_consoles(&consoles); if (r < 0) return log_error_errno(r, "Failed to determine devices of /dev/console: %m"); pids = set_new(NULL); if (!pids) return log_oom(); arguments = strv_copy(argv); if (!arguments) return log_oom(); /* Start an agent on each console. */ STRV_FOREACH(tty, consoles) { r = ask_on_this_console(*tty, &pid, arguments); if (r < 0) return r; if (set_put(pids, PID_TO_PTR(pid)) < 0) return log_oom(); } /* Wait for an agent to exit. */ for (;;) { zero(status); if (waitid(P_ALL, 0, &status, WEXITED) < 0) { if (errno == EINTR) continue; return log_error_errno(errno, "waitid() failed: %m"); } set_remove(pids, PID_TO_PTR(status.si_pid)); break; } if (!is_clean_exit(status.si_code, status.si_status, EXIT_CLEAN_DAEMON, NULL)) log_error("Password agent failed with: %d", status.si_status); terminate_agents(pids); return 0; } static int run(int argc, char *argv[]) { int r; log_setup(); umask(0022); r = parse_argv(argc, argv); if (r <= 0) return r; if (arg_console && !arg_device) /* * Spawn a separate process for each console device. */ return ask_on_consoles(argv); if (arg_device) { /* * Later on, a controlling terminal will be acquired, * therefore the current process has to become a session * leader and should not have a controlling terminal already. */ (void) setsid(); (void) release_terminal(); } return process_and_watch_password_files(!IN_SET(arg_action, ACTION_QUERY, ACTION_LIST)); } DEFINE_MAIN_FUNCTION(run);
23,489
32.037975
122
c
null
systemd-main/src/udev/fuzz-udev-rule-parse-value.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <string.h> #include "alloc-util.h" #include "fuzz.h" #include "udev-util.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_free_ char *str = NULL; int r; char *value = UINT_TO_PTR(0x12345678U); char *endpos = UINT_TO_PTR(0x87654321U); assert_se(str = malloc(size + 1)); memcpy(str, data, size); str[size] = '\0'; r = udev_rule_parse_value(str, &value, &endpos); if (r < 0) { /* not modified on failure */ assert_se(value == UINT_TO_PTR(0x12345678U)); assert_se(endpos == UINT_TO_PTR(0x87654321U)); } else { assert_se(endpos <= str + size); assert_se(endpos > str + 1); } return 0; }
849
25.5625
62
c
null
systemd-main/src/udev/fuzz-udev-rules.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <stdio.h> #include "fd-util.h" #include "fs-util.h" #include "fuzz.h" #include "tests.h" #include "tmpfile-util.h" #include "udev-rules.h" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { _cleanup_(udev_rules_freep) UdevRules *rules = NULL; _cleanup_fclose_ FILE *f = NULL; _cleanup_(unlink_tempfilep) char filename[] = "/tmp/fuzz-udev-rules.XXXXXX"; int r; if (outside_size_range(size, 0, 65536)) return 0; 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(rules = udev_rules_new(RESOLVE_NAME_EARLY)); r = udev_rules_parse_file(rules, filename, /* extra_checks = */ false, NULL); log_info_errno(r, "Parsing %s: %m", filename); assert_se(r >= 0 || /* OK */ r == -ENOBUFS); /* line length exceeded */ return 0; }
1,131
29.594595
85
c
null
systemd-main/src/udev/test-udev-builtin.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "tests.h" #include "udev-builtin.h" TEST(udev_builtin_cmd_to_ptr) { /* Those could have been static asserts, but ({}) is not allowed there. */ #if HAVE_BLKID assert_se(UDEV_BUILTIN_CMD_TO_PTR(UDEV_BUILTIN_BLKID)); assert_se(PTR_TO_UDEV_BUILTIN_CMD(UDEV_BUILTIN_CMD_TO_PTR(UDEV_BUILTIN_BLKID)) == UDEV_BUILTIN_BLKID); #endif assert_se(UDEV_BUILTIN_CMD_TO_PTR(UDEV_BUILTIN_BTRFS)); assert_se(PTR_TO_UDEV_BUILTIN_CMD(UDEV_BUILTIN_CMD_TO_PTR(UDEV_BUILTIN_BTRFS)) == UDEV_BUILTIN_BTRFS); assert_se(PTR_TO_UDEV_BUILTIN_CMD(UDEV_BUILTIN_CMD_TO_PTR(_UDEV_BUILTIN_INVALID)) == _UDEV_BUILTIN_INVALID); assert_se(PTR_TO_UDEV_BUILTIN_CMD(NULL) == _UDEV_BUILTIN_INVALID); assert_se(PTR_TO_UDEV_BUILTIN_CMD((void*) 10000) == _UDEV_BUILTIN_INVALID); } DEFINE_TEST_MAIN(LOG_DEBUG);
892
41.52381
116
c
null
systemd-main/src/udev/test-udev-event.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "path-util.h" #include "signal-util.h" #include "strv.h" #include "tests.h" #include "udev-event.h" #define BUF_SIZE 1024 static void test_event_spawn_core(bool with_pidfd, const char *cmd, char *result_buf, size_t buf_size) { _cleanup_(sd_device_unrefp) sd_device *dev = NULL; _cleanup_(udev_event_freep) UdevEvent *event = NULL; assert_se(setenv("SYSTEMD_PIDFD", yes_no(with_pidfd), 1) >= 0); assert_se(sd_device_new_from_syspath(&dev, "/sys/class/net/lo") >= 0); assert_se(event = udev_event_new(dev, 0, NULL, LOG_DEBUG)); assert_se(udev_event_spawn(event, 5 * USEC_PER_SEC, SIGKILL, false, cmd, result_buf, buf_size, NULL) == 0); assert_se(unsetenv("SYSTEMD_PIDFD") >= 0); } static void test_event_spawn_cat(bool with_pidfd, size_t buf_size) { _cleanup_strv_free_ char **lines = NULL; _cleanup_free_ char *cmd = NULL; char result_buf[BUF_SIZE]; log_debug("/* %s(%s) */", __func__, yes_no(with_pidfd)); assert_se(find_executable("cat", &cmd) >= 0); assert_se(strextend_with_separator(&cmd, " ", "/sys/class/net/lo/uevent")); test_event_spawn_core(with_pidfd, cmd, result_buf, buf_size >= BUF_SIZE ? BUF_SIZE : buf_size); assert_se(lines = strv_split_newlines(result_buf)); strv_print(lines); if (buf_size >= BUF_SIZE) { assert_se(strv_contains(lines, "INTERFACE=lo")); assert_se(strv_contains(lines, "IFINDEX=1")); } } static void test_event_spawn_self(const char *self, const char *arg, bool with_pidfd) { _cleanup_strv_free_ char **lines = NULL; _cleanup_free_ char *cmd = NULL; char result_buf[BUF_SIZE]; log_debug("/* %s(%s, %s) */", __func__, arg, yes_no(with_pidfd)); assert_se(cmd = strjoin(self, " ", arg)); test_event_spawn_core(with_pidfd, cmd, result_buf, BUF_SIZE); assert_se(lines = strv_split_newlines(result_buf)); strv_print(lines); assert_se(strv_contains(lines, "aaa")); assert_se(strv_contains(lines, "bbb")); } static void test1(void) { fprintf(stdout, "aaa\nbbb"); fprintf(stderr, "ccc\nddd"); } static void test2(void) { char buf[16384]; fprintf(stdout, "aaa\nbbb"); memset(buf, 'a', sizeof(buf) - 1); char_array_0(buf); fputs(buf, stderr); } int main(int argc, char *argv[]) { _cleanup_free_ char *self = NULL; if (argc > 1) { if (streq(argv[1], "test1")) test1(); else if (streq(argv[1], "test2")) test2(); else assert_not_reached(); return 0; } test_setup_logging(LOG_DEBUG); assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGCHLD, -1) >= 0); test_event_spawn_cat(true, SIZE_MAX); test_event_spawn_cat(false, SIZE_MAX); test_event_spawn_cat(true, 5); test_event_spawn_cat(false, 5); assert_se(path_make_absolute_cwd(argv[0], &self) >= 0); path_simplify(self); test_event_spawn_self(self, "test1", true); test_event_spawn_self(self, "test1", false); test_event_spawn_self(self, "test2", true); test_event_spawn_self(self, "test2", false); return 0; }
3,471
29.725664
115
c
null
systemd-main/src/udev/udev-builtin-btrfs.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <fcntl.h> #include <linux/btrfs.h> #include <stdlib.h> #include <sys/ioctl.h> #include "device-util.h" #include "errno-util.h" #include "fd-util.h" #include "string-util.h" #include "strxcpyx.h" #include "udev-builtin.h" static int builtin_btrfs(UdevEvent *event, int argc, char *argv[], bool test) { sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev); struct btrfs_ioctl_vol_args args = {}; _cleanup_close_ int fd = -EBADF; int r; if (argc != 3 || !streq(argv[1], "ready")) return log_device_error_errno(dev, SYNTHETIC_ERRNO(EINVAL), "Invalid arguments"); fd = open("/dev/btrfs-control", O_RDWR|O_CLOEXEC|O_NOCTTY); if (fd < 0) { if (ERRNO_IS_DEVICE_ABSENT(errno)) { /* Driver not installed? Then we aren't ready. This is useful in initrds that lack * btrfs.ko. After the host transition (where btrfs.ko will hopefully become * available) the device can be retriggered and will then be considered ready. */ udev_builtin_add_property(dev, test, "ID_BTRFS_READY", "0"); return 0; } return log_device_debug_errno(dev, errno, "Failed to open /dev/btrfs-control: %m"); } strscpy(args.name, sizeof(args.name), argv[2]); r = ioctl(fd, BTRFS_IOC_DEVICES_READY, &args); if (r < 0) return log_device_debug_errno(dev, errno, "Failed to call BTRFS_IOC_DEVICES_READY: %m"); udev_builtin_add_property(dev, test, "ID_BTRFS_READY", one_zero(r == 0)); return 0; } const UdevBuiltin udev_builtin_btrfs = { .name = "btrfs", .cmd = builtin_btrfs, .help = "btrfs volume management", };
1,864
35.568627
106
c
null
systemd-main/src/udev/udev-builtin-hwdb.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <fnmatch.h> #include <getopt.h> #include <stdio.h> #include <stdlib.h> #include "sd-hwdb.h" #include "alloc-util.h" #include "device-util.h" #include "hwdb-util.h" #include "parse-util.h" #include "string-util.h" #include "udev-builtin.h" static sd_hwdb *hwdb; int udev_builtin_hwdb_lookup(sd_device *dev, const char *prefix, const char *modalias, const char *filter, bool test) { _cleanup_free_ char *lookup = NULL; const char *key, *value; int n = 0, r; if (!hwdb) return -ENOENT; if (prefix) { lookup = strjoin(prefix, modalias); if (!lookup) return -ENOMEM; modalias = lookup; } SD_HWDB_FOREACH_PROPERTY(hwdb, modalias, key, value) { if (filter && fnmatch(filter, key, FNM_NOESCAPE) != 0) continue; r = udev_builtin_add_property(dev, test, key, value); if (r < 0) return r; n++; } return n; } static const char *modalias_usb(sd_device *dev, char *s, size_t size) { const char *v, *p, *n = NULL; uint16_t vn, pn; if (sd_device_get_sysattr_value(dev, "idVendor", &v) < 0) return NULL; if (sd_device_get_sysattr_value(dev, "idProduct", &p) < 0) return NULL; if (safe_atoux16(v, &vn) < 0) return NULL; if (safe_atoux16(p, &pn) < 0) return NULL; (void) sd_device_get_sysattr_value(dev, "product", &n); (void) snprintf(s, size, "usb:v%04Xp%04X:%s", vn, pn, strempty(n)); return s; } static int udev_builtin_hwdb_search(sd_device *dev, sd_device *srcdev, const char *subsystem, const char *prefix, const char *filter, bool test) { char s[LINE_MAX]; bool last = false; int r = 0; assert(dev); if (!srcdev) srcdev = dev; for (sd_device *d = srcdev; d; ) { const char *dsubsys, *devtype, *modalias = NULL; if (sd_device_get_subsystem(d, &dsubsys) < 0) goto next; /* look only at devices of a specific subsystem */ if (subsystem && !streq(dsubsys, subsystem)) goto next; (void) sd_device_get_property_value(d, "MODALIAS", &modalias); if (streq(dsubsys, "usb") && sd_device_get_devtype(d, &devtype) >= 0 && streq(devtype, "usb_device")) { /* if the usb_device does not have a modalias, compose one */ if (!modalias) modalias = modalias_usb(d, s, sizeof(s)); /* avoid looking at any parent device, they are usually just a USB hub */ last = true; } if (!modalias) goto next; log_device_debug(dev, "hwdb modalias key: \"%s\"", modalias); r = udev_builtin_hwdb_lookup(dev, prefix, modalias, filter, test); if (r > 0) break; if (last) break; next: if (sd_device_get_parent(d, &d) < 0) break; } return r; } static int builtin_hwdb(UdevEvent *event, int argc, char *argv[], bool test) { static const struct option options[] = { { "filter", required_argument, NULL, 'f' }, { "device", required_argument, NULL, 'd' }, { "subsystem", required_argument, NULL, 's' }, { "lookup-prefix", required_argument, NULL, 'p' }, {} }; const char *filter = NULL; const char *device = NULL; const char *subsystem = NULL; const char *prefix = NULL; _cleanup_(sd_device_unrefp) sd_device *srcdev = NULL; sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev); int r; if (!hwdb) return -EINVAL; for (;;) { int option; option = getopt_long(argc, argv, "f:d:s:p:", options, NULL); if (option == -1) break; switch (option) { case 'f': filter = optarg; break; case 'd': device = optarg; break; case 's': subsystem = optarg; break; case 'p': prefix = optarg; break; } } /* query a specific key given as argument */ if (argv[optind]) { r = udev_builtin_hwdb_lookup(dev, prefix, argv[optind], filter, test); if (r < 0) return log_device_debug_errno(dev, r, "Failed to look up hwdb: %m"); if (r == 0) return log_device_debug_errno(dev, SYNTHETIC_ERRNO(ENODATA), "No entry found from hwdb."); return r; } /* read data from another device than the device we will store the data */ if (device) { r = sd_device_new_from_device_id(&srcdev, device); if (r < 0) return log_device_debug_errno(dev, r, "Failed to create sd_device object '%s': %m", device); } r = udev_builtin_hwdb_search(dev, srcdev, subsystem, prefix, filter, test); if (r < 0) return log_device_debug_errno(dev, r, "Failed to look up hwdb: %m"); if (r == 0) return log_device_debug_errno(dev, SYNTHETIC_ERRNO(ENODATA), "No entry found from hwdb."); return r; } /* called at udev startup and reload */ static int builtin_hwdb_init(void) { int r; if (hwdb) return 0; r = sd_hwdb_new(&hwdb); if (r < 0) return r; return 0; } /* called on udev shutdown and reload request */ static void builtin_hwdb_exit(void) { hwdb = sd_hwdb_unref(hwdb); } /* called every couple of seconds during event activity; 'true' if config has changed */ static bool builtin_hwdb_should_reload(void) { if (hwdb_should_reload(hwdb)) { log_debug("hwdb needs reloading."); return true; } return false; } const UdevBuiltin udev_builtin_hwdb = { .name = "hwdb", .cmd = builtin_hwdb, .init = builtin_hwdb_init, .exit = builtin_hwdb_exit, .should_reload = builtin_hwdb_should_reload, .help = "Hardware database", };
7,072
30.02193
116
c
null
systemd-main/src/udev/udev-builtin-input_id.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * expose input properties via udev * * Portions Copyright Β© 2004 David Zeuthen, <[email protected]> * Copyright Β© 2014 Carlos Garnacho <[email protected]> */ #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <unistd.h> #include <linux/limits.h> #include "device-util.h" #include "fd-util.h" #include "missing_input.h" #include "parse-util.h" #include "stdio-util.h" #include "string-util.h" #include "udev-builtin.h" /* we must use this kernel-compatible implementation */ #define BITS_PER_LONG (sizeof(unsigned long) * 8) #define NBITS(x) ((((x)-1)/BITS_PER_LONG)+1) #define OFF(x) ((x)%BITS_PER_LONG) #define BIT(x) (1UL<<OFF(x)) #define LONG(x) ((x)/BITS_PER_LONG) #define test_bit(bit, array) ((array[LONG(bit)] >> OFF(bit)) & 1) struct range { unsigned start; unsigned end; }; /* key code ranges above BTN_MISC (start is inclusive, stop is exclusive) */ static const struct range high_key_blocks[] = { { KEY_OK, BTN_DPAD_UP }, { KEY_ALS_TOGGLE, BTN_TRIGGER_HAPPY } }; static int abs_size_mm(const struct input_absinfo *absinfo) { /* Resolution is defined to be in units/mm for ABS_X/Y */ return (absinfo->maximum - absinfo->minimum) / absinfo->resolution; } static void extract_info(sd_device *dev, bool test) { char width[DECIMAL_STR_MAX(int)], height[DECIMAL_STR_MAX(int)]; struct input_absinfo xabsinfo = {}, yabsinfo = {}; _cleanup_close_ int fd = -EBADF; fd = sd_device_open(dev, O_RDONLY|O_CLOEXEC|O_NONBLOCK|O_NOCTTY); if (fd < 0) return; if (ioctl(fd, EVIOCGABS(ABS_X), &xabsinfo) < 0 || ioctl(fd, EVIOCGABS(ABS_Y), &yabsinfo) < 0) return; if (xabsinfo.resolution <= 0 || yabsinfo.resolution <= 0) return; xsprintf(width, "%d", abs_size_mm(&xabsinfo)); xsprintf(height, "%d", abs_size_mm(&yabsinfo)); udev_builtin_add_property(dev, test, "ID_INPUT_WIDTH_MM", width); udev_builtin_add_property(dev, test, "ID_INPUT_HEIGHT_MM", height); } /* * Read a capability attribute and return bitmask. * @param dev sd_device * @param attr sysfs attribute name (e. g. "capabilities/key") * @param bitmask: Output array which has a sizeof of bitmask_size */ static void get_cap_mask(sd_device *pdev, const char* attr, unsigned long *bitmask, size_t bitmask_size, bool test) { const char *v; char text[4096]; unsigned i; char* word; unsigned long val; int r; if (sd_device_get_sysattr_value(pdev, attr, &v) < 0) v = ""; xsprintf(text, "%s", v); log_device_debug(pdev, "%s raw kernel attribute: %s", attr, text); memzero(bitmask, bitmask_size); i = 0; while ((word = strrchr(text, ' '))) { r = safe_atolu_full(word+1, 16, &val); if (r < 0) log_device_debug_errno(pdev, r, "Ignoring %s block which failed to parse: %m", attr); else if (i < bitmask_size / sizeof(unsigned long)) bitmask[i] = val; else log_device_debug(pdev, "Ignoring %s block %lX which is larger than maximum size", attr, val); *word = '\0'; i++; } r = safe_atolu_full(text, 16, &val); if (r < 0) log_device_debug_errno(pdev, r, "Ignoring %s block which failed to parse: %m", attr); else if (i < bitmask_size / sizeof(unsigned long)) bitmask[i] = val; else log_device_debug(pdev, "Ignoring %s block %lX which is larger than maximum size", attr, val); if (test && DEBUG_LOGGING) { log_device_debug(pdev, "%s decoded bit map:", attr); val = bitmask_size / sizeof (unsigned long); /* skip trailing zeros */ while (bitmask[val-1] == 0 && val > 0) --val; /* IN_SET() cannot be used in assert_cc(). */ assert_cc(sizeof(unsigned long) == 4 || sizeof(unsigned long) == 8); for (unsigned long j = 0; j < val; j++) log_device_debug(pdev, sizeof(unsigned long) == 4 ? " bit %4lu: %08lX\n" : " bit %4lu: %016lX\n", j * BITS_PER_LONG, bitmask[j]); } } static struct input_id get_input_id(sd_device *dev) { const char *v; struct input_id id = {}; if (sd_device_get_sysattr_value(dev, "id/bustype", &v) >= 0) (void) safe_atoux16(v, &id.bustype); if (sd_device_get_sysattr_value(dev, "id/vendor", &v) >= 0) (void) safe_atoux16(v, &id.vendor); if (sd_device_get_sysattr_value(dev, "id/product", &v) >= 0) (void) safe_atoux16(v, &id.product); if (sd_device_get_sysattr_value(dev, "id/version", &v) >= 0) (void) safe_atoux16(v, &id.version); return id; } /* pointer devices */ static bool test_pointers(sd_device *dev, const struct input_id *id, const unsigned long* bitmask_ev, const unsigned long* bitmask_abs, const unsigned long* bitmask_key, const unsigned long* bitmask_rel, const unsigned long* bitmask_props, bool test) { bool has_abs_coordinates = false; bool has_rel_coordinates = false; bool has_mt_coordinates = false; size_t num_joystick_axes = 0; size_t num_joystick_buttons = 0; bool has_pad_buttons = false; bool is_direct = false; bool has_touch = false; bool has_3d_coordinates = false; bool has_keys = false; bool has_stylus = false; bool has_pen = false; bool finger_but_no_pen = false; bool has_mouse_button = false; bool is_mouse = false; bool is_abs_mouse = false; bool is_touchpad = false; bool is_touchscreen = false; bool is_tablet = false; bool is_tablet_pad = false; bool is_joystick = false; bool is_accelerometer = false; bool is_pointing_stick = false; bool has_wheel = false; has_keys = test_bit(EV_KEY, bitmask_ev); has_abs_coordinates = test_bit(ABS_X, bitmask_abs) && test_bit(ABS_Y, bitmask_abs); has_3d_coordinates = has_abs_coordinates && test_bit(ABS_Z, bitmask_abs); is_accelerometer = test_bit(INPUT_PROP_ACCELEROMETER, bitmask_props); if (!has_keys && has_3d_coordinates) is_accelerometer = true; if (is_accelerometer) { udev_builtin_add_property(dev, test, "ID_INPUT_ACCELEROMETER", "1"); return true; } is_pointing_stick = test_bit(INPUT_PROP_POINTING_STICK, bitmask_props); has_stylus = test_bit(BTN_STYLUS, bitmask_key); has_pen = test_bit(BTN_TOOL_PEN, bitmask_key); finger_but_no_pen = test_bit(BTN_TOOL_FINGER, bitmask_key) && !test_bit(BTN_TOOL_PEN, bitmask_key); for (int button = BTN_MOUSE; button < BTN_JOYSTICK && !has_mouse_button; button++) has_mouse_button = test_bit(button, bitmask_key); has_rel_coordinates = test_bit(EV_REL, bitmask_ev) && test_bit(REL_X, bitmask_rel) && test_bit(REL_Y, bitmask_rel); has_mt_coordinates = test_bit(ABS_MT_POSITION_X, bitmask_abs) && test_bit(ABS_MT_POSITION_Y, bitmask_abs); /* unset has_mt_coordinates if devices claims to have all abs axis */ if (has_mt_coordinates && test_bit(ABS_MT_SLOT, bitmask_abs) && test_bit(ABS_MT_SLOT - 1, bitmask_abs)) has_mt_coordinates = false; is_direct = test_bit(INPUT_PROP_DIRECT, bitmask_props); has_touch = test_bit(BTN_TOUCH, bitmask_key); has_pad_buttons = test_bit(BTN_0, bitmask_key) && test_bit(BTN_1, bitmask_key) && !has_pen; has_wheel = test_bit(EV_REL, bitmask_ev) && (test_bit(REL_WHEEL, bitmask_rel) || test_bit(REL_HWHEEL, bitmask_rel)); /* joysticks don't necessarily have buttons; e. g. * rudders/pedals are joystick-like, but buttonless; they have * other fancy axes. Others have buttons only but no axes. * * The BTN_JOYSTICK range starts after the mouse range, so a mouse * with more than 16 buttons runs into the joystick range (e.g. Mad * Catz Mad Catz M.M.O.TE). Skip those. */ if (!test_bit(BTN_JOYSTICK - 1, bitmask_key)) { for (int button = BTN_JOYSTICK; button < BTN_DIGI; button++) if (test_bit(button, bitmask_key)) num_joystick_buttons++; for (int button = BTN_TRIGGER_HAPPY1; button <= BTN_TRIGGER_HAPPY40; button++) if (test_bit(button, bitmask_key)) num_joystick_buttons++; for (int button = BTN_DPAD_UP; button <= BTN_DPAD_RIGHT; button++) if (test_bit(button, bitmask_key)) num_joystick_buttons++; } for (int axis = ABS_RX; axis < ABS_PRESSURE; axis++) if (test_bit(axis, bitmask_abs)) num_joystick_axes++; if (has_abs_coordinates) { if (has_stylus || has_pen) is_tablet = true; else if (finger_but_no_pen && !is_direct) is_touchpad = true; else if (has_mouse_button) /* This path is taken by VMware's USB mouse, which has * absolute axes, but no touch/pressure button. */ is_abs_mouse = true; else if (has_touch || is_direct) is_touchscreen = true; else if (num_joystick_buttons > 0 || num_joystick_axes > 0) is_joystick = true; } else if (num_joystick_buttons > 0 || num_joystick_axes > 0) is_joystick = true; if (has_mt_coordinates) { if (has_stylus || has_pen) is_tablet = true; else if (finger_but_no_pen && !is_direct) is_touchpad = true; else if (has_touch || is_direct) is_touchscreen = true; } if (is_tablet && has_pad_buttons) is_tablet_pad = true; if (has_pad_buttons && has_wheel && !has_rel_coordinates) { is_tablet = true; is_tablet_pad = true; } if (!is_tablet && !is_touchpad && !is_joystick && has_mouse_button && (has_rel_coordinates || !has_abs_coordinates)) /* mouse buttons and no axis */ is_mouse = true; /* There is no such thing as an i2c mouse */ if (is_mouse && id->bustype == BUS_I2C) is_pointing_stick = true; /* Joystick un-detection. Some keyboards have random joystick buttons * set. Avoid those being labeled as ID_INPUT_JOYSTICK with some heuristics. * The well-known keys represent a (randomly picked) set of key groups. * A joystick may have one of those but probably not several. And a joystick with less than 2 buttons * or axes is not a joystick either. * libinput uses similar heuristics, any changes here should be added to libinput too. */ if (is_joystick) { static const unsigned int well_known_keyboard_keys[] = { KEY_LEFTCTRL, KEY_CAPSLOCK, KEY_NUMLOCK, KEY_INSERT, KEY_MUTE, KEY_CALC, KEY_FILE, KEY_MAIL, KEY_PLAYPAUSE, KEY_BRIGHTNESSDOWN, }; size_t num_well_known_keys = 0; if (has_keys) for (size_t i = 0; i < ELEMENTSOF(well_known_keyboard_keys); i++) if (test_bit(well_known_keyboard_keys[i], bitmask_key)) num_well_known_keys++; if (num_well_known_keys >= 4 || num_joystick_buttons + num_joystick_axes < 2) { log_device_debug(dev, "Input device has %zu joystick buttons and %zu axes but also %zu keyboard key sets, " "assuming this is a keyboard, not a joystick.", num_joystick_buttons, num_joystick_axes, num_well_known_keys); is_joystick = false; } if (has_wheel && has_pad_buttons) { log_device_debug(dev, "Input device has %zu joystick buttons as well as tablet pad buttons, " "assuming this is a tablet pad, not a joystick.", num_joystick_buttons); is_joystick = false; } } if (is_pointing_stick) udev_builtin_add_property(dev, test, "ID_INPUT_POINTINGSTICK", "1"); if (is_mouse || is_abs_mouse) udev_builtin_add_property(dev, test, "ID_INPUT_MOUSE", "1"); if (is_touchpad) udev_builtin_add_property(dev, test, "ID_INPUT_TOUCHPAD", "1"); if (is_touchscreen) udev_builtin_add_property(dev, test, "ID_INPUT_TOUCHSCREEN", "1"); if (is_joystick) udev_builtin_add_property(dev, test, "ID_INPUT_JOYSTICK", "1"); if (is_tablet) udev_builtin_add_property(dev, test, "ID_INPUT_TABLET", "1"); if (is_tablet_pad) udev_builtin_add_property(dev, test, "ID_INPUT_TABLET_PAD", "1"); return is_tablet || is_mouse || is_abs_mouse || is_touchpad || is_touchscreen || is_joystick || is_pointing_stick; } /* key like devices */ static bool test_key(sd_device *dev, const unsigned long* bitmask_ev, const unsigned long* bitmask_key, bool test) { bool found = false; /* do we have any KEY_* capability? */ if (!test_bit(EV_KEY, bitmask_ev)) { log_device_debug(dev, "test_key: no EV_KEY capability"); return false; } /* only consider KEY_* here, not BTN_* */ for (size_t i = 0; i < BTN_MISC/BITS_PER_LONG && !found; i++) { if (bitmask_key[i]) found = true; log_device_debug(dev, "test_key: checking bit block %zu for any keys; found=%s", i * BITS_PER_LONG, yes_no(found)); } /* If there are no keys in the lower block, check the higher blocks */ for (size_t block = 0; block < sizeof(high_key_blocks) / sizeof(struct range) && !found; block++) for (unsigned i = high_key_blocks[block].start; i < high_key_blocks[block].end && !found; i++) if (test_bit(i, bitmask_key)) { log_device_debug(dev, "test_key: Found key %x in high block", i); found = true; } if (found) udev_builtin_add_property(dev, test, "ID_INPUT_KEY", "1"); /* the first 32 bits are ESC, numbers, and Q to D; if we have all of * those, consider it a full keyboard; do not test KEY_RESERVED, though */ if (FLAGS_SET(bitmask_key[0], 0xFFFFFFFE)) { udev_builtin_add_property(dev, test, "ID_INPUT_KEYBOARD", "1"); return true; } return found; } static int builtin_input_id(UdevEvent *event, int argc, char *argv[], bool test) { sd_device *pdev, *dev = ASSERT_PTR(ASSERT_PTR(event)->dev); unsigned long bitmask_ev[NBITS(EV_MAX)]; unsigned long bitmask_abs[NBITS(ABS_MAX)]; unsigned long bitmask_key[NBITS(KEY_MAX)]; unsigned long bitmask_rel[NBITS(REL_MAX)]; unsigned long bitmask_props[NBITS(INPUT_PROP_MAX)]; const char *sysname; bool is_pointer; bool is_key; /* walk up the parental chain until we find the real input device; the * argument is very likely a subdevice of this, like eventN */ for (pdev = dev; pdev; ) { const char *s; if (sd_device_get_sysattr_value(pdev, "capabilities/ev", &s) >= 0) break; if (sd_device_get_parent_with_subsystem_devtype(pdev, "input", NULL, &pdev) >= 0) continue; pdev = NULL; break; } if (pdev) { struct input_id id = get_input_id(pdev); /* Use this as a flag that input devices were detected, so that this * program doesn't need to be called more than once per device */ udev_builtin_add_property(dev, test, "ID_INPUT", "1"); get_cap_mask(pdev, "capabilities/ev", bitmask_ev, sizeof(bitmask_ev), test); get_cap_mask(pdev, "capabilities/abs", bitmask_abs, sizeof(bitmask_abs), test); get_cap_mask(pdev, "capabilities/rel", bitmask_rel, sizeof(bitmask_rel), test); get_cap_mask(pdev, "capabilities/key", bitmask_key, sizeof(bitmask_key), test); get_cap_mask(pdev, "properties", bitmask_props, sizeof(bitmask_props), test); is_pointer = test_pointers(dev, &id, bitmask_ev, bitmask_abs, bitmask_key, bitmask_rel, bitmask_props, test); is_key = test_key(dev, bitmask_ev, bitmask_key, test); /* Some evdev nodes have only a scrollwheel */ if (!is_pointer && !is_key && test_bit(EV_REL, bitmask_ev) && (test_bit(REL_WHEEL, bitmask_rel) || test_bit(REL_HWHEEL, bitmask_rel))) udev_builtin_add_property(dev, test, "ID_INPUT_KEY", "1"); if (test_bit(EV_SW, bitmask_ev)) udev_builtin_add_property(dev, test, "ID_INPUT_SWITCH", "1"); } if (sd_device_get_sysname(dev, &sysname) >= 0 && startswith(sysname, "event")) extract_info(dev, test); return 0; } const UdevBuiltin udev_builtin_input_id = { .name = "input_id", .cmd = builtin_input_id, .help = "Input device properties", };
18,835
42.400922
131
c
null
systemd-main/src/udev/udev-builtin-net_setup_link.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include "alloc-util.h" #include "device-util.h" #include "escape.h" #include "errno-util.h" #include "link-config.h" #include "log.h" #include "string-util.h" #include "strv.h" #include "udev-builtin.h" static LinkConfigContext *ctx = NULL; static int builtin_net_setup_link(UdevEvent *event, int argc, char **argv, bool test) { sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev); _cleanup_(link_freep) Link *link = NULL; _cleanup_free_ char *joined = NULL; int r; if (argc > 1) return log_device_error_errno(dev, SYNTHETIC_ERRNO(EINVAL), "This program takes no arguments."); r = link_new(ctx, &event->rtnl, dev, &link); if (r == -ENODEV) { log_device_debug_errno(dev, r, "Link vanished while getting information, ignoring."); return 0; } if (r < 0) return log_device_warning_errno(dev, r, "Failed to get link information: %m"); if (link->driver) udev_builtin_add_property(dev, test, "ID_NET_DRIVER", link->driver); r = link_get_config(ctx, link); if (r < 0) { if (r == -ENOENT) { log_device_debug_errno(dev, r, "No matching link configuration found, ignoring device."); return 0; } return log_device_error_errno(dev, r, "Failed to get link config: %m"); } r = link_apply_config(ctx, &event->rtnl, link); if (r == -ENODEV) log_device_debug_errno(dev, r, "Link vanished while applying configuration, ignoring."); else if (r < 0) log_device_warning_errno(dev, r, "Could not apply link configuration, ignoring: %m"); udev_builtin_add_property(dev, test, "ID_NET_LINK_FILE", link->config->filename); if (link->new_name) udev_builtin_add_property(dev, test, "ID_NET_NAME", link->new_name); event->altnames = TAKE_PTR(link->altnames); STRV_FOREACH(d, link->config->dropins) { _cleanup_free_ char *escaped = NULL; escaped = xescape(*d, ":"); if (!escaped) return log_oom(); if (!strextend_with_separator(&joined, ":", escaped)) return log_oom(); } udev_builtin_add_property(dev, test, "ID_NET_LINK_FILE_DROPINS", joined); return 0; } static int builtin_net_setup_link_init(void) { int r; if (ctx) return 0; r = link_config_ctx_new(&ctx); if (r < 0) return r; r = link_config_load(ctx); if (r < 0) return r; log_debug("Created link configuration context."); return 0; } static void builtin_net_setup_link_exit(void) { ctx = link_config_ctx_free(ctx); log_debug("Unloaded link configuration context."); } static bool builtin_net_setup_link_should_reload(void) { if (!ctx) return false; if (link_config_should_reload(ctx)) { log_debug("Link configuration context needs reloading."); return true; } return false; } const UdevBuiltin udev_builtin_net_setup_link = { .name = "net_setup_link", .cmd = builtin_net_setup_link, .init = builtin_net_setup_link_init, .exit = builtin_net_setup_link_exit, .should_reload = builtin_net_setup_link_should_reload, .help = "Configure network link", .run_once = false, };
3,657
30.264957
113
c
null
systemd-main/src/udev/udev-builtin-uaccess.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * manage device node user ACL */ #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> #include "sd-login.h" #include "device-util.h" #include "devnode-acl.h" #include "login-util.h" #include "log.h" #include "udev-builtin.h" static int builtin_uaccess(UdevEvent *event, int argc, char *argv[], bool test) { sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev); const char *path = NULL, *seat; bool changed_acl = false; uid_t uid; int r; umask(0022); /* don't muck around with ACLs when the system is not running systemd */ if (!logind_running()) return 0; r = sd_device_get_devname(dev, &path); if (r < 0) { log_device_error_errno(dev, r, "Failed to get device name: %m"); goto finish; } if (sd_device_get_property_value(dev, "ID_SEAT", &seat) < 0) seat = "seat0"; r = sd_seat_get_active(seat, NULL, &uid); if (r < 0) { if (IN_SET(r, -ENXIO, -ENODATA)) /* No active session on this seat */ r = 0; else log_device_error_errno(dev, r, "Failed to determine active user on seat %s: %m", seat); goto finish; } r = devnode_acl(path, true, false, 0, true, uid); if (r < 0) { log_device_full_errno(dev, r == -ENOENT ? LOG_DEBUG : LOG_ERR, r, "Failed to apply ACL: %m"); goto finish; } changed_acl = true; r = 0; finish: if (path && !changed_acl) { int k; /* Better be safe than sorry and reset ACL */ k = devnode_acl(path, true, false, 0, false, 0); if (k < 0) { log_device_full_errno(dev, k == -ENOENT ? LOG_DEBUG : LOG_ERR, k, "Failed to apply ACL: %m"); if (r >= 0) r = k; } } return r; } const UdevBuiltin udev_builtin_uaccess = { .name = "uaccess", .cmd = builtin_uaccess, .help = "Manage device node user ACL", };
2,291
26.95122
117
c
null
systemd-main/src/udev/udev-builtin-usb_id.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * USB device properties and persistent device path * * Copyright (c) 2005 SUSE Linux Products GmbH, Germany * Author: Hannes Reinecke <[email protected]> */ #include <ctype.h> #include <errno.h> #include <fcntl.h> #include <stdarg.h> #include <stdio.h> #include <unistd.h> #include "alloc-util.h" #include "device-nodes.h" #include "device-util.h" #include "fd-util.h" #include "parse-util.h" #include "string-util.h" #include "strxcpyx.h" #include "udev-builtin.h" #include "udev-util.h" static void set_usb_iftype(char *to, int if_class_num, size_t len) { const char *type = "generic"; switch (if_class_num) { case 1: type = "audio"; break; case 2: /* CDC-Control */ break; case 3: type = "hid"; break; case 5: /* Physical */ break; case 6: type = "media"; break; case 7: type = "printer"; break; case 8: type = "storage"; break; case 9: type = "hub"; break; case 0x0a: /* CDC-Data */ break; case 0x0b: /* Chip/Smart Card */ break; case 0x0d: /* Content Security */ break; case 0x0e: type = "video"; break; case 0xdc: /* Diagnostic Device */ break; case 0xe0: /* Wireless Controller */ break; case 0xfe: /* Application-specific */ break; case 0xff: /* Vendor-specific */ break; default: break; } strncpy(to, type, len); to[len-1] = '\0'; } static int set_usb_mass_storage_ifsubtype(char *to, const char *from, size_t len) { int type_num = 0; const char *type = "generic"; if (safe_atoi(from, &type_num) >= 0) { switch (type_num) { case 1: /* RBC devices */ type = "rbc"; break; case 2: type = "atapi"; break; case 3: type = "tape"; break; case 4: /* UFI */ type = "floppy"; break; case 6: /* Transparent SPC-2 devices */ type = "scsi"; break; default: break; } } strscpy(to, len, type); return type_num; } static void set_scsi_type(char *to, const char *from, size_t len) { unsigned type_num; const char *type = "generic"; if (safe_atou(from, &type_num) >= 0) { switch (type_num) { case 0: case 0xe: type = "disk"; break; case 1: type = "tape"; break; case 4: case 7: case 0xf: type = "optical"; break; case 5: type = "cd"; break; default: break; } } strscpy(to, len, type); } #define USB_DT_DEVICE 0x01 #define USB_DT_INTERFACE 0x04 static int dev_if_packed_info(sd_device *dev, char *ifs_str, size_t len) { _cleanup_close_ int fd = -EBADF; ssize_t size; unsigned char buf[18 + 65535]; size_t pos = 0; unsigned strpos = 0; const char *filename, *syspath; int r; struct usb_interface_descriptor { uint8_t bLength; uint8_t bDescriptorType; uint8_t bInterfaceNumber; uint8_t bAlternateSetting; uint8_t bNumEndpoints; uint8_t bInterfaceClass; uint8_t bInterfaceSubClass; uint8_t bInterfaceProtocol; uint8_t iInterface; } _packed_; r = sd_device_get_syspath(dev, &syspath); if (r < 0) return r; filename = strjoina(syspath, "/descriptors"); fd = open(filename, O_RDONLY|O_CLOEXEC|O_NOCTTY); if (fd < 0) return log_device_debug_errno(dev, errno, "Failed to open \"%s\": %m", filename); size = read(fd, buf, sizeof(buf)); if (size < 18) return log_device_warning_errno(dev, SYNTHETIC_ERRNO(EIO), "Short read from \"%s\"", filename); assert((size_t) size <= sizeof buf); ifs_str[0] = '\0'; while (pos + sizeof(struct usb_interface_descriptor) < (size_t) size && strpos + 7 < len - 2) { struct usb_interface_descriptor *desc; char if_str[8]; desc = (struct usb_interface_descriptor *) (buf + pos); if (desc->bLength < 3) break; if (desc->bLength > size - sizeof(struct usb_interface_descriptor)) return log_device_debug_errno(dev, SYNTHETIC_ERRNO(EIO), "Corrupt data read from \"%s\"", filename); pos += desc->bLength; if (desc->bDescriptorType != USB_DT_INTERFACE) continue; if (snprintf(if_str, 8, ":%02x%02x%02x", desc->bInterfaceClass, desc->bInterfaceSubClass, desc->bInterfaceProtocol) != 7) continue; if (strstr(ifs_str, if_str)) continue; memcpy(&ifs_str[strpos], if_str, 8), strpos += 7; } if (strpos > 0) { ifs_str[strpos++] = ':'; ifs_str[strpos++] = '\0'; } return 0; } /* * A unique USB identification is generated like this: * * 1.) Get the USB device type from InterfaceClass and InterfaceSubClass * 2.) If the device type is 'Mass-Storage/SPC-2' or 'Mass-Storage/RBC', * use the SCSI vendor and model as USB-Vendor and USB-model. * 3.) Otherwise, use the USB manufacturer and product as * USB-Vendor and USB-model. Any non-printable characters * in those strings will be skipped; a slash '/' will be converted * into a full stop '.'. * 4.) If that fails, too, we will use idVendor and idProduct * as USB-Vendor and USB-model. * 5.) The USB identification is the USB-vendor and USB-model * string concatenated with an underscore '_'. * 6.) If the device supplies a serial number, this number * is concatenated with the identification with an underscore '_'. */ static int builtin_usb_id(UdevEvent *event, int argc, char *argv[], bool test) { sd_device *dev = ASSERT_PTR(ASSERT_PTR(event)->dev); char vendor_str[64] = ""; char vendor_str_enc[256]; const char *vendor_id; char model_str[64] = ""; char model_str_enc[256]; const char *product_id; char serial_str[UDEV_NAME_SIZE] = ""; char packed_if_str[UDEV_NAME_SIZE] = ""; char revision_str[64] = ""; char type_str[64] = ""; char instance_str[64] = ""; const char *ifnum = NULL; const char *driver = NULL; char serial[256]; sd_device *dev_interface, *dev_usb; const char *if_class, *if_subclass; unsigned if_class_num; int protocol = 0; size_t l; char *s; const char *syspath, *sysname, *devtype, *interface_syspath; int r; r = sd_device_get_syspath(dev, &syspath); if (r < 0) return r; r = sd_device_get_sysname(dev, &sysname); if (r < 0) return r; /* shortcut, if we are called directly for a "usb_device" type */ if (sd_device_get_devtype(dev, &devtype) >= 0 && streq(devtype, "usb_device")) { dev_if_packed_info(dev, packed_if_str, sizeof(packed_if_str)); dev_usb = dev; goto fallback; } /* usb interface directory */ r = sd_device_get_parent_with_subsystem_devtype(dev, "usb", "usb_interface", &dev_interface); if (r < 0) return log_device_debug_errno(dev, r, "Failed to access usb_interface: %m"); r = sd_device_get_syspath(dev_interface, &interface_syspath); if (r < 0) return log_device_debug_errno(dev_interface, r, "Failed to get syspath: %m"); (void) sd_device_get_sysattr_value(dev_interface, "bInterfaceNumber", &ifnum); (void) sd_device_get_sysattr_value(dev_interface, "driver", &driver); r = sd_device_get_sysattr_value(dev_interface, "bInterfaceClass", &if_class); if (r < 0) return log_device_debug_errno(dev_interface, r, "Failed to get bInterfaceClass attribute: %m"); r = safe_atou_full(if_class, 16, &if_class_num); if (r < 0) return log_device_debug_errno(dev_interface, r, "Failed to parse if_class: %m"); if (if_class_num == 8) { /* mass storage */ if (sd_device_get_sysattr_value(dev_interface, "bInterfaceSubClass", &if_subclass) >= 0) protocol = set_usb_mass_storage_ifsubtype(type_str, if_subclass, sizeof(type_str)-1); } else set_usb_iftype(type_str, if_class_num, sizeof(type_str)-1); log_device_debug(dev_interface, "if_class:%u protocol:%i", if_class_num, protocol); /* usb device directory */ r = sd_device_get_parent_with_subsystem_devtype(dev_interface, "usb", "usb_device", &dev_usb); if (r < 0) return log_device_debug_errno(dev_interface, r, "Failed to find parent 'usb' device"); /* all interfaces of the device in a single string */ dev_if_packed_info(dev_usb, packed_if_str, sizeof(packed_if_str)); /* mass storage : SCSI or ATAPI */ if (IN_SET(protocol, 6, 2)) { sd_device *dev_scsi; const char *scsi_sysname, *scsi_model, *scsi_vendor, *scsi_type, *scsi_rev; int host, bus, target, lun; /* get scsi device */ r = sd_device_get_parent_with_subsystem_devtype(dev, "scsi", "scsi_device", &dev_scsi); if (r < 0) { log_device_debug_errno(dev, r, "Unable to find parent SCSI device"); goto fallback; } if (sd_device_get_sysname(dev_scsi, &scsi_sysname) < 0) goto fallback; if (sscanf(scsi_sysname, "%d:%d:%d:%d", &host, &bus, &target, &lun) != 4) { log_device_debug(dev_scsi, "Invalid SCSI device"); goto fallback; } /* Generic SPC-2 device */ r = sd_device_get_sysattr_value(dev_scsi, "vendor", &scsi_vendor); if (r < 0) { log_device_debug_errno(dev_scsi, r, "Failed to get SCSI vendor attribute: %m"); goto fallback; } encode_devnode_name(scsi_vendor, vendor_str_enc, sizeof(vendor_str_enc)); udev_replace_whitespace(scsi_vendor, vendor_str, sizeof(vendor_str)-1); udev_replace_chars(vendor_str, NULL); r = sd_device_get_sysattr_value(dev_scsi, "model", &scsi_model); if (r < 0) { log_device_debug_errno(dev_scsi, r, "Failed to get SCSI model attribute: %m"); goto fallback; } encode_devnode_name(scsi_model, model_str_enc, sizeof(model_str_enc)); udev_replace_whitespace(scsi_model, model_str, sizeof(model_str)-1); udev_replace_chars(model_str, NULL); r = sd_device_get_sysattr_value(dev_scsi, "type", &scsi_type); if (r < 0) { log_device_debug_errno(dev_scsi, r, "Failed to get SCSI type attribute: %m"); goto fallback; } set_scsi_type(type_str, scsi_type, sizeof(type_str)-1); r = sd_device_get_sysattr_value(dev_scsi, "rev", &scsi_rev); if (r < 0) { log_device_debug_errno(dev_scsi, r, "Failed to get SCSI revision attribute: %m"); goto fallback; } udev_replace_whitespace(scsi_rev, revision_str, sizeof(revision_str)-1); udev_replace_chars(revision_str, NULL); /* * some broken devices have the same identifiers * for all luns, export the target:lun number */ sprintf(instance_str, "%d:%d", target, lun); } fallback: r = sd_device_get_sysattr_value(dev_usb, "idVendor", &vendor_id); if (r < 0) return log_device_debug_errno(dev_usb, r, "Failed to get idVendor attribute: %m"); r = sd_device_get_sysattr_value(dev_usb, "idProduct", &product_id); if (r < 0) return log_device_debug_errno(dev_usb, r, "Failed to get idProduct attribute: %m"); /* fall back to USB vendor & device */ if (vendor_str[0] == '\0') { const char *usb_vendor; if (sd_device_get_sysattr_value(dev_usb, "manufacturer", &usb_vendor) < 0) usb_vendor = vendor_id; encode_devnode_name(usb_vendor, vendor_str_enc, sizeof(vendor_str_enc)); udev_replace_whitespace(usb_vendor, vendor_str, sizeof(vendor_str)-1); udev_replace_chars(vendor_str, NULL); } if (model_str[0] == '\0') { const char *usb_model; if (sd_device_get_sysattr_value(dev_usb, "product", &usb_model) < 0) usb_model = product_id; encode_devnode_name(usb_model, model_str_enc, sizeof(model_str_enc)); udev_replace_whitespace(usb_model, model_str, sizeof(model_str)-1); udev_replace_chars(model_str, NULL); } if (revision_str[0] == '\0') { const char *usb_rev; if (sd_device_get_sysattr_value(dev_usb, "bcdDevice", &usb_rev) >= 0) { udev_replace_whitespace(usb_rev, revision_str, sizeof(revision_str)-1); udev_replace_chars(revision_str, NULL); } } if (serial_str[0] == '\0') { const char *usb_serial; if (sd_device_get_sysattr_value(dev_usb, "serial", &usb_serial) >= 0) { /* http://msdn.microsoft.com/en-us/library/windows/hardware/gg487321.aspx */ for (const unsigned char *p = (unsigned char*) usb_serial; *p != '\0'; p++) if (*p < 0x20 || *p > 0x7f || *p == ',') { usb_serial = NULL; break; } if (usb_serial) { udev_replace_whitespace(usb_serial, serial_str, sizeof(serial_str)-1); udev_replace_chars(serial_str, NULL); } } } s = serial; l = strpcpyl(&s, sizeof(serial), vendor_str, "_", model_str, NULL); if (!isempty(serial_str)) l = strpcpyl(&s, l, "_", serial_str, NULL); if (!isempty(instance_str)) strpcpyl(&s, l, "-", instance_str, NULL); if (sd_device_get_property_value(dev, "ID_BUS", NULL) >= 0) log_device_debug(dev, "ID_BUS property is already set, setting only properties prefixed with \"ID_USB_\"."); else { udev_builtin_add_property(dev, test, "ID_BUS", "usb"); udev_builtin_add_property(dev, test, "ID_MODEL", model_str); udev_builtin_add_property(dev, test, "ID_MODEL_ENC", model_str_enc); udev_builtin_add_property(dev, test, "ID_MODEL_ID", product_id); udev_builtin_add_property(dev, test, "ID_SERIAL", serial); if (!isempty(serial_str)) udev_builtin_add_property(dev, test, "ID_SERIAL_SHORT", serial_str); udev_builtin_add_property(dev, test, "ID_VENDOR", vendor_str); udev_builtin_add_property(dev, test, "ID_VENDOR_ENC", vendor_str_enc); udev_builtin_add_property(dev, test, "ID_VENDOR_ID", vendor_id); udev_builtin_add_property(dev, test, "ID_REVISION", revision_str); if (!isempty(type_str)) udev_builtin_add_property(dev, test, "ID_TYPE", type_str); if (!isempty(instance_str)) udev_builtin_add_property(dev, test, "ID_INSTANCE", instance_str); } /* Also export the same values in the above by prefixing ID_USB_. */ udev_builtin_add_property(dev, test, "ID_USB_MODEL", model_str); udev_builtin_add_property(dev, test, "ID_USB_MODEL_ENC", model_str_enc); udev_builtin_add_property(dev, test, "ID_USB_MODEL_ID", product_id); udev_builtin_add_property(dev, test, "ID_USB_SERIAL", serial); if (!isempty(serial_str)) udev_builtin_add_property(dev, test, "ID_USB_SERIAL_SHORT", serial_str); udev_builtin_add_property(dev, test, "ID_USB_VENDOR", vendor_str); udev_builtin_add_property(dev, test, "ID_USB_VENDOR_ENC", vendor_str_enc); udev_builtin_add_property(dev, test, "ID_USB_VENDOR_ID", vendor_id); udev_builtin_add_property(dev, test, "ID_USB_REVISION", revision_str); if (!isempty(type_str)) udev_builtin_add_property(dev, test, "ID_USB_TYPE", type_str); if (!isempty(instance_str)) udev_builtin_add_property(dev, test, "ID_USB_INSTANCE", instance_str); if (!isempty(packed_if_str)) udev_builtin_add_property(dev, test, "ID_USB_INTERFACES", packed_if_str); if (ifnum) udev_builtin_add_property(dev, test, "ID_USB_INTERFACE_NUM", ifnum); if (driver) udev_builtin_add_property(dev, test, "ID_USB_DRIVER", driver); return 0; } const UdevBuiltin udev_builtin_usb_id = { .name = "usb_id", .cmd = builtin_usb_id, .help = "USB device properties", .run_once = true, };
19,121
38.02449
124
c
null
systemd-main/src/udev/udev-builtin.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include <stdio.h> #include "device-private.h" #include "device-util.h" #include "string-util.h" #include "strv.h" #include "udev-builtin.h" static bool initialized; static const UdevBuiltin *const builtins[_UDEV_BUILTIN_MAX] = { #if HAVE_BLKID [UDEV_BUILTIN_BLKID] = &udev_builtin_blkid, #endif [UDEV_BUILTIN_BTRFS] = &udev_builtin_btrfs, [UDEV_BUILTIN_HWDB] = &udev_builtin_hwdb, [UDEV_BUILTIN_INPUT_ID] = &udev_builtin_input_id, [UDEV_BUILTIN_KEYBOARD] = &udev_builtin_keyboard, #if HAVE_KMOD [UDEV_BUILTIN_KMOD] = &udev_builtin_kmod, #endif [UDEV_BUILTIN_NET_ID] = &udev_builtin_net_id, [UDEV_BUILTIN_NET_LINK] = &udev_builtin_net_setup_link, [UDEV_BUILTIN_PATH_ID] = &udev_builtin_path_id, [UDEV_BUILTIN_USB_ID] = &udev_builtin_usb_id, #if HAVE_ACL [UDEV_BUILTIN_UACCESS] = &udev_builtin_uaccess, #endif }; void udev_builtin_init(void) { if (initialized) return; for (UdevBuiltinCommand i = 0; i < _UDEV_BUILTIN_MAX; i++) if (builtins[i] && builtins[i]->init) builtins[i]->init(); initialized = true; } void udev_builtin_exit(void) { if (!initialized) return; for (UdevBuiltinCommand i = 0; i < _UDEV_BUILTIN_MAX; i++) if (builtins[i] && builtins[i]->exit) builtins[i]->exit(); initialized = false; } bool udev_builtin_should_reload(void) { for (UdevBuiltinCommand i = 0; i < _UDEV_BUILTIN_MAX; i++) if (builtins[i] && builtins[i]->should_reload && builtins[i]->should_reload()) return true; return false; } void udev_builtin_list(void) { for (UdevBuiltinCommand i = 0; i < _UDEV_BUILTIN_MAX; i++) if (builtins[i]) fprintf(stderr, " %-14s %s\n", builtins[i]->name, builtins[i]->help); } const char *udev_builtin_name(UdevBuiltinCommand cmd) { assert(cmd >= 0 && cmd < _UDEV_BUILTIN_MAX); if (!builtins[cmd]) return NULL; return builtins[cmd]->name; } bool udev_builtin_run_once(UdevBuiltinCommand cmd) { assert(cmd >= 0 && cmd < _UDEV_BUILTIN_MAX); if (!builtins[cmd]) return false; return builtins[cmd]->run_once; } UdevBuiltinCommand udev_builtin_lookup(const char *command) { size_t n; assert(command); command += strspn(command, WHITESPACE); n = strcspn(command, WHITESPACE); for (UdevBuiltinCommand i = 0; i < _UDEV_BUILTIN_MAX; i++) if (builtins[i] && strneq(builtins[i]->name, command, n)) return i; return _UDEV_BUILTIN_INVALID; } int udev_builtin_run(UdevEvent *event, UdevBuiltinCommand cmd, const char *command, bool test) { _cleanup_strv_free_ char **argv = NULL; int r; assert(event); assert(event->dev); assert(cmd >= 0 && cmd < _UDEV_BUILTIN_MAX); assert(command); if (!builtins[cmd]) return -EOPNOTSUPP; r = strv_split_full(&argv, command, NULL, EXTRACT_UNQUOTE | EXTRACT_RELAX | EXTRACT_RETAIN_ESCAPE); if (r < 0) return r; /* we need '0' here to reset the internal state */ optind = 0; return builtins[cmd]->cmd(event, strv_length(argv), argv, test); } int udev_builtin_add_property(sd_device *dev, bool test, const char *key, const char *val) { int r; assert(dev); assert(key); r = device_add_property(dev, key, val); if (r < 0) return log_device_debug_errno(dev, r, "Failed to add property '%s%s%s'", key, val ? "=" : "", strempty(val)); if (test) printf("%s=%s\n", key, strempty(val)); return 0; } int udev_builtin_add_propertyf(sd_device *dev, bool test, const char *key, const char *valf, ...) { _cleanup_free_ char *val = NULL; va_list ap; int r; assert(dev); assert(key); assert(valf); va_start(ap, valf); r = vasprintf(&val, valf, ap); va_end(ap); if (r < 0) return log_oom_debug(); return udev_builtin_add_property(dev, test, key, val); }
4,464
27.621795
107
c
null
systemd-main/src/udev/udev-builtin.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include <stdbool.h> #include "sd-device.h" #include "sd-netlink.h" #include "macro.h" #include "udev-event.h" typedef enum UdevBuiltinCommand { #if HAVE_BLKID UDEV_BUILTIN_BLKID, #endif UDEV_BUILTIN_BTRFS, UDEV_BUILTIN_HWDB, UDEV_BUILTIN_INPUT_ID, UDEV_BUILTIN_KEYBOARD, #if HAVE_KMOD UDEV_BUILTIN_KMOD, #endif UDEV_BUILTIN_NET_ID, UDEV_BUILTIN_NET_LINK, UDEV_BUILTIN_PATH_ID, UDEV_BUILTIN_USB_ID, #if HAVE_ACL UDEV_BUILTIN_UACCESS, #endif _UDEV_BUILTIN_MAX, _UDEV_BUILTIN_INVALID = -EINVAL, } UdevBuiltinCommand; typedef struct UdevBuiltin { const char *name; int (*cmd)(UdevEvent *event, int argc, char *argv[], bool test); const char *help; int (*init)(void); void (*exit)(void); bool (*should_reload)(void); bool run_once; } UdevBuiltin; #define UDEV_BUILTIN_CMD_TO_PTR(u) \ ({ \ UdevBuiltinCommand _u = (u); \ _u < 0 ? NULL : (void*)(intptr_t) (_u + 1); \ }) #define PTR_TO_UDEV_BUILTIN_CMD(p) \ ({ \ void *_p = (p); \ _p && (intptr_t)(_p) <= _UDEV_BUILTIN_MAX ? \ (UdevBuiltinCommand)((intptr_t)_p - 1) : _UDEV_BUILTIN_INVALID; \ }) #if HAVE_BLKID extern const UdevBuiltin udev_builtin_blkid; #endif extern const UdevBuiltin udev_builtin_btrfs; extern const UdevBuiltin udev_builtin_hwdb; extern const UdevBuiltin udev_builtin_input_id; extern const UdevBuiltin udev_builtin_keyboard; #if HAVE_KMOD extern const UdevBuiltin udev_builtin_kmod; #endif extern const UdevBuiltin udev_builtin_net_id; extern const UdevBuiltin udev_builtin_net_setup_link; extern const UdevBuiltin udev_builtin_path_id; extern const UdevBuiltin udev_builtin_usb_id; #if HAVE_ACL extern const UdevBuiltin udev_builtin_uaccess; #endif void udev_builtin_init(void); void udev_builtin_exit(void); UdevBuiltinCommand udev_builtin_lookup(const char *command); const char *udev_builtin_name(UdevBuiltinCommand cmd); bool udev_builtin_run_once(UdevBuiltinCommand cmd); int udev_builtin_run(UdevEvent *event, UdevBuiltinCommand cmd, const char *command, bool test); void udev_builtin_list(void); bool udev_builtin_should_reload(void); int udev_builtin_add_property(sd_device *dev, bool test, const char *key, const char *val); int udev_builtin_add_propertyf(sd_device *dev, bool test, const char *key, const char *valf, ...) _printf_(4, 5); int udev_builtin_hwdb_lookup(sd_device *dev, const char *prefix, const char *modalias, const char *filter, bool test);
2,855
31.827586
113
h
null
systemd-main/src/udev/udev-ctrl.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <errno.h> #include <poll.h> #include <stddef.h> #include <stdlib.h> #include <string.h> #include <sys/un.h> #include <unistd.h> #include "sd-event.h" #include "alloc-util.h" #include "errno-util.h" #include "fd-util.h" #include "format-util.h" #include "io-util.h" #include "socket-util.h" #include "strxcpyx.h" #include "udev-ctrl.h" /* wire protocol magic must match */ #define UDEV_CTRL_MAGIC 0xdead1dea typedef struct UdevCtrlMessageWire { char version[16]; unsigned magic; UdevCtrlMessageType type; UdevCtrlMessageValue value; } UdevCtrlMessageWire; struct UdevCtrl { unsigned n_ref; int sock; int sock_connect; union sockaddr_union saddr; socklen_t addrlen; bool bound; bool connected; bool maybe_disconnected; sd_event *event; sd_event_source *event_source; sd_event_source *event_source_connect; udev_ctrl_handler_t callback; void *userdata; }; int udev_ctrl_new_from_fd(UdevCtrl **ret, int fd) { _cleanup_close_ int sock = -EBADF; UdevCtrl *uctrl; assert(ret); if (fd < 0) { sock = socket(AF_UNIX, SOCK_SEQPACKET|SOCK_NONBLOCK|SOCK_CLOEXEC, 0); if (sock < 0) return log_error_errno(errno, "Failed to create socket: %m"); } uctrl = new(UdevCtrl, 1); if (!uctrl) return -ENOMEM; *uctrl = (UdevCtrl) { .n_ref = 1, .sock = fd >= 0 ? fd : TAKE_FD(sock), .sock_connect = -EBADF, .bound = fd >= 0, }; uctrl->saddr.un = (struct sockaddr_un) { .sun_family = AF_UNIX, .sun_path = "/run/udev/control", }; uctrl->addrlen = SOCKADDR_UN_LEN(uctrl->saddr.un); *ret = TAKE_PTR(uctrl); return 0; } int udev_ctrl_enable_receiving(UdevCtrl *uctrl) { assert(uctrl); if (uctrl->bound) return 0; (void) sockaddr_un_unlink(&uctrl->saddr.un); if (bind(uctrl->sock, &uctrl->saddr.sa, uctrl->addrlen) < 0) return log_error_errno(errno, "Failed to bind udev control socket: %m"); if (listen(uctrl->sock, 0) < 0) return log_error_errno(errno, "Failed to listen udev control socket: %m"); uctrl->bound = true; return 0; } static void udev_ctrl_disconnect(UdevCtrl *uctrl) { if (!uctrl) return; uctrl->event_source_connect = sd_event_source_unref(uctrl->event_source_connect); uctrl->sock_connect = safe_close(uctrl->sock_connect); } static UdevCtrl *udev_ctrl_free(UdevCtrl *uctrl) { assert(uctrl); udev_ctrl_disconnect(uctrl); sd_event_source_unref(uctrl->event_source); safe_close(uctrl->sock); sd_event_unref(uctrl->event); return mfree(uctrl); } DEFINE_TRIVIAL_REF_UNREF_FUNC(UdevCtrl, udev_ctrl, udev_ctrl_free); int udev_ctrl_attach_event(UdevCtrl *uctrl, sd_event *event) { int r; assert_return(uctrl, -EINVAL); assert_return(!uctrl->event, -EBUSY); if (event) uctrl->event = sd_event_ref(event); else { r = sd_event_default(&uctrl->event); if (r < 0) return r; } return 0; } sd_event_source *udev_ctrl_get_event_source(UdevCtrl *uctrl) { assert(uctrl); return uctrl->event_source; } static void udev_ctrl_disconnect_and_listen_again(UdevCtrl *uctrl) { udev_ctrl_disconnect(uctrl); udev_ctrl_unref(uctrl); (void) sd_event_source_set_enabled(uctrl->event_source, SD_EVENT_ON); /* We don't return NULL here because uctrl is not freed */ } DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(UdevCtrl*, udev_ctrl_disconnect_and_listen_again, NULL); static int udev_ctrl_connection_event_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) { _cleanup_(udev_ctrl_disconnect_and_listen_againp) UdevCtrl *uctrl = NULL; UdevCtrlMessageWire msg_wire; struct iovec iov = IOVEC_MAKE(&msg_wire, sizeof(UdevCtrlMessageWire)); CMSG_BUFFER_TYPE(CMSG_SPACE(sizeof(struct ucred))) control; struct msghdr smsg = { .msg_iov = &iov, .msg_iovlen = 1, .msg_control = &control, .msg_controllen = sizeof(control), }; struct ucred *cred; ssize_t size; assert(userdata); /* When UDEV_CTRL_EXIT is received, manager unref udev_ctrl object. * To avoid the object freed, let's increment the refcount. */ uctrl = udev_ctrl_ref(userdata); size = next_datagram_size_fd(fd); if (size < 0) return log_error_errno(size, "Failed to get size of message: %m"); if (size == 0) return 0; /* Client disconnects? */ size = recvmsg_safe(fd, &smsg, 0); if (size == -EINTR) return 0; if (size < 0) return log_error_errno(size, "Failed to receive ctrl message: %m"); cmsg_close_all(&smsg); cred = CMSG_FIND_DATA(&smsg, SOL_SOCKET, SCM_CREDENTIALS, struct ucred); if (!cred) { log_error("No sender credentials received, ignoring message"); return 0; } if (cred->uid != 0) { log_error("Invalid sender uid "UID_FMT", ignoring message", cred->uid); return 0; } if (msg_wire.magic != UDEV_CTRL_MAGIC) { log_error("Message magic 0x%08x doesn't match, ignoring message", msg_wire.magic); return 0; } if (msg_wire.type == _UDEV_CTRL_END_MESSAGES) return 0; if (uctrl->callback) (void) uctrl->callback(uctrl, msg_wire.type, &msg_wire.value, uctrl->userdata); /* Do not disconnect and wait for next message. */ uctrl = udev_ctrl_unref(uctrl); return 0; } static int udev_ctrl_event_handler(sd_event_source *s, int fd, uint32_t revents, void *userdata) { UdevCtrl *uctrl = ASSERT_PTR(userdata); _cleanup_close_ int sock = -EBADF; struct ucred ucred; int r; sock = accept4(fd, NULL, NULL, SOCK_CLOEXEC|SOCK_NONBLOCK); if (sock < 0) { if (ERRNO_IS_ACCEPT_AGAIN(errno)) return 0; return log_error_errno(errno, "Failed to accept ctrl connection: %m"); } /* check peer credential of connection */ r = getpeercred(sock, &ucred); if (r < 0) { log_error_errno(r, "Failed to receive credentials of ctrl connection: %m"); return 0; } if (ucred.uid > 0) { log_error("Invalid sender uid "UID_FMT", closing connection", ucred.uid); return 0; } /* enable receiving of the sender credentials in the messages */ r = setsockopt_int(sock, SOL_SOCKET, SO_PASSCRED, true); if (r < 0) log_warning_errno(r, "Failed to set SO_PASSCRED, ignoring: %m"); r = sd_event_add_io(uctrl->event, &uctrl->event_source_connect, sock, EPOLLIN, udev_ctrl_connection_event_handler, uctrl); if (r < 0) { log_error_errno(r, "Failed to create event source for udev control connection: %m"); return 0; } (void) sd_event_source_set_description(uctrl->event_source_connect, "udev-ctrl-connection"); /* Do not accept multiple connection. */ (void) sd_event_source_set_enabled(uctrl->event_source, SD_EVENT_OFF); uctrl->sock_connect = TAKE_FD(sock); return 0; } int udev_ctrl_start(UdevCtrl *uctrl, udev_ctrl_handler_t callback, void *userdata) { int r; assert(uctrl); if (!uctrl->event) { r = udev_ctrl_attach_event(uctrl, NULL); if (r < 0) return r; } r = udev_ctrl_enable_receiving(uctrl); if (r < 0) return r; uctrl->callback = callback; uctrl->userdata = userdata; r = sd_event_add_io(uctrl->event, &uctrl->event_source, uctrl->sock, EPOLLIN, udev_ctrl_event_handler, uctrl); if (r < 0) return r; (void) sd_event_source_set_description(uctrl->event_source, "udev-ctrl"); return 0; } int udev_ctrl_send(UdevCtrl *uctrl, UdevCtrlMessageType type, const void *data) { UdevCtrlMessageWire ctrl_msg_wire = { .version = "udev-" STRINGIFY(PROJECT_VERSION), .magic = UDEV_CTRL_MAGIC, .type = type, }; if (uctrl->maybe_disconnected) return -ENOANO; /* to distinguish this from other errors. */ if (type == UDEV_CTRL_SET_ENV) { assert(data); strscpy(ctrl_msg_wire.value.buf, sizeof(ctrl_msg_wire.value.buf), data); } else if (IN_SET(type, UDEV_CTRL_SET_LOG_LEVEL, UDEV_CTRL_SET_CHILDREN_MAX)) ctrl_msg_wire.value.intval = PTR_TO_INT(data); if (!uctrl->connected) { if (connect(uctrl->sock, &uctrl->saddr.sa, uctrl->addrlen) < 0) return -errno; uctrl->connected = true; } if (send(uctrl->sock, &ctrl_msg_wire, sizeof(ctrl_msg_wire), 0) < 0) return -errno; if (type == UDEV_CTRL_EXIT) uctrl->maybe_disconnected = true; return 0; } int udev_ctrl_wait(UdevCtrl *uctrl, usec_t timeout) { _cleanup_(sd_event_source_disable_unrefp) sd_event_source *source_io = NULL, *source_timeout = NULL; int r; assert(uctrl); if (uctrl->sock < 0) return 0; if (!uctrl->connected) return 0; if (!uctrl->maybe_disconnected) { r = udev_ctrl_send(uctrl, _UDEV_CTRL_END_MESSAGES, NULL); if (r < 0) return r; } if (timeout == 0) return 0; if (!uctrl->event) { r = udev_ctrl_attach_event(uctrl, NULL); if (r < 0) return r; } r = sd_event_add_io(uctrl->event, &source_io, uctrl->sock, EPOLLIN, NULL, INT_TO_PTR(0)); if (r < 0) return r; (void) sd_event_source_set_description(source_io, "udev-ctrl-wait-io"); if (timeout != USEC_INFINITY) { r = sd_event_add_time_relative( uctrl->event, &source_timeout, CLOCK_BOOTTIME, timeout, 0, NULL, INT_TO_PTR(-ETIMEDOUT)); if (r < 0) return r; (void) sd_event_source_set_description(source_timeout, "udev-ctrl-wait-timeout"); } return sd_event_loop(uctrl->event); }
11,212
29.889807
130
c
null
systemd-main/src/udev/udev-ctrl.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include "sd-event.h" #include "macro.h" #include "time-util.h" typedef struct UdevCtrl UdevCtrl; typedef enum UdevCtrlMessageType { _UDEV_CTRL_END_MESSAGES, UDEV_CTRL_SET_LOG_LEVEL, UDEV_CTRL_STOP_EXEC_QUEUE, UDEV_CTRL_START_EXEC_QUEUE, UDEV_CTRL_RELOAD, UDEV_CTRL_SET_ENV, UDEV_CTRL_SET_CHILDREN_MAX, UDEV_CTRL_PING, UDEV_CTRL_EXIT, } UdevCtrlMessageType; typedef union UdevCtrlMessageValue { int intval; char buf[256]; } UdevCtrlMessageValue; typedef int (*udev_ctrl_handler_t)(UdevCtrl *udev_ctrl, UdevCtrlMessageType type, const UdevCtrlMessageValue *value, void *userdata); int udev_ctrl_new_from_fd(UdevCtrl **ret, int fd); static inline int udev_ctrl_new(UdevCtrl **ret) { return udev_ctrl_new_from_fd(ret, -1); } int udev_ctrl_enable_receiving(UdevCtrl *uctrl); UdevCtrl *udev_ctrl_ref(UdevCtrl *uctrl); UdevCtrl *udev_ctrl_unref(UdevCtrl *uctrl); int udev_ctrl_attach_event(UdevCtrl *uctrl, sd_event *event); int udev_ctrl_start(UdevCtrl *uctrl, udev_ctrl_handler_t callback, void *userdata); sd_event_source *udev_ctrl_get_event_source(UdevCtrl *uctrl); int udev_ctrl_wait(UdevCtrl *uctrl, usec_t timeout); int udev_ctrl_send(UdevCtrl *uctrl, UdevCtrlMessageType type, const void *data); static inline int udev_ctrl_send_set_log_level(UdevCtrl *uctrl, int priority) { return udev_ctrl_send(uctrl, UDEV_CTRL_SET_LOG_LEVEL, INT_TO_PTR(priority)); } static inline int udev_ctrl_send_stop_exec_queue(UdevCtrl *uctrl) { return udev_ctrl_send(uctrl, UDEV_CTRL_STOP_EXEC_QUEUE, NULL); } static inline int udev_ctrl_send_start_exec_queue(UdevCtrl *uctrl) { return udev_ctrl_send(uctrl, UDEV_CTRL_START_EXEC_QUEUE, NULL); } static inline int udev_ctrl_send_reload(UdevCtrl *uctrl) { return udev_ctrl_send(uctrl, UDEV_CTRL_RELOAD, NULL); } static inline int udev_ctrl_send_set_env(UdevCtrl *uctrl, const char *key) { return udev_ctrl_send(uctrl, UDEV_CTRL_SET_ENV, key); } static inline int udev_ctrl_send_set_children_max(UdevCtrl *uctrl, int count) { return udev_ctrl_send(uctrl, UDEV_CTRL_SET_CHILDREN_MAX, INT_TO_PTR(count)); } static inline int udev_ctrl_send_ping(UdevCtrl *uctrl) { return udev_ctrl_send(uctrl, UDEV_CTRL_PING, NULL); } static inline int udev_ctrl_send_exit(UdevCtrl *uctrl) { return udev_ctrl_send(uctrl, UDEV_CTRL_EXIT, NULL); } DEFINE_TRIVIAL_CLEANUP_FUNC(UdevCtrl*, udev_ctrl_unref);
2,586
31.746835
86
h
null
systemd-main/src/udev/udev-event.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once /* * Copyright Β© 2003 Greg Kroah-Hartman <[email protected]> */ #include "sd-device.h" #include "sd-netlink.h" #include "hashmap.h" #include "macro.h" #include "udev-rules.h" #include "udev-util.h" #define READ_END 0 #define WRITE_END 1 #define UDEV_ALLOWED_CHARS_INPUT "/ $%?," typedef struct UdevEvent { sd_device *dev; sd_device *dev_parent; sd_device *dev_db_clone; char *name; char **altnames; char *program_result; mode_t mode; uid_t uid; gid_t gid; OrderedHashmap *seclabel_list; OrderedHashmap *run_list; usec_t exec_delay_usec; usec_t birth_usec; sd_netlink *rtnl; unsigned builtin_run; unsigned builtin_ret; UdevRuleEscapeType esc:8; bool inotify_watch; bool inotify_watch_final; bool group_final; bool owner_final; bool mode_final; bool name_final; bool devlink_final; bool run_final; bool log_level_was_debug; int default_log_level; } UdevEvent; UdevEvent *udev_event_new(sd_device *dev, usec_t exec_delay_usec, sd_netlink *rtnl, int log_level); UdevEvent *udev_event_free(UdevEvent *event); DEFINE_TRIVIAL_CLEANUP_FUNC(UdevEvent*, udev_event_free); size_t udev_event_apply_format( UdevEvent *event, const char *src, char *dest, size_t size, bool replace_whitespace, bool *ret_truncated); int udev_check_format(const char *value, size_t *offset, const char **hint); int udev_event_spawn( UdevEvent *event, usec_t timeout_usec, int timeout_signal, bool accept_failure, const char *cmd, char *result, size_t ressize, bool *ret_truncated); int udev_event_execute_rules( UdevEvent *event, int inotify_fd, usec_t timeout_usec, int timeout_signal, Hashmap *properties_list, UdevRules *rules); void udev_event_execute_run(UdevEvent *event, usec_t timeout_usec, int timeout_signal); static inline usec_t udev_warn_timeout(usec_t timeout_usec) { return DIV_ROUND_UP(timeout_usec, 3); }
2,409
28.036145
99
h
null
systemd-main/src/udev/udev-node.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include <stdbool.h> #include <sys/types.h> #include "sd-device.h" #include "hashmap.h" int udev_node_apply_permissions( sd_device *dev, bool apply_mac, mode_t mode, uid_t uid, gid_t gid, OrderedHashmap *seclabel_list); int static_node_apply_permissions( const char *name, mode_t mode, uid_t uid, gid_t gid, char **tags); int udev_node_remove(sd_device *dev); int udev_node_update(sd_device *dev, sd_device *dev_old); int udev_node_cleanup(void); size_t udev_node_escape_path(const char *src, char *dest, size_t size);
762
24.433333
71
h
null
systemd-main/src/udev/udev-rules.h
/* SPDX-License-Identifier: GPL-2.0-or-later */ #pragma once #include "alloc-util.h" #include "hashmap.h" #include "time-util.h" #include "udev-util.h" typedef struct UdevRuleFile UdevRuleFile; typedef struct UdevRules UdevRules; typedef struct UdevEvent UdevEvent; typedef enum { ESCAPE_UNSET, ESCAPE_NONE, /* OPTIONS="string_escape=none" */ ESCAPE_REPLACE, /* OPTIONS="string_escape=replace" */ _ESCAPE_TYPE_MAX, _ESCAPE_TYPE_INVALID = -EINVAL, } UdevRuleEscapeType; int udev_rules_parse_file(UdevRules *rules, const char *filename, bool extra_checks, UdevRuleFile **ret); unsigned udev_rule_file_get_issues(UdevRuleFile *rule_file); UdevRules* udev_rules_new(ResolveNameTiming resolve_name_timing); int udev_rules_load(UdevRules **ret_rules, ResolveNameTiming resolve_name_timing); UdevRules *udev_rules_free(UdevRules *rules); DEFINE_TRIVIAL_CLEANUP_FUNC(UdevRules*, udev_rules_free); #define udev_rules_free_and_replace(a, b) free_and_replace_full(a, b, udev_rules_free) bool udev_rules_should_reload(UdevRules *rules); int udev_rules_apply_to_event(UdevRules *rules, UdevEvent *event, usec_t timeout_usec, int timeout_signal, Hashmap *properties_list); int udev_rules_apply_static_dev_perms(UdevRules *rules);
1,354
37.714286
105
h
null
systemd-main/src/udev/udev-watch.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright Β© 2009 Canonical Ltd. * Copyright Β© 2009 Scott James Remnant <[email protected]> */ #include <sys/inotify.h> #include "alloc-util.h" #include "device-private.h" #include "device-util.h" #include "dirent-util.h" #include "fd-util.h" #include "fs-util.h" #include "mkdir.h" #include "parse-util.h" #include "rm-rf.h" #include "stdio-util.h" #include "string-util.h" #include "udev-util.h" #include "udev-watch.h" int device_new_from_watch_handle_at(sd_device **ret, int dirfd, int wd) { char path_wd[STRLEN("/run/udev/watch/") + DECIMAL_STR_MAX(int)]; _cleanup_free_ char *id = NULL; int r; assert(ret); if (wd < 0) return -EBADF; if (dirfd >= 0) { xsprintf(path_wd, "%d", wd); r = readlinkat_malloc(dirfd, path_wd, &id); } else { xsprintf(path_wd, "/run/udev/watch/%d", wd); r = readlink_malloc(path_wd, &id); } if (r < 0) return r; return sd_device_new_from_device_id(ret, id); } int udev_watch_restore(int inotify_fd) { _cleanup_closedir_ DIR *dir = NULL; int r; /* Move any old watches directory out of the way, and then restore the watches. */ assert(inotify_fd >= 0); (void) rm_rf("/run/udev/watch.old", REMOVE_ROOT); if (rename("/run/udev/watch", "/run/udev/watch.old") < 0) { if (errno == ENOENT) return 0; r = log_warning_errno(errno, "Failed to move watches directory '/run/udev/watch/'. " "Old watches will not be restored: %m"); goto finalize; } dir = opendir("/run/udev/watch.old"); if (!dir) { r = log_warning_errno(errno, "Failed to open old watches directory '/run/udev/watch.old/'. " "Old watches will not be restored: %m"); goto finalize; } FOREACH_DIRENT_ALL(de, dir, break) { _cleanup_(sd_device_unrefp) sd_device *dev = NULL; int wd; /* For backward compatibility, read symlink from watch handle to device ID. This is necessary * when udevd is restarted after upgrading from v248 or older. The new format (ID -> wd) was * introduced by e7f781e473f5119bf9246208a6de9f6b76a39c5d (v249). */ if (dot_or_dot_dot(de->d_name)) continue; if (safe_atoi(de->d_name, &wd) < 0) continue; r = device_new_from_watch_handle_at(&dev, dirfd(dir), wd); if (r < 0) { log_full_errno(r == -ENODEV ? LOG_DEBUG : LOG_WARNING, r, "Failed to create sd_device object from saved watch handle '%i', ignoring: %m", wd); continue; } (void) udev_watch_begin(inotify_fd, dev); } r = 0; finalize: (void) rm_rf("/run/udev/watch.old", REMOVE_ROOT); return r; } static int udev_watch_clear(sd_device *dev, int dirfd, int *ret_wd) { _cleanup_free_ char *wd_str = NULL, *buf = NULL; const char *id; int wd = -1, r; assert(dev); assert(dirfd >= 0); r = device_get_device_id(dev, &id); if (r < 0) return log_device_debug_errno(dev, r, "Failed to get device ID: %m"); /* 1. read symlink ID -> wd */ r = readlinkat_malloc(dirfd, id, &wd_str); if (r == -ENOENT) { if (ret_wd) *ret_wd = -1; return 0; } if (r < 0) { log_device_debug_errno(dev, r, "Failed to read symlink '/run/udev/watch/%s': %m", id); goto finalize; } r = safe_atoi(wd_str, &wd); if (r < 0) { log_device_debug_errno(dev, r, "Failed to parse watch handle from symlink '/run/udev/watch/%s': %m", id); goto finalize; } if (wd < 0) { r = log_device_debug_errno(dev, SYNTHETIC_ERRNO(EBADF), "Invalid watch handle %i.", wd); goto finalize; } /* 2. read symlink wd -> ID */ r = readlinkat_malloc(dirfd, wd_str, &buf); if (r < 0) { log_device_debug_errno(dev, r, "Failed to read symlink '/run/udev/watch/%s': %m", wd_str); goto finalize; } /* 3. check if the symlink wd -> ID is owned by the device. */ if (!streq(buf, id)) { r = log_device_debug_errno(dev, SYNTHETIC_ERRNO(ENOENT), "Symlink '/run/udev/watch/%s' is owned by another device '%s'.", wd_str, buf); goto finalize; } /* 4. remove symlink wd -> ID. * In the above, we already confirmed that the symlink is owned by us. Hence, no other workers remove * the symlink and cannot create a new symlink with the same filename but to a different ID. Hence, * the removal below is safe even the steps in this function are not atomic. */ if (unlinkat(dirfd, wd_str, 0) < 0 && errno != ENOENT) log_device_debug_errno(dev, errno, "Failed to remove '/run/udev/watch/%s', ignoring: %m", wd_str); if (ret_wd) *ret_wd = wd; r = 0; finalize: /* 5. remove symlink ID -> wd. * The file is always owned by the device. Hence, it is safe to remove it unconditionally. */ if (unlinkat(dirfd, id, 0) < 0 && errno != ENOENT) log_device_debug_errno(dev, errno, "Failed to remove '/run/udev/watch/%s': %m", id); return r; } int udev_watch_begin(int inotify_fd, sd_device *dev) { char wd_str[DECIMAL_STR_MAX(int)]; _cleanup_close_ int dirfd = -EBADF; const char *devnode, *id; int wd, r; assert(inotify_fd >= 0); assert(dev); if (device_for_action(dev, SD_DEVICE_REMOVE)) return 0; r = sd_device_get_devname(dev, &devnode); if (r < 0) return log_device_debug_errno(dev, r, "Failed to get device node: %m"); r = device_get_device_id(dev, &id); if (r < 0) return log_device_debug_errno(dev, r, "Failed to get device ID: %m"); r = dirfd = open_mkdir_at(AT_FDCWD, "/run/udev/watch", O_CLOEXEC | O_RDONLY, 0755); if (r < 0) return log_device_debug_errno(dev, r, "Failed to create and open '/run/udev/watch/': %m"); /* 1. Clear old symlinks */ (void) udev_watch_clear(dev, dirfd, NULL); /* 2. Add inotify watch */ log_device_debug(dev, "Adding watch on '%s'", devnode); wd = inotify_add_watch(inotify_fd, devnode, IN_CLOSE_WRITE); if (wd < 0) return log_device_debug_errno(dev, errno, "Failed to watch device node '%s': %m", devnode); xsprintf(wd_str, "%d", wd); /* 3. Create new symlinks */ if (symlinkat(wd_str, dirfd, id) < 0) { r = log_device_debug_errno(dev, errno, "Failed to create symlink '/run/udev/watch/%s' to '%s': %m", id, wd_str); goto on_failure; } if (symlinkat(id, dirfd, wd_str) < 0) { /* Possibly, the watch handle is previously assigned to another device, and udev_watch_end() * is not called for the device yet. */ r = log_device_debug_errno(dev, errno, "Failed to create symlink '/run/udev/watch/%s' to '%s': %m", wd_str, id); goto on_failure; } return 0; on_failure: (void) unlinkat(dirfd, id, 0); (void) inotify_rm_watch(inotify_fd, wd); return r; } int udev_watch_end(int inotify_fd, sd_device *dev) { _cleanup_close_ int dirfd = -EBADF; int wd, r; assert(dev); /* This may be called by 'udevadm test'. In that case, inotify_fd is not initialized. */ if (inotify_fd < 0) return 0; if (sd_device_get_devname(dev, NULL) < 0) return 0; dirfd = RET_NERRNO(open("/run/udev/watch", O_CLOEXEC | O_DIRECTORY | O_NOFOLLOW | O_RDONLY)); if (dirfd == -ENOENT) return 0; if (dirfd < 0) return log_device_debug_errno(dev, dirfd, "Failed to open '/run/udev/watch/': %m"); /* First, clear symlinks. */ r = udev_watch_clear(dev, dirfd, &wd); if (r < 0) return r; /* Then, remove inotify watch. */ log_device_debug(dev, "Removing watch handle %i.", wd); (void) inotify_rm_watch(inotify_fd, wd); return 0; }
9,035
33.62069
128
c
null
systemd-main/src/udev/udevadm-control.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ #include <errno.h> #include <getopt.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include "parse-util.h" #include "process-util.h" #include "syslog-util.h" #include "time-util.h" #include "udevadm.h" #include "udev-ctrl.h" #include "virt.h" static int help(void) { printf("%s control OPTION\n\n" "Control the udev daemon.\n\n" " -h --help Show this help\n" " -V --version Show package version\n" " -e --exit Instruct the daemon to cleanup and exit\n" " -l --log-level=LEVEL Set the udev log level for the daemon\n" " -s --stop-exec-queue Do not execute events, queue only\n" " -S --start-exec-queue Execute events, flush queue\n" " -R --reload Reload rules and databases\n" " -p --property=KEY=VALUE Set a global property for all events\n" " -m --children-max=N Maximum number of children\n" " --ping Wait for udev to respond to a ping message\n" " -t --timeout=SECONDS Maximum time to block for a reply\n", program_invocation_short_name); return 0; } int control_main(int argc, char *argv[], void *userdata) { _cleanup_(udev_ctrl_unrefp) UdevCtrl *uctrl = NULL; usec_t timeout = 60 * USEC_PER_SEC; int c, r; enum { ARG_PING = 0x100, }; static const struct option options[] = { { "exit", no_argument, NULL, 'e' }, { "log-level", required_argument, NULL, 'l' }, { "log-priority", required_argument, NULL, 'l' }, /* for backward compatibility */ { "stop-exec-queue", no_argument, NULL, 's' }, { "start-exec-queue", no_argument, NULL, 'S' }, { "reload", no_argument, NULL, 'R' }, { "reload-rules", no_argument, NULL, 'R' }, /* alias for -R */ { "property", required_argument, NULL, 'p' }, { "env", required_argument, NULL, 'p' }, /* alias for -p */ { "children-max", required_argument, NULL, 'm' }, { "ping", no_argument, NULL, ARG_PING }, { "timeout", required_argument, NULL, 't' }, { "version", no_argument, NULL, 'V' }, { "help", no_argument, NULL, 'h' }, {} }; if (running_in_chroot() > 0) { log_info("Running in chroot, ignoring request."); return 0; } if (argc <= 1) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "This command expects one or more options."); r = udev_ctrl_new(&uctrl); if (r < 0) return log_error_errno(r, "Failed to initialize udev control: %m"); while ((c = getopt_long(argc, argv, "el:sSRp:m:t:Vh", options, NULL)) >= 0) switch (c) { case 'e': r = udev_ctrl_send_exit(uctrl); if (r == -ENOANO) log_warning("Cannot specify --exit after --exit, ignoring."); else if (r < 0) return log_error_errno(r, "Failed to send exit request: %m"); break; case 'l': r = log_level_from_string(optarg); if (r < 0) return log_error_errno(r, "Failed to parse log level '%s': %m", optarg); r = udev_ctrl_send_set_log_level(uctrl, r); if (r == -ENOANO) log_warning("Cannot specify --log-level after --exit, ignoring."); else if (r < 0) return log_error_errno(r, "Failed to send request to set log level: %m"); break; case 's': r = udev_ctrl_send_stop_exec_queue(uctrl); if (r == -ENOANO) log_warning("Cannot specify --stop-exec-queue after --exit, ignoring."); else if (r < 0) return log_error_errno(r, "Failed to send request to stop exec queue: %m"); break; case 'S': r = udev_ctrl_send_start_exec_queue(uctrl); if (r == -ENOANO) log_warning("Cannot specify --start-exec-queue after --exit, ignoring."); else if (r < 0) return log_error_errno(r, "Failed to send request to start exec queue: %m"); break; case 'R': r = udev_ctrl_send_reload(uctrl); if (r == -ENOANO) log_warning("Cannot specify --reload after --exit, ignoring."); else if (r < 0) return log_error_errno(r, "Failed to send reload request: %m"); break; case 'p': if (!strchr(optarg, '=')) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "expect <KEY>=<value> instead of '%s'", optarg); r = udev_ctrl_send_set_env(uctrl, optarg); if (r == -ENOANO) log_warning("Cannot specify --property after --exit, ignoring."); else if (r < 0) return log_error_errno(r, "Failed to send request to update environment: %m"); break; case 'm': { unsigned i; r = safe_atou(optarg, &i); if (r < 0) return log_error_errno(r, "Failed to parse maximum number of children '%s': %m", optarg); r = udev_ctrl_send_set_children_max(uctrl, i); if (r == -ENOANO) log_warning("Cannot specify --children-max after --exit, ignoring."); else if (r < 0) return log_error_errno(r, "Failed to send request to set number of children: %m"); break; } case ARG_PING: r = udev_ctrl_send_ping(uctrl); if (r == -ENOANO) log_error("Cannot specify --ping after --exit, ignoring."); else if (r < 0) return log_error_errno(r, "Failed to send a ping message: %m"); break; case 't': r = parse_sec(optarg, &timeout); if (r < 0) return log_error_errno(r, "Failed to parse timeout value '%s': %m", optarg); break; case 'V': return print_version(); case 'h': return help(); case '?': return -EINVAL; default: assert_not_reached(); } if (optind < argc) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Extraneous argument: %s", argv[optind]); r = udev_ctrl_wait(uctrl, timeout); if (r < 0) return log_error_errno(r, "Failed to wait for daemon to reply: %m"); return 0; }
8,693
45.741935
128
c
null
systemd-main/src/udev/udevadm-hwdb.c
/* SPDX-License-Identifier: LGPL-2.1-or-later */ #include <getopt.h> #include "hwdb-util.h" #include "udevadm.h" static const char *arg_test = NULL; static const char *arg_root = NULL; static const char *arg_hwdb_bin_dir = NULL; static bool arg_update = false; static bool arg_strict = false; static int help(void) { printf("%s hwdb [OPTIONS]\n\n" " -h --help Print this message\n" " -V --version Print version of the program\n" " -u --update Update the hardware database\n" " -s --strict When updating, return non-zero exit value on any parsing error\n" " --usr Generate in " UDEVLIBEXECDIR " instead of /etc/udev\n" " -t --test=MODALIAS Query database and print result\n" " -r --root=PATH Alternative root path in the filesystem\n\n" "NOTE:\n" "The sub-command 'hwdb' is deprecated, and is left for backwards compatibility.\n" "Please use systemd-hwdb instead.\n", program_invocation_short_name); return 0; } static int parse_argv(int argc, char *argv[]) { enum { ARG_USR = 0x100, }; static const struct option options[] = { { "update", no_argument, NULL, 'u' }, { "usr", no_argument, NULL, ARG_USR }, { "strict", no_argument, NULL, 's' }, { "test", required_argument, NULL, 't' }, { "root", required_argument, NULL, 'r' }, { "version", no_argument, NULL, 'V' }, { "help", no_argument, NULL, 'h' }, {} }; int c; while ((c = getopt_long(argc, argv, "ust:r:Vh", options, NULL)) >= 0) switch (c) { case 'u': arg_update = true; break; case ARG_USR: arg_hwdb_bin_dir = UDEVLIBEXECDIR; break; case 's': arg_strict = true; break; case 't': arg_test = optarg; break; case 'r': arg_root = optarg; break; case 'V': return print_version(); case 'h': return help(); case '?': return -EINVAL; default: assert_not_reached(); } return 1; } int hwdb_main(int argc, char *argv[], void *userdata) { int r; r = parse_argv(argc, argv); if (r <= 0) return r; if (!arg_update && !arg_test) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Either --update or --test must be used."); log_notice("udevadm hwdb is deprecated. Use systemd-hwdb instead."); if (arg_update) { r = hwdb_update(arg_root, arg_hwdb_bin_dir, arg_strict, true); if (r < 0) return r; } if (arg_test) return hwdb_query(arg_test, NULL); return 0; }
3,457
32.572816
104
c
null
systemd-main/src/udev/udevadm-monitor.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ #include <errno.h> #include <getopt.h> #include "sd-device.h" #include "sd-event.h" #include "alloc-util.h" #include "device-monitor-private.h" #include "device-private.h" #include "device-util.h" #include "fd-util.h" #include "format-util.h" #include "hashmap.h" #include "set.h" #include "signal-util.h" #include "string-util.h" #include "udevadm.h" #include "virt.h" #include "time-util.h" static bool arg_show_property = false; static bool arg_print_kernel = false; static bool arg_print_udev = false; static Set *arg_tag_filter = NULL; static Hashmap *arg_subsystem_filter = NULL; static int device_monitor_handler(sd_device_monitor *monitor, sd_device *device, void *userdata) { sd_device_action_t action = _SD_DEVICE_ACTION_INVALID; const char *devpath = NULL, *subsystem = NULL; MonitorNetlinkGroup group = PTR_TO_INT(userdata); struct timespec ts; assert(device); assert(IN_SET(group, MONITOR_GROUP_UDEV, MONITOR_GROUP_KERNEL)); (void) sd_device_get_action(device, &action); (void) sd_device_get_devpath(device, &devpath); (void) sd_device_get_subsystem(device, &subsystem); assert_se(clock_gettime(CLOCK_MONOTONIC, &ts) == 0); printf("%-6s[%"PRI_TIME".%06"PRI_NSEC"] %-8s %s (%s)\n", group == MONITOR_GROUP_UDEV ? "UDEV" : "KERNEL", ts.tv_sec, (nsec_t)ts.tv_nsec/1000, strna(device_action_to_string(action)), devpath, subsystem); if (arg_show_property) { FOREACH_DEVICE_PROPERTY(device, key, value) printf("%s=%s\n", key, value); printf("\n"); } return 0; } static int setup_monitor(MonitorNetlinkGroup sender, sd_event *event, sd_device_monitor **ret) { _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *monitor = NULL; const char *subsystem, *devtype, *tag; int r; r = device_monitor_new_full(&monitor, sender, -1); if (r < 0) return log_error_errno(r, "Failed to create netlink socket: %m"); (void) sd_device_monitor_set_receive_buffer_size(monitor, 128*1024*1024); r = sd_device_monitor_attach_event(monitor, event); if (r < 0) return log_error_errno(r, "Failed to attach event: %m"); HASHMAP_FOREACH_KEY(devtype, subsystem, arg_subsystem_filter) { r = sd_device_monitor_filter_add_match_subsystem_devtype(monitor, subsystem, devtype); if (r < 0) return log_error_errno(r, "Failed to apply subsystem filter '%s%s%s': %m", subsystem, devtype ? "/" : "", strempty(devtype)); } SET_FOREACH(tag, arg_tag_filter) { r = sd_device_monitor_filter_add_match_tag(monitor, tag); if (r < 0) return log_error_errno(r, "Failed to apply tag filter '%s': %m", tag); } r = sd_device_monitor_start(monitor, device_monitor_handler, INT_TO_PTR(sender)); if (r < 0) return log_error_errno(r, "Failed to start device monitor: %m"); (void) sd_device_monitor_set_description(monitor, sender == MONITOR_GROUP_UDEV ? "udev" : "kernel"); *ret = TAKE_PTR(monitor); return 0; } static int help(void) { printf("%s monitor [OPTIONS]\n\n" "Listen to kernel and udev events.\n\n" " -h --help Show this help\n" " -V --version Show package version\n" " -p --property Print the event properties\n" " -k --kernel Print kernel uevents\n" " -u --udev Print udev events\n" " -s --subsystem-match=SUBSYSTEM[/DEVTYPE] Filter events by subsystem\n" " -t --tag-match=TAG Filter events by tag\n", program_invocation_short_name); return 0; } static int parse_argv(int argc, char *argv[]) { static const struct option options[] = { { "property", no_argument, NULL, 'p' }, { "environment", no_argument, NULL, 'e' }, /* alias for -p */ { "kernel", no_argument, NULL, 'k' }, { "udev", no_argument, NULL, 'u' }, { "subsystem-match", required_argument, NULL, 's' }, { "tag-match", required_argument, NULL, 't' }, { "version", no_argument, NULL, 'V' }, { "help", no_argument, NULL, 'h' }, {} }; int r, c; while ((c = getopt_long(argc, argv, "pekus:t:Vh", options, NULL)) >= 0) switch (c) { case 'p': case 'e': arg_show_property = true; break; case 'k': arg_print_kernel = true; break; case 'u': arg_print_udev = true; break; case 's': { _cleanup_free_ char *subsystem = NULL, *devtype = NULL; const char *slash; slash = strchr(optarg, '/'); if (slash) { devtype = strdup(slash + 1); if (!devtype) return -ENOMEM; subsystem = strndup(optarg, slash - optarg); } else subsystem = strdup(optarg); if (!subsystem) return -ENOMEM; r = hashmap_ensure_put(&arg_subsystem_filter, NULL, subsystem, devtype); if (r < 0) return r; TAKE_PTR(subsystem); TAKE_PTR(devtype); break; } case 't': /* optarg is stored in argv[], so we don't need to copy it */ r = set_ensure_put(&arg_tag_filter, &string_hash_ops, optarg); if (r < 0) return r; break; case 'V': return print_version(); case 'h': return help(); case '?': return -EINVAL; default: assert_not_reached(); } if (!arg_print_kernel && !arg_print_udev) { arg_print_kernel = true; arg_print_udev = true; } return 1; } int monitor_main(int argc, char *argv[], void *userdata) { _cleanup_(sd_device_monitor_unrefp) sd_device_monitor *kernel_monitor = NULL, *udev_monitor = NULL; _cleanup_(sd_event_unrefp) sd_event *event = NULL; int r; r = parse_argv(argc, argv); if (r <= 0) goto finalize; if (running_in_chroot() > 0) { log_info("Running in chroot, ignoring request."); return 0; } /* Callers are expecting to see events as they happen: Line buffering */ setlinebuf(stdout); r = sd_event_default(&event); if (r < 0) { log_error_errno(r, "Failed to initialize event: %m"); goto finalize; } assert_se(sigprocmask_many(SIG_UNBLOCK, NULL, SIGTERM, SIGINT, -1) >= 0); (void) sd_event_add_signal(event, NULL, SIGTERM, NULL, NULL); (void) sd_event_add_signal(event, NULL, SIGINT, NULL, NULL); printf("monitor will print the received events for:\n"); if (arg_print_udev) { r = setup_monitor(MONITOR_GROUP_UDEV, event, &udev_monitor); if (r < 0) goto finalize; printf("UDEV - the event which udev sends out after rule processing\n"); } if (arg_print_kernel) { r = setup_monitor(MONITOR_GROUP_KERNEL, event, &kernel_monitor); if (r < 0) goto finalize; printf("KERNEL - the kernel uevent\n"); } printf("\n"); r = sd_event_loop(event); if (r < 0) { log_error_errno(r, "Failed to run event loop: %m"); goto finalize; } r = 0; finalize: hashmap_free_free_free(arg_subsystem_filter); set_free(arg_tag_filter); return r; }
8,980
35.068273
108
c
null
systemd-main/src/udev/udevadm-settle.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ /* * Copyright Β© 2009 Canonical Ltd. * Copyright Β© 2009 Scott James Remnant <[email protected]> */ #include <getopt.h> #include <unistd.h> #include "sd-bus.h" #include "sd-event.h" #include "sd-login.h" #include "sd-messages.h" #include "bus-util.h" #include "path-util.h" #include "strv.h" #include "time-util.h" #include "udev-ctrl.h" #include "udev-util.h" #include "udevadm.h" #include "unit-def.h" #include "virt.h" static usec_t arg_timeout_usec = 120 * USEC_PER_SEC; static const char *arg_exists = NULL; static int help(void) { printf("%s settle [OPTIONS]\n\n" "Wait for pending udev events.\n\n" " -h --help Show this help\n" " -V --version Show package version\n" " -t --timeout=SEC Maximum time to wait for events\n" " -E --exit-if-exists=FILE Stop waiting if file exists\n", program_invocation_short_name); return 0; } static int parse_argv(int argc, char *argv[]) { static const struct option options[] = { { "timeout", required_argument, NULL, 't' }, { "exit-if-exists", required_argument, NULL, 'E' }, { "version", no_argument, NULL, 'V' }, { "help", no_argument, NULL, 'h' }, { "seq-start", required_argument, NULL, 's' }, /* removed */ { "seq-end", required_argument, NULL, 'e' }, /* removed */ { "quiet", no_argument, NULL, 'q' }, /* removed */ {} }; int c, r; while ((c = getopt_long(argc, argv, "t:E:Vhs:e:q", options, NULL)) >= 0) { switch (c) { case 't': r = parse_sec(optarg, &arg_timeout_usec); if (r < 0) return log_error_errno(r, "Failed to parse timeout value '%s': %m", optarg); break; case 'E': if (!path_is_valid(optarg)) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid path: %s", optarg); arg_exists = optarg; break; case 'V': return print_version(); case 'h': return help(); case 's': case 'e': case 'q': return log_info_errno(SYNTHETIC_ERRNO(EINVAL), "Option -%c no longer supported.", c); case '?': return -EINVAL; default: assert_not_reached(); } } return 1; } static int emit_deprecation_warning(void) { _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL; _cleanup_strv_free_ char **a = NULL; _cleanup_free_ char *unit = NULL; int r; r = sd_pid_get_unit(0, &unit); if (r < 0) { log_debug_errno(r, "Failed to determine unit we run in, ignoring: %m"); return 0; } if (!streq(unit, "systemd-udev-settle.service")) return 0; r = bus_connect_system_systemd(&bus); if (r < 0) log_debug_errno(r, "Failed to open connection to systemd, skipping dependency queries: %m"); else { _cleanup_strv_free_ char **b = NULL; _cleanup_free_ char *unit_path = NULL; unit_path = unit_dbus_path_from_name("systemd-udev-settle.service"); if (!unit_path) return -ENOMEM; (void) sd_bus_get_property_strv( bus, "org.freedesktop.systemd1", unit_path, "org.freedesktop.systemd1.Unit", "WantedBy", NULL, &a); (void) sd_bus_get_property_strv( bus, "org.freedesktop.systemd1", unit_path, "org.freedesktop.systemd1.Unit", "RequiredBy", NULL, &b); r = strv_extend_strv(&a, b, true); if (r < 0) return r; } if (strv_isempty(a)) /* Print a simple message if we cannot determine the dependencies */ log_notice("systemd-udev-settle.service is deprecated."); else { /* Print a longer, structured message if we can acquire the dependencies (this should be the * common case). This is hooked up with a catalog entry and everything. */ _cleanup_free_ char *t = NULL; t = strv_join(a, ", "); if (!t) return -ENOMEM; log_struct(LOG_NOTICE, LOG_MESSAGE("systemd-udev-settle.service is deprecated. Please fix %s not to pull it in.", t), "OFFENDING_UNITS=%s", t, "MESSAGE_ID=" SD_MESSAGE_SYSTEMD_UDEV_SETTLE_DEPRECATED_STR); } return 0; } static bool check(void) { int r; if (arg_exists) { if (access(arg_exists, F_OK) >= 0) return true; if (errno != ENOENT) log_warning_errno(errno, "Failed to check the existence of \"%s\", ignoring: %m", arg_exists); } /* exit if queue is empty */ r = udev_queue_is_empty(); if (r < 0) log_warning_errno(r, "Failed to check if udev queue is empty, ignoring: %m"); return r > 0; } static int on_inotify(sd_event_source *s, const struct inotify_event *event, void *userdata) { assert(s); if (check()) return sd_event_exit(sd_event_source_get_event(s), 0); return 0; } int settle_main(int argc, char *argv[], void *userdata) { _cleanup_(sd_event_unrefp) sd_event *event = NULL; int r; r = parse_argv(argc, argv); if (r <= 0) return r; if (running_in_chroot() > 0) { log_info("Running in chroot, ignoring request."); return 0; } (void) emit_deprecation_warning(); if (getuid() == 0) { _cleanup_(udev_ctrl_unrefp) UdevCtrl *uctrl = NULL; /* guarantee that the udev daemon isn't pre-processing */ r = udev_ctrl_new(&uctrl); if (r < 0) return log_error_errno(r, "Failed to create control socket for udev daemon: %m"); r = udev_ctrl_send_ping(uctrl); if (r < 0) { log_debug_errno(r, "Failed to connect to udev daemon, ignoring: %m"); return 0; } r = udev_ctrl_wait(uctrl, MAX(5 * USEC_PER_SEC, arg_timeout_usec)); if (r < 0) return log_error_errno(r, "Failed to wait for daemon to reply: %m"); } else { /* For non-privileged users, at least check if udevd is running. */ if (access("/run/udev/control", F_OK) < 0) return log_error_errno(errno, errno == ENOENT ? "systemd-udevd is not running." : "Failed to check if /run/udev/control exists: %m"); } r = sd_event_default(&event); if (r < 0) return log_error_errno(r, "Failed to get default sd-event object: %m"); r = sd_event_add_inotify(event, NULL, "/run/udev" , IN_DELETE, on_inotify, NULL); if (r < 0) return log_error_errno(r, "Failed to add inotify watch for /run/udev: %m"); if (arg_timeout_usec != USEC_INFINITY) { r = sd_event_add_time_relative(event, NULL, CLOCK_BOOTTIME, arg_timeout_usec, 0, NULL, INT_TO_PTR(-ETIMEDOUT)); if (r < 0) return log_error_errno(r, "Failed to add timer event source: %m"); } /* Check before entering the event loop, as the udev queue may be already empty. */ if (check()) return 0; r = sd_event_loop(event); if (r == -ETIMEDOUT) return log_error_errno(r, "Timed out for waiting the udev queue being empty."); if (r < 0) return log_error_errno(r, "Event loop failed: %m"); return 0; }
9,146
35.15415
121
c
null
systemd-main/src/udev/udevadm-test-builtin.c
/* SPDX-License-Identifier: GPL-2.0-or-later */ #include <errno.h> #include <getopt.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include "log.h" #include "udev-builtin.h" #include "udevadm.h" #include "udevadm-util.h" static sd_device_action_t arg_action = SD_DEVICE_ADD; static const char *arg_command = NULL; static const char *arg_syspath = NULL; static int help(void) { printf("%s test-builtin [OPTIONS] COMMAND DEVPATH\n\n" "Test a built-in command.\n\n" " -h --help Print this message\n" " -V --version Print version of the program\n\n" " -a --action=ACTION|help Set action string\n" "Commands:\n", program_invocation_short_name); udev_builtin_list(); return 0; } static int parse_argv(int argc, char *argv[]) { static const struct option options[] = { { "action", required_argument, NULL, 'a' }, { "version", no_argument, NULL, 'V' }, { "help", no_argument, NULL, 'h' }, {} }; int r, c; while ((c = getopt_long(argc, argv, "a:Vh", options, NULL)) >= 0) switch (c) { case 'a': r = parse_device_action(optarg, &arg_action); if (r < 0) return log_error_errno(r, "Invalid action '%s'", optarg); if (r == 0) return 0; break; case 'V': return print_version(); case 'h': return help(); case '?': return -EINVAL; default: assert_not_reached(); } arg_command = argv[optind++]; if (!arg_command) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Command missing."); arg_syspath = argv[optind++]; if (!arg_syspath) return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "device is missing."); return 1; } int builtin_main(int argc, char *argv[], void *userdata) { _cleanup_(udev_event_freep) UdevEvent *event = NULL; _cleanup_(sd_device_unrefp) sd_device *dev = NULL; UdevBuiltinCommand cmd; int r; log_set_max_level(LOG_DEBUG); r = parse_argv(argc, argv); if (r <= 0) return r; udev_builtin_init(); cmd = udev_builtin_lookup(arg_command); if (cmd < 0) { r = log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Unknown command '%s'", arg_command); goto finish; } r = find_device_with_action(arg_syspath, arg_action, &dev); if (r < 0) { log_error_errno(r, "Failed to open device '%s': %m", arg_syspath); goto finish; } event = udev_event_new(dev, 0, NULL, LOG_DEBUG); if (!event) { r = log_oom(); goto finish; } r = udev_builtin_run(event, cmd, arg_command, true); if (r < 0) log_debug_errno(r, "Builtin command '%s' fails: %m", arg_command); finish: udev_builtin_exit(); return r; }
3,468
29.429825
98
c