Debian Codegraph @

src/shared/tests.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <stdlib.h>
4 #include <sys/mman.h>
5 #include <unistd.h>
6
7 #include "sd-bus.h"
8 #include "sd-daemon.h"
9
10 #include "alloc-util.h"
11 #include "argv-util.h"
12 #include "bus-error.h"
13 #include "bus-locator.h"
14 #include "bus-util.h"
15 #include "bus-wait-for-jobs.h"
16 #include "cgroup-setup.h"
17 #include "cgroup-util.h"
18 #include "coredump-util.h"
19 #include "env-file.h"
20 #include "env-util.h"
21 #include "errno-util.h"
22 #include "extract-word.h"
23 #include "fd-util.h"
24 #include "fs-util.h"
25 #include "hexdecoct.h"
26 #include "log.h"
27 #include "namespace-util.h"
28 #include "path-util.h"
29 #include "pidref.h"
30 #include "process-util.h"
31 #include "random-util.h"
32 #include "rlimit-util.h"
33 #include "strv.h"
34 #include "tests.h"
35 #include "tmpfile-util.h"
36 #include "uid-range.h"
37
38 char* setup_fake_runtime_dir(void) {
39 char *t;
40
41 ASSERT_OK(mkdtemp_malloc("/tmp/fake-xdg-runtime-XXXXXX", &t));
42 ASSERT_OK(setenv("XDG_RUNTIME_DIR", t, /* overwrite= */ true));
43 return t;
44 }
45
46 static void load_testdata_env(void) {
47 static bool called = false;
48 _cleanup_free_ char *s = NULL, *d = NULL, *envpath = NULL;
49 _cleanup_strv_free_ char **pairs = NULL;
50 int r;
51
52 if (called)
53 return;
54 called = true;
55
56 ASSERT_OK(readlink_and_make_absolute("/proc/self/exe", &s));
57 ASSERT_OK(path_extract_directory(s, &d));
58 ASSERT_NOT_NULL(envpath = path_join(d, "systemd-runtest.env"));
59
60 r = load_env_file_pairs(NULL, envpath, &pairs);
61 if (r < 0) {
62 log_debug_errno(r, "Reading %s failed, ignoring: %m", envpath);
63 return;
64 }
65
66 STRV_FOREACH_PAIR(k, v, pairs)
67 ASSERT_OK(setenv(*k, *v, /* overwrite= */ false));
68 }
69
70 int get_testdata_dir(const char *suffix, char **ret) {
71 const char *dir;
72 char *p;
73
74 assert(ret);
75
76 load_testdata_env();
77
78 /* if the env var is set, use that */
79 dir = getenv("SYSTEMD_TEST_DATA");
80 if (!dir)
81 dir = SYSTEMD_TEST_DATA;
82 if (access(dir, F_OK) < 0)
83 return log_error_errno(errno, "ERROR: $SYSTEMD_TEST_DATA directory [%s] not accessible: %m", dir);
84
85 p = path_join(dir, suffix);
86 if (!p)
87 return log_oom();
88
89 *ret = p;
90 return 0;
91 }
92
93 const char* get_catalog_dir(void) {
94 const char *env;
95
96 load_testdata_env();
97
98 /* if the env var is set, use that */
99 env = getenv("SYSTEMD_CATALOG_DIR");
100 if (!env)
101 env = SYSTEMD_CATALOG_DIR;
102 if (access(env, F_OK) < 0) {
103 fprintf(stderr, "ERROR: $SYSTEMD_CATALOG_DIR directory [%s] does not exist\n", env);
104 exit(EXIT_FAILURE);
105 }
106 return env;
107 }
108
109 bool slow_tests_enabled(void) {
110 int r;
111
112 r = getenv_bool("SYSTEMD_SLOW_TESTS");
113 if (r >= 0)
114 return r;
115
116 if (r != -ENXIO)
117 log_warning_errno(r, "Cannot parse $SYSTEMD_SLOW_TESTS, ignoring.");
118 return SYSTEMD_SLOW_TESTS_DEFAULT;
119 }
120
121 void test_setup_logging(int level) {
122 log_set_assert_return_is_critical(true);
123 log_set_max_level(level);
124 log_setup();
125 }
126
127 int write_tmpfile(char *pattern, const char *contents) {
128 _cleanup_close_ int fd = -EBADF;
129
130 assert(pattern);
131 assert(contents);
132
133 fd = mkostemp_safe(pattern);
134 if (fd < 0)
135 return fd;
136
137 ssize_t l = strlen(contents);
138 errno = 0;
139 if (write(fd, contents, l) != l)
140 return errno_or_else(EIO);
141 return 0;
142 }
143
144 bool have_namespaces(void) {
145 _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
146 int r;
147
148 /* Checks whether namespaces are available. In some cases they aren't. We do this by calling unshare(), and we
149 * do so in a child process in order not to affect our own process. */
150
151 ASSERT_OK(r = pidref_safe_fork("(have_namespace)", /* flags= */ 0, &pid));
152 if (r == 0) {
153 /* child */
154 if (detach_mount_namespace() < 0)
155 _exit(EXIT_FAILURE);
156
157 _exit(EXIT_SUCCESS);
158 }
159
160 ASSERT_OK(r = pidref_wait_for_terminate_and_check("(have_namespace)", &pid, /* flags= */ 0));
161 if (r == EXIT_SUCCESS)
162 return true;
163
164 if (r == EXIT_FAILURE)
165 return false;
166
167 assert_not_reached();
168 }
169
170 bool userns_has_single_user(void) {
171 _cleanup_(uid_range_freep) UIDRange *uidrange = NULL, *gidrange = NULL;
172
173 /* Check if we're in a user namespace with only a single user mapped in. We special case this
174 * scenario in a few tests because it's the only kind of namespace that can be created unprivileged
175 * and as such happens more often than not, so we make sure to deal with it so that all tests pass
176 * in such environments. */
177
178 if (uid_range_load_userns(NULL, UID_RANGE_USERNS_INSIDE, &uidrange) < 0)
179 return false;
180
181 if (uid_range_load_userns(NULL, GID_RANGE_USERNS_INSIDE, &gidrange) < 0)
182 return false;
183
184 return uidrange->n_entries == 1 && uidrange->entries[0].nr == 1 &&
185 gidrange->n_entries == 1 && gidrange->entries[0].nr == 1;
186 }
187
188 bool can_memlock(void) {
189 /* Let's see if we can mlock() a larger blob of memory. BPF programs are charged against
190 * RLIMIT_MEMLOCK, hence let's first make sure we can lock memory at all, and skip the test if we
191 * cannot. Why not check RLIMIT_MEMLOCK explicitly? Because in container environments the
192 * RLIMIT_MEMLOCK value we see might not match the RLIMIT_MEMLOCK value actually in effect. */
193
194 void *p = mmap(NULL, CAN_MEMLOCK_SIZE, PROT_READ|PROT_WRITE, MAP_ANONYMOUS|MAP_SHARED, -1, 0);
195 if (p == MAP_FAILED)
196 return false;
197
198 bool b = mlock(p, CAN_MEMLOCK_SIZE) >= 0;
199 if (b)
200 ASSERT_OK(munlock(p, CAN_MEMLOCK_SIZE));
201
202 ASSERT_OK(munmap(p, CAN_MEMLOCK_SIZE));
203 return b;
204 }
205
206 static int allocate_scope(void) {
207 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
208 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
209 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
210 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
211 _cleanup_free_ char *scope = NULL, *cgroup_root = NULL;
212 const char *object;
213 int r;
214
215 /* Let's try to run this test in a scope of its own, with delegation turned on, so that PID 1 doesn't
216 * interfere with our cgroup management. */
217 if (cg_pid_get_path(0, &cgroup_root) >= 0 && cg_is_delegated(cgroup_root) && stderr_is_journal()) {
218 log_debug("Already running as a unit with delegated cgroup, not allocating a cgroup subroot.");
219 return 0;
220 }
221
222 if (geteuid() == 0)
223 r = sd_bus_default_system(&bus);
224 else
225 r = sd_bus_default_user(&bus);
226 if (r < 0)
227 return log_error_errno(r, "Failed to connect to system bus: %m");
228
229 r = bus_wait_for_jobs_new(bus, &w);
230 if (r < 0)
231 return log_error_errno(r, "Could not watch jobs: %m");
232
233 if (asprintf(&scope, "%s-%" PRIx64 ".scope", program_invocation_short_name, random_u64()) < 0)
234 return log_oom();
235
236 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
237 if (r < 0)
238 return bus_log_create_error(r);
239
240 /* Name and Mode */
241 r = sd_bus_message_append(m, "ss", scope, "fail");
242 if (r < 0)
243 return bus_log_create_error(r);
244
245 /* Properties */
246 r = sd_bus_message_open_container(m, 'a', "(sv)");
247 if (r < 0)
248 return bus_log_create_error(r);
249
250 r = sd_bus_message_append(m, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached());
251 if (r < 0)
252 return bus_log_create_error(r);
253
254 r = sd_bus_message_append(m, "(sv)", "Delegate", "b", 1);
255 if (r < 0)
256 return bus_log_create_error(r);
257
258 r = sd_bus_message_append(m, "(sv)", "CollectMode", "s", "inactive-or-failed");
259 if (r < 0)
260 return bus_log_create_error(r);
261
262 r = sd_bus_message_close_container(m);
263 if (r < 0)
264 return bus_log_create_error(r);
265
266 /* Auxiliary units */
267 r = sd_bus_message_append(m, "a(sa(sv))", 0);
268 if (r < 0)
269 return bus_log_create_error(r);
270
271 r = sd_bus_call(bus, m, 0, &error, &reply);
272 if (r < 0)
273 return log_error_errno(r, "Failed to start transient scope unit: %s", bus_error_message(&error, r));
274
275 r = sd_bus_message_read(reply, "o", &object);
276 if (r < 0)
277 return bus_log_parse_error(r);
278
279 r = bus_wait_for_jobs_one(w, object, BUS_WAIT_JOBS_LOG_ERROR, NULL);
280 if (r < 0)
281 return r;
282
283 return 0;
284 }
285
286 static int enter_cgroup(char **ret_cgroup, bool enter_subroot) {
287 _cleanup_free_ char *cgroup_root = NULL, *cgroup_subroot = NULL;
288 CGroupMask supported;
289 int r;
290
291 r = cg_is_available();
292 if (r < 0)
293 return r;
294 if (r == 0)
295 return log_warning_errno(SYNTHETIC_ERRNO(ENOMEDIUM), "cgroupfs v2 is not mounted.");
296
297 r = allocate_scope();
298 if (r < 0)
299 log_warning_errno(r, "Couldn't allocate a scope unit for this test, proceeding without.");
300
301 r = cg_pid_get_path(0, &cgroup_root);
302 if (IN_SET(r, -ENOMEDIUM, -ENOENT))
303 return log_warning_errno(r, "cg_pid_get_path(0, ...) failed: %m");
304 ASSERT_OK(r);
305
306 if (enter_subroot)
307 ASSERT_OK(asprintf(&cgroup_subroot, "%s/%" PRIx64, cgroup_root, random_u64()));
308 else
309 ASSERT_NOT_NULL(cgroup_subroot = strdup(cgroup_root));
310
311 ASSERT_OK(cg_mask_supported(&supported));
312
313 /* If this fails, then we don't mind as the later cgroup operations will fail too, and it's fine if
314 * we handle any errors at that point. */
315
316 r = cg_create_and_attach(cgroup_subroot, 0);
317 if (r < 0)
318 return r;
319
320 if (ret_cgroup)
321 *ret_cgroup = TAKE_PTR(cgroup_subroot);
322
323 return 0;
324 }
325
326 int enter_cgroup_subroot(char **ret_cgroup) {
327 return enter_cgroup(ret_cgroup, true);
328 }
329
330 int enter_cgroup_root(char **ret_cgroup) {
331 return enter_cgroup(ret_cgroup, false);
332 }
333
334 int define_hex_ptr_internal(const char *hex, void **name, size_t *name_len) {
335 return unhexmem_full(hex, strlen_ptr(hex), false, name, name_len);
336 }
337
338 const char* ci_environment(void) {
339 /* We return a string because we might want to provide multiple bits of information later on: not
340 * just the general CI environment type, but also whether we're sanitizing or not, etc. The caller is
341 * expected to use strstr on the returned value. */
342 static const char *ans = POINTER_MAX;
343 int r;
344
345 if (ans != POINTER_MAX)
346 return ans;
347
348 /* We allow specifying the environment with $CITYPE. Nobody uses this so far, but we are ready. */
349 const char *citype = getenv("CITYPE");
350 if (!isempty(citype))
351 return (ans = citype);
352
353 if (getenv_bool("TRAVIS") > 0)
354 return (ans = "travis");
355 if (getenv_bool("SEMAPHORE") > 0)
356 return (ans = "semaphore");
357 if (getenv_bool("GITHUB_ACTIONS") > 0)
358 return (ans = "github-actions");
359 if (getenv("AUTOPKGTEST_ARTIFACTS") || getenv("AUTOPKGTEST_TMP"))
360 return (ans = "autopkgtest");
361 if (getenv("SALSA_CI_IMAGES"))
362 return (ans = "salsa-ci");
363
364 FOREACH_STRING(var, "CI", "CONTINUOUS_INTEGRATION") {
365 /* Those vars are booleans according to Semaphore and Travis docs:
366 * https://docs.travis-ci.com/user/environment-variables/#default-environment-variables
367 * https://docs.semaphoreci.com/ci-cd-environment/environment-variables/#ci
368 */
369 r = getenv_bool(var);
370 if (r > 0)
371 return (ans = "unknown"); /* Some other unknown thing */
372 if (r == 0)
373 return (ans = NULL);
374 }
375
376 return (ans = NULL);
377 }
378
379 int run_test_table(const TestFunc *start, const TestFunc *end) {
380 _cleanup_strv_free_ char **tests = NULL;
381 int r = EXIT_SUCCESS;
382 bool ran = false;
383
384 if (!start)
385 return r;
386
387 const char *e = getenv("TESTFUNCS");
388 if (e) {
389 int n = strv_split_full(&tests, e, ":", EXTRACT_DONT_COALESCE_SEPARATORS);
390 if (n < 0)
391 return log_error_errno(n, "Failed to parse $TESTFUNCS: %m");
392 }
393
394 for (const TestFunc *t = start; t + 1 <= end; t++) {
395 if (tests && !strv_contains(tests, t->name))
396 continue;
397
398 if (t->sd_booted && sd_booted() <= 0) {
399 log_info("/* systemd not booted, skipping %s */", t->name);
400 if (t->has_ret && r == EXIT_SUCCESS)
401 r = EXIT_TEST_SKIP;
402 } else {
403 log_info("/* %s */", t->name);
404
405 if (t->has_ret) {
406 int r2 = t->f.int_func();
407 if (r == EXIT_SUCCESS)
408 r = r2;
409 } else
410 t->f.void_func();
411 }
412
413 ran = true;
414 }
415
416 if (!ran)
417 return log_error_errno(SYNTHETIC_ERRNO(ENXIO), "No matching tests found.");
418
419 return r;
420 }
421
422 void test_prepare(int argc, char *argv[], int log_level) {
423 save_argc_argv(argc, argv);
424 test_setup_logging(log_level);
425 }
426
427 /* Returns:
428 * ASSERT_SIGNAL_FORK_CHILD = We are in the child process
429 * ASSERT_SIGNAL_FORK_PARENT = We are in the parent process (signal/status stored in *ret_signal)
430 * <0 = Error (negative errno)
431 */
432 int assert_signal_internal(int *ret_signal) {
433 siginfo_t siginfo = {};
434 int r;
435
436 assert(ret_signal);
437
438 r = fork();
439 if (r < 0)
440 return -errno;
441
442 if (r == 0) {
443 /* Speed things up by never even attempting to generate a coredump */
444 (void) set_dumpable(SUID_DUMP_DISABLE);
445
446 /* But still set an rlimit just in case */
447 (void) setrlimit(RLIMIT_CORE, &RLIMIT_MAKE_CONST(0));
448 return ASSERT_SIGNAL_FORK_CHILD;
449 }
450
451 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
452 r = pidref_set_pid(&pidref, r);
453 if (r < 0)
454 return r;
455
456 r = pidref_wait_for_terminate(&pidref, &siginfo);
457 if (r < 0)
458 return r;
459
460 /* si_status means different things depending on si_code:
461 * - CLD_EXITED: si_status is the exit code
462 * - CLD_KILLED/CLD_DUMPED: si_status is the signal number that killed the process
463 * We need to return the signal number only if the child was killed by a signal. */
464 if (IN_SET(siginfo.si_code, CLD_KILLED, CLD_DUMPED))
465 *ret_signal = siginfo.si_status;
466 else
467 *ret_signal = 0;
468
469 return ASSERT_SIGNAL_FORK_PARENT;
470 }
471
472
473 void log_test_failed_internal(const char *file, int line, const char *func, const char *format, ...) {
474 va_list ap;
475
476 va_start(ap, format);
477 DISABLE_WARNING_FORMAT_NONLITERAL;
478 log_internalv(LOG_ERR, 0, file, line, func, format, ap);
479 REENABLE_WARNING;
480 va_end(ap);
481
482 abort();
483 }