Debian Codegraph @

src/shared/condition.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <fnmatch.h>
5 #include <gnu/libc-version.h>
6 #include <sys/stat.h>
7 #include <sys/utsname.h>
8 #include <time.h>
9 #include <unistd.h>
10
11 #include "sd-id128.h"
12
13 #include "alloc-util.h"
14 #include "apparmor-util.h"
15 #include "architecture.h"
16 #include "battery-util.h"
17 #include "bitfield.h"
18 #include "blockdev-util.h"
19 #include "capability-list.h"
20 #include "capability-util.h"
21 #include "cgroup-util.h"
22 #include "compare-operator.h"
23 #include "condition.h"
24 #include "confidential-virt.h"
25 #include "cpu-set-util.h"
26 #include "creds-util.h"
27 #include "efi-loader.h"
28 #include "efivars.h"
29 #include "env-file.h"
30 #include "env-util.h"
31 #include "extract-word.h"
32 #include "fd-util.h"
33 #include "fileio.h"
34 #include "fs-util.h"
35 #include "glob-util.h"
36 #include "hmac.h"
37 #include "hostname-setup.h"
38 #include "hostname-util.h"
39 #include "id128-util.h"
40 #include "ima-util.h"
41 #include "initrd-util.h"
42 #include "libaudit-util.h"
43 #include "limits-util.h"
44 #include "list.h"
45 #include "log.h"
46 #include "mountpoint-util.h"
47 #include "nulstr-util.h"
48 #include "os-util.h"
49 #include "parse-util.h"
50 #include "path-util.h"
51 #include "percent-util.h"
52 #include "pidref.h"
53 #include "proc-cmdline.h"
54 #include "process-util.h"
55 #include "psi-util.h"
56 #include "selinux-util.h"
57 #include "smack-util.h"
58 #include "special.h"
59 #include "stat-util.h"
60 #include "string-table.h"
61 #include "string-util.h"
62 #include "strv.h"
63 #include "time-util.h"
64 #include "tomoyo-util.h"
65 #include "tpm2-util.h"
66 #include "uid-classification.h"
67 #include "unaligned.h"
68 #include "user-util.h"
69 #include "virt.h"
70
71 Condition* condition_new(ConditionType type, const char *parameter, bool trigger, bool negate) {
72 Condition *c;
73
74 assert(type >= 0);
75 assert(type < _CONDITION_TYPE_MAX);
76 assert(parameter);
77
78 c = new(Condition, 1);
79 if (!c)
80 return NULL;
81
82 *c = (Condition) {
83 .type = type,
84 .trigger = trigger,
85 .negate = negate,
86 };
87
88 c->parameter = strdup(parameter);
89 if (!c->parameter)
90 return mfree(c);
91
92 return c;
93 }
94
95 Condition* condition_free(Condition *c) {
96 assert(c);
97
98 free(c->parameter);
99 return mfree(c);
100 }
101
102 Condition* condition_free_list_type(Condition *head, ConditionType type) {
103 LIST_FOREACH(conditions, c, head)
104 if (type < 0 || c->type == type) {
105 LIST_REMOVE(conditions, head, c);
106 condition_free(c);
107 }
108
109 assert(type >= 0 || !head);
110 return head;
111 }
112
113 static int condition_test_kernel_command_line(Condition *c, char **env) {
114 _cleanup_strv_free_ char **args = NULL;
115 int r;
116
117 assert(c);
118 assert(c->parameter);
119 assert(c->type == CONDITION_KERNEL_COMMAND_LINE);
120
121 r = proc_cmdline_strv(&args);
122 if (r < 0)
123 return r;
124
125 bool equal = strchr(c->parameter, '=');
126
127 STRV_FOREACH(word, args) {
128 bool found;
129
130 if (equal)
131 found = streq(*word, c->parameter);
132 else {
133 const char *f;
134
135 f = startswith(*word, c->parameter);
136 found = f && IN_SET(*f, 0, '=');
137 }
138
139 if (found)
140 return true;
141 }
142
143 return false;
144 }
145
146 static int condition_test_credential(Condition *c, char **env) {
147 int r;
148
149 assert(c);
150 assert(c->parameter);
151 assert(c->type == CONDITION_CREDENTIAL);
152
153 /* For now we'll do a very simple existence check and are happy with either a regular or an encrypted
154 * credential. Given that we check the syntax of the argument we have the option to later maybe allow
155 * contents checks too without breaking compatibility, but for now let's be minimalistic. */
156
157 if (!credential_name_valid(c->parameter)) /* credentials with invalid names do not exist */
158 return false;
159
160 int (*gd)(const char **ret);
161 FOREACH_ARGUMENT(gd, get_credentials_dir, get_encrypted_credentials_dir) {
162 _cleanup_free_ char *j = NULL;
163 const char *cd;
164
165 r = gd(&cd);
166 if (r == -ENXIO) /* no env var set */
167 continue;
168 if (r < 0)
169 return r;
170
171 j = path_join(cd, c->parameter);
172 if (!j)
173 return -ENOMEM;
174
175 r = access_nofollow(j, F_OK);
176 if (r >= 0)
177 return true; /* yay! */
178 if (r != -ENOENT)
179 return r;
180
181 /* not found in this dir */
182 }
183
184 return false;
185 }
186
187 static int condition_test_version_cmp(const char *condition, const char *ver) {
188 CompareOperator operator;
189 bool first = true;
190
191 assert(ver);
192
193 for (const char *p = condition;;) {
194 _cleanup_free_ char *word = NULL;
195 const char *s;
196 int r;
197
198 r = extract_first_word(&p, &word, NULL, EXTRACT_UNQUOTE);
199 if (r < 0)
200 return log_debug_errno(r, "Failed to parse condition string \"%s\": %m", p);
201 if (r == 0)
202 break;
203
204 s = strstrip(word);
205 operator = parse_compare_operator(&s, COMPARE_ALLOW_FNMATCH|COMPARE_EQUAL_BY_STRING);
206 if (operator < 0) /* No prefix? Then treat as glob string */
207 operator = COMPARE_FNMATCH_EQUAL;
208
209 s += strspn(s, WHITESPACE);
210 if (isempty(s)) {
211 if (first) {
212 /* For backwards compatibility, allow whitespace between the operator and
213 * value, without quoting, but only in the first expression. */
214 word = mfree(word);
215 r = extract_first_word(&p, &word, NULL, 0);
216 if (r < 0)
217 return log_debug_errno(r, "Failed to parse condition string \"%s\": %m", p);
218 if (r == 0)
219 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected end of expression: %s", p);
220 s = word;
221 } else
222 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected end of expression: %s", p);
223 }
224
225 r = version_or_fnmatch_compare(operator, ver, s);
226 if (r < 0)
227 return r;
228 if (!r)
229 return false;
230
231 first = false;
232 }
233
234 return true;
235 }
236
237 static int condition_test_version(Condition *c, char **env) {
238 int r;
239
240 assert(c);
241 assert(c->type == CONDITION_VERSION);
242
243 /* An empty condition is considered true. */
244 if (isempty(c->parameter))
245 return true;
246
247 const char *p = c->parameter;
248 _cleanup_free_ char *word = NULL;
249 r = extract_first_word(&p, &word, COMPARE_OPERATOR_WITH_FNMATCH_CHARS WHITESPACE,
250 EXTRACT_DONT_COALESCE_SEPARATORS|EXTRACT_RETAIN_SEPARATORS);
251 if (r < 0)
252 return log_debug_errno(r, "Failed to parse compare predicate \"%s\": %m", p);
253 if (r == 0)
254 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Missing right operand in condition: %s", c->parameter);
255
256 if (streq(word, "systemd"))
257 return condition_test_version_cmp(p, STRINGIFY(PROJECT_VERSION));
258
259 if (streq(word, "glibc"))
260 return condition_test_version_cmp(p, gnu_get_libc_version());
261
262 /* if no predicate has been set, default to "kernel" and use the whole parameter as condition */
263 if (!streq(word, "kernel"))
264 p = c->parameter;
265
266 struct utsname u;
267 assert_se(uname(&u) >= 0);
268 return condition_test_version_cmp(p, u.release);
269 }
270
271 static int condition_test_osrelease(Condition *c, char **env) {
272 int r;
273
274 assert(c);
275 assert(c->type == CONDITION_OS_RELEASE);
276
277 for (const char *parameter = ASSERT_PTR(c->parameter);;) {
278 _cleanup_free_ char *key = NULL, *condition = NULL, *actual_value = NULL;
279 CompareOperator operator;
280 const char *word;
281
282 r = extract_first_word(&parameter, &condition, NULL, EXTRACT_UNQUOTE);
283 if (r < 0)
284 return log_debug_errno(r, "Failed to parse parameter: %m");
285 if (r == 0)
286 break;
287
288 /* parse_compare_operator() needs the string to start with the comparators */
289 word = condition;
290 r = extract_first_word(&word, &key, COMPARE_OPERATOR_WITH_FNMATCH_CHARS, EXTRACT_RETAIN_SEPARATORS);
291 if (r < 0)
292 return log_debug_errno(r, "Failed to parse parameter: %m");
293 /* The os-release spec mandates env-var-like key names */
294 if (r == 0 || isempty(word) || !env_name_is_valid(key))
295 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
296 "Failed to parse parameter, key/value format expected.");
297
298 /* Do not allow whitespace after the separator, as that's not a valid os-release format */
299 operator = parse_compare_operator(&word, COMPARE_ALLOW_FNMATCH|COMPARE_EQUAL_BY_STRING);
300 if (operator < 0 || isempty(word) || strchr(WHITESPACE, *word) != NULL)
301 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
302 "Failed to parse parameter, key/value format expected.");
303
304 r = parse_os_release(NULL, key, &actual_value);
305 if (r < 0)
306 return log_debug_errno(r, "Failed to parse os-release: %m");
307
308 /* If not found, use "". This means that missing and empty assignments
309 * in the file have the same result. */
310 r = version_or_fnmatch_compare(operator, strempty(actual_value), word);
311 if (r < 0)
312 return r;
313 if (!r)
314 return false;
315 }
316
317 return true;
318 }
319
320 static int condition_test_machine_tag(Condition *c, char **env) {
321 int r;
322
323 assert(c);
324 assert(c->parameter);
325 assert(c->type == CONDITION_MACHINE_TAG);
326
327 _cleanup_free_ char *tags = NULL;
328 r = parse_env_file(
329 /* f= */ NULL, etc_machine_info(),
330 "TAGS", &tags);
331 if (r < 0 && r != -ENOENT) {
332 log_debug_errno(r, "Failed to read /etc/machine-info, ignoring: %m");
333 return false;
334 }
335
336 /* Silently ignore invalid tags, matching the Tags D-Bus property */
337 _cleanup_strv_free_ char **l = NULL;
338 r = machine_tags_from_string(tags, /* graceful= */ true, &l);
339 if (r < 0) {
340 log_debug_errno(r, "Failed to parse machine tags '%s', ignoring: %m", tags);
341 return false;
342 }
343
344 STRV_FOREACH(i, l)
345 if (fnmatch(c->parameter, *i, /* flags= */ 0) == 0)
346 return true;
347
348 return false;
349 }
350
351 static int condition_test_memory(Condition *c, char **env) {
352 CompareOperator operator;
353 uint64_t m, k;
354 const char *p;
355 int r;
356
357 assert(c);
358 assert(c->parameter);
359 assert(c->type == CONDITION_MEMORY);
360
361 m = physical_memory();
362
363 p = c->parameter;
364 operator = parse_compare_operator(&p, 0);
365 if (operator < 0)
366 operator = COMPARE_GREATER_OR_EQUAL; /* default to >= check, if nothing is specified. */
367
368 r = parse_size(p, 1024, &k);
369 if (r < 0)
370 return log_debug_errno(r, "Failed to parse size '%s': %m", p);
371
372 return test_order(CMP(m, k), operator);
373 }
374
375 static int condition_test_cpus(Condition *c, char **env) {
376 CompareOperator operator;
377 const char *p;
378 unsigned k;
379 int r, n;
380
381 assert(c);
382 assert(c->parameter);
383 assert(c->type == CONDITION_CPUS);
384
385 n = cpus_in_affinity_mask();
386 if (n < 0)
387 return log_debug_errno(n, "Failed to determine CPUs in affinity mask: %m");
388
389 p = c->parameter;
390 operator = parse_compare_operator(&p, 0);
391 if (operator < 0)
392 operator = COMPARE_GREATER_OR_EQUAL; /* default to >= check, if nothing is specified. */
393
394 r = safe_atou(p, &k);
395 if (r < 0)
396 return log_debug_errno(r, "Failed to parse number of CPUs: %m");
397
398 return test_order(CMP((unsigned) n, k), operator);
399 }
400
401 static int condition_test_user(Condition *c, char **env) {
402 uid_t id;
403 int r;
404
405 assert(c);
406 assert(c->parameter);
407 assert(c->type == CONDITION_USER);
408
409 /* Do the quick&easy comparisons first, and only parse the UID later. */
410 if (streq(c->parameter, "root"))
411 return getuid() == 0 || geteuid() == 0;
412 if (streq(c->parameter, NOBODY_USER_NAME))
413 return getuid() == UID_NOBODY || geteuid() == UID_NOBODY;
414 if (streq(c->parameter, "@system"))
415 return uid_is_system(getuid()) || uid_is_system(geteuid());
416
417 r = parse_uid(c->parameter, &id);
418 if (r >= 0)
419 return id == getuid() || id == geteuid();
420
421 if (getpid_cached() == 1) /* We already checked for "root" above, and we know that
422 * PID 1 is running as root, hence we know it cannot match. */
423 return false;
424
425 /* getusername_malloc() may do an nss lookup, which is not allowed in PID 1. */
426 _cleanup_free_ char *username = getusername_malloc();
427 if (!username)
428 return -ENOMEM;
429
430 if (streq(username, c->parameter))
431 return 1;
432
433 r = get_user_creds(c->parameter, USER_CREDS_ALLOW_MISSING, NULL, &id, NULL, NULL, NULL);
434 if (r < 0)
435 return 0;
436
437 return id == getuid() || id == geteuid();
438 }
439
440 static int condition_test_control_group_controller(Condition *c, char **env) {
441 CGroupMask system_mask, wanted_mask;
442 int r;
443
444 assert(c);
445 assert(c->parameter);
446 assert(c->type == CONDITION_CONTROL_GROUP_CONTROLLER);
447
448 if (streq(c->parameter, "v2"))
449 return true;
450 if (streq(c->parameter, "v1"))
451 return false;
452
453 r = cg_mask_supported(&system_mask);
454 if (r < 0)
455 return log_debug_errno(r, "Failed to determine supported controllers: %m");
456
457 r = cg_mask_from_string(c->parameter, &wanted_mask);
458 if (r < 0 || wanted_mask <= 0) {
459 /* This won't catch the case that we have an unknown controller
460 * mixed in with valid ones -- these are only assessed on the
461 * validity of the valid controllers found. */
462 log_debug("Failed to parse cgroup string: %s", c->parameter);
463 return true;
464 }
465
466 return FLAGS_SET(system_mask, wanted_mask);
467 }
468
469 static int condition_test_group(Condition *c, char **env) {
470 gid_t id;
471 int r;
472
473 assert(c);
474 assert(c->parameter);
475 assert(c->type == CONDITION_GROUP);
476
477 r = parse_gid(c->parameter, &id);
478 if (r >= 0)
479 return in_gid(id);
480
481 /* Avoid any NSS lookups if we are PID1 */
482 if (getpid_cached() == 1)
483 return streq(c->parameter, "root");
484
485 return in_group(c->parameter) > 0;
486 }
487
488 static int condition_test_virtualization(Condition *c, char **env) {
489 Virtualization v;
490 int b;
491
492 assert(c);
493 assert(c->parameter);
494 assert(c->type == CONDITION_VIRTUALIZATION);
495
496 if (streq(c->parameter, "private-users"))
497 return running_in_userns();
498
499 v = detect_virtualization();
500 if (v < 0)
501 return v;
502
503 /* First, compare with yes/no */
504 b = parse_boolean(c->parameter);
505 if (b >= 0)
506 return b == (v != VIRTUALIZATION_NONE);
507
508 /* Then, compare categorization */
509 if (streq(c->parameter, "vm"))
510 return VIRTUALIZATION_IS_VM(v);
511
512 if (streq(c->parameter, "container"))
513 return VIRTUALIZATION_IS_CONTAINER(v);
514
515 /* Finally compare id */
516 return v != VIRTUALIZATION_NONE && streq(c->parameter, virtualization_to_string(v));
517 }
518
519 static int condition_test_architecture(Condition *c, char **env) {
520 Architecture a, b;
521
522 assert(c);
523 assert(c->parameter);
524 assert(c->type == CONDITION_ARCHITECTURE);
525
526 a = uname_architecture();
527 if (a < 0)
528 return a;
529
530 if (streq(c->parameter, "native"))
531 b = native_architecture();
532 else {
533 b = architecture_from_string(c->parameter);
534 if (b < 0) /* unknown architecture? Then it's definitely not ours */
535 return false;
536 }
537
538 return a == b;
539 }
540
541 #define DTCOMPAT_FILE "/proc/device-tree/compatible"
542 static int condition_test_firmware_devicetree_compatible(const char *dtcarg) {
543 int r;
544 _cleanup_free_ char *dtcompat = NULL;
545 _cleanup_strv_free_ char **dtcompatlist = NULL;
546 size_t size;
547
548 r = read_full_virtual_file(DTCOMPAT_FILE, &dtcompat, &size);
549 if (r < 0) {
550 /* if the path doesn't exist it is incompatible */
551 if (r != -ENOENT)
552 log_debug_errno(r, "Failed to open '%s', assuming machine is incompatible: %m", DTCOMPAT_FILE);
553 return false;
554 }
555
556 /* Not sure this can happen, but play safe. */
557 if (size == 0) {
558 log_debug("%s has zero length, assuming machine is incompatible", DTCOMPAT_FILE);
559 return false;
560 }
561
562 /* /proc/device-tree/compatible consists of one or more strings, each ending in '\0'.
563 * So the last character in dtcompat must be a '\0'. */
564 if (dtcompat[size - 1] != '\0') {
565 log_debug("%s is in an unknown format, assuming machine is incompatible", DTCOMPAT_FILE);
566 return false;
567 }
568
569 dtcompatlist = strv_parse_nulstr(dtcompat, size);
570 if (!dtcompatlist)
571 return -ENOMEM;
572
573 return strv_contains(dtcompatlist, dtcarg);
574 }
575
576 static int condition_test_firmware_smbios_field(const char *expression) {
577 _cleanup_free_ char *field = NULL, *expected_value = NULL, *actual_value = NULL;
578 CompareOperator operator;
579 int r;
580
581 assert(expression);
582
583 /* Parse SMBIOS field */
584 r = extract_first_word(&expression, &field, COMPARE_OPERATOR_WITH_FNMATCH_CHARS, EXTRACT_RETAIN_SEPARATORS);
585 if (r < 0)
586 return r;
587 if (r == 0 || isempty(expression))
588 return -EINVAL;
589
590 /* Remove trailing spaces from SMBIOS field */
591 delete_trailing_chars(field, WHITESPACE);
592
593 /* Parse operator */
594 operator = parse_compare_operator(&expression, COMPARE_ALLOW_FNMATCH|COMPARE_EQUAL_BY_STRING);
595 if (operator < 0)
596 return operator;
597
598 /* Parse expected value */
599 r = extract_first_word(&expression, &expected_value, NULL, EXTRACT_UNQUOTE);
600 if (r < 0)
601 return r;
602 if (r == 0 || !isempty(expression))
603 return -EINVAL;
604
605 /* Read actual value from sysfs */
606 if (!filename_is_valid(field))
607 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid SMBIOS field name.");
608
609 const char *p = strjoina("/sys/class/dmi/id/", field);
610 r = read_virtual_file(p, SIZE_MAX, &actual_value, NULL);
611 if (r < 0) {
612 log_debug_errno(r, "Failed to read %s: %m", p);
613 if (r == -ENOENT)
614 return false;
615 return r;
616 }
617
618 /* Remove trailing newline */
619 delete_trailing_chars(actual_value, WHITESPACE);
620
621 /* Finally compare actual and expected value */
622 return version_or_fnmatch_compare(operator, actual_value, expected_value);
623 }
624
625 static int condition_test_firmware(Condition *c, char **env) {
626 sd_char *arg;
627 int r;
628
629 assert(c);
630 assert(c->parameter);
631 assert(c->type == CONDITION_FIRMWARE);
632
633 if (streq(c->parameter, "device-tree")) {
634 if (access("/sys/firmware/devicetree/", F_OK) < 0) {
635 if (errno != ENOENT)
636 log_debug_errno(errno, "Unexpected error when checking for /sys/firmware/devicetree/: %m");
637 return false;
638 } else
639 return true;
640 } else if ((arg = startswith(c->parameter, "device-tree-compatible("))) {
641 _cleanup_free_ char *dtc_arg = NULL;
642 char *end;
643
644 end = strrchr(arg, ')');
645 if (!end || *(end + 1) != '\0') {
646 log_debug("Malformed ConditionFirmware=%s", c->parameter);
647 return false;
648 }
649
650 dtc_arg = strndup(arg, end - arg);
651 if (!dtc_arg)
652 return -ENOMEM;
653
654 return condition_test_firmware_devicetree_compatible(dtc_arg);
655 } else if (streq(c->parameter, "uefi"))
656 return is_efi_boot();
657 else if ((arg = startswith(c->parameter, "smbios-field("))) {
658 _cleanup_free_ char *smbios_arg = NULL;
659 char *end;
660
661 end = strrchr(arg, ')');
662 if (!end || *(end + 1) != '\0')
663 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Malformed ConditionFirmware=%s.", c->parameter);
664
665 smbios_arg = strndup(arg, end - arg);
666 if (!smbios_arg)
667 return log_oom_debug();
668
669 r = condition_test_firmware_smbios_field(smbios_arg);
670 if (r < 0)
671 return log_debug_errno(r, "Malformed ConditionFirmware=%s: %m", c->parameter);
672 return r;
673 } else {
674 log_debug("Unsupported Firmware condition \"%s\"", c->parameter);
675 return false;
676 }
677 }
678
679 static int condition_test_host(Condition *c, char **env) {
680 _cleanup_free_ char *h = NULL;
681 int r;
682
683 assert(c);
684 assert(c->parameter);
685 assert(c->type == CONDITION_HOST);
686
687 sd_id128_t x;
688 if (sd_id128_from_string(c->parameter, &x) >= 0) {
689 static const struct {
690 const char *name;
691 int (*get_id)(sd_id128_t *ret);
692 } table[] = {
693 { "machine ID", sd_id128_get_machine },
694 { "boot ID", sd_id128_get_boot },
695 { "product UUID", id128_get_product },
696 };
697
698 /* If this is a UUID, check if this matches the machine ID, boot ID or product UUID */
699 FOREACH_ELEMENT(i, table) {
700 sd_id128_t y;
701
702 r = i->get_id(&y);
703 if (r < 0)
704 log_debug_errno(r, "Failed to get %s, ignoring: %m", i->name);
705 else if (sd_id128_equal(x, y))
706 return true;
707 }
708
709 /* Fall through, also allow setups where people set hostnames to UUIDs. Kinda weird, but no
710 * reason not to allow that */
711 }
712
713 h = gethostname_malloc();
714 if (!h)
715 return -ENOMEM;
716
717 r = fnmatch(c->parameter, h, FNM_CASEFOLD);
718 if (r == FNM_NOMATCH)
719 return false;
720 if (r != 0)
721 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "fnmatch() failed.");
722
723 return true;
724 }
725
726 static uint32_t condition_fraction_value(sd_id128_t machine_id, const char *text) {
727 /* Maps (machine ID, text) to a value uniformly distributed over [0, UINT32_MAX], via
728 * HMAC-SHA256 keyed by the machine ID over 'text'. The machine ID keys the hash, so each
729 * machine lands at a stable but unpredictable point; 'text' selects the subset, so that
730 * distinct rollouts (different texts) pick independent subsets of a fleet. */
731 assert(text);
732
733 uint8_t res[SHA256_DIGEST_SIZE];
734 hmac_sha256(&machine_id, sizeof(machine_id), text, strlen(text), res);
735
736 return unaligned_read_le32(res);
737 }
738
739 static int condition_test_fraction(Condition *c, char **env) {
740 int r;
741
742 assert(c);
743 assert(c->parameter);
744 assert(c->type == CONDITION_FRACTION);
745
746 /* Expected syntax: "[TAG ]PERCENT". The percentage is mandatory; the optional leading tag is used as
747 * a hash salt, so that distinct staged rollouts select independent subsets of a fleet. The condition
748 * is true for approximately PERCENT of all machines — on a given machine when its derived value
749 * falls below the threshold. This is useful for staged rollouts: hand the same unit to a whole fleet
750 * and only a fraction of it will be enabled, with each machine deciding locally and stably (no
751 * coordination required). */
752
753 const char *p = c->parameter;
754 _cleanup_free_ char *first = NULL, *second = NULL;
755
756 r = extract_first_word(&p, &first, /* separators=*/ NULL, /* flags= */ 0);
757 if (r < 0)
758 return log_debug_errno(r, "Failed to parse ConditionFraction=%s: %m", c->parameter);
759 if (r == 0)
760 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "ConditionFraction= value is empty.");
761
762 r = extract_first_word(&p, &second, /* separators= */ NULL, /* flags= */ 0);
763 if (r < 0)
764 return log_debug_errno(r, "Failed to parse ConditionFraction=%s: %m", c->parameter);
765
766 const char *tag, *percent;
767 if (r == 0) {
768 /* A single field: it's the percentage, with no tag. */
769 tag = NULL;
770 percent = first;
771 } else if (isempty(p)) {
772 /* Two fields: TAG followed by PERCENT. */
773 tag = first;
774 percent = second;
775 } else
776 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
777 "ConditionFraction=%s has trailing garbage.", c->parameter);
778
779 int permyriad = parse_permyriad(percent);
780 if (permyriad < 0)
781 return log_debug_errno(permyriad, "Failed to parse percentage in ConditionFraction=%s: %m", c->parameter);
782 if (permyriad == 0)
783 return false; /* 0% → matches no machine */
784 if (permyriad >= 10000)
785 return true; /* 100% → matches every machine */
786
787 /* Implicitly prefix the tag with a fixed namespace string, so that an absent or empty tag
788 * still yields a well-defined, non-trivial value (never the HMAC of the empty string), and
789 * so this value space is domain-separated from other uses of the machine ID. */
790 _cleanup_free_ char *text = strjoin("systemd-fraction-", strempty(tag));
791 if (!text)
792 return log_oom_debug();
793
794 sd_id128_t mid;
795 r = sd_id128_get_machine(&mid);
796 if (r < 0)
797 return log_debug_errno(r, "Failed to get machine ID for ConditionFraction=: %m");
798
799 return condition_fraction_value(mid, text) < UINT32_SCALE_FROM_PERMYRIAD(permyriad);
800 }
801
802 static int condition_test_ac_power(Condition *c, char **env) {
803 int r;
804
805 assert(c);
806 assert(c->parameter);
807 assert(c->type == CONDITION_AC_POWER);
808
809 r = parse_boolean(c->parameter);
810 if (r < 0)
811 return r;
812
813 return (on_ac_power() != 0) == !!r;
814 }
815
816 static int has_tpm2(void) {
817 /* Checks whether the kernel has the TPM subsystem enabled and the firmware reports support. Note
818 * we don't check for actual TPM devices, since we might not have loaded the driver for it yet, i.e.
819 * during early boot where we very likely want to use this condition check).
820 *
821 * Note that we don't check if we ourselves are built with TPM2 support here! */
822
823 return FLAGS_SET(tpm2_support_full(TPM2_SUPPORT_SUBSYSTEM|TPM2_SUPPORT_FIRMWARE), TPM2_SUPPORT_SUBSYSTEM|TPM2_SUPPORT_FIRMWARE);
824 }
825
826 static int condition_test_security(Condition *c, char **env) {
827 assert(c);
828 assert(c->parameter);
829 assert(c->type == CONDITION_SECURITY);
830
831 if (streq(c->parameter, "selinux"))
832 return mac_selinux_use();
833 if (streq(c->parameter, "smack"))
834 return mac_smack_use();
835 if (streq(c->parameter, "apparmor"))
836 return mac_apparmor_use();
837 if (streq(c->parameter, "audit"))
838 return use_audit();
839 if (streq(c->parameter, "ima"))
840 return use_ima();
841 if (streq(c->parameter, "tomoyo"))
842 return mac_tomoyo_use();
843 if (streq(c->parameter, "uefi-secureboot"))
844 return is_efi_secure_boot();
845 if (streq(c->parameter, "tpm2"))
846 return has_tpm2();
847 if (streq(c->parameter, "cvm"))
848 return detect_confidential_virtualization() > 0;
849 if (streq(c->parameter, "measured-uki"))
850 return efi_measured_uki(LOG_DEBUG);
851 if (streq(c->parameter, "measured-os"))
852 return efi_measured_os(LOG_DEBUG);
853
854 return false;
855 }
856
857 static int condition_test_capability(Condition *c, char **env) {
858 int r;
859
860 assert(c);
861 assert(c->parameter);
862 assert(c->type == CONDITION_CAPABILITY);
863
864 /* If it's an invalid capability, we don't have it */
865 int value = capability_from_name(c->parameter);
866 if (value < 0)
867 return -EINVAL;
868
869 CapabilityQuintet q;
870 r = pidref_get_capability(&PIDREF_MAKE_FROM_PID(getpid_cached()), &q);
871 if (r < 0)
872 return r;
873
874 return BIT_SET(q.bounding, value);
875 }
876
877 static int condition_test_needs_update(Condition *c, char **env) {
878 struct stat usr, other;
879 const char *p;
880 bool b;
881 int r;
882
883 assert(c);
884 assert(c->parameter);
885 assert(c->type == CONDITION_NEEDS_UPDATE);
886
887 r = proc_cmdline_get_bool("systemd.condition_needs_update", /* flags= */ 0, &b);
888 if (r < 0)
889 log_debug_errno(r, "Failed to parse systemd.condition_needs_update= kernel command line argument, ignoring: %m");
890 if (r > 0)
891 return b;
892
893 if (in_initrd()) {
894 log_debug("We are in an initrd, not doing any updates.");
895 return false;
896 }
897
898 if (!path_is_absolute(c->parameter)) {
899 log_debug("Specified condition parameter '%s' is not absolute, assuming an update is needed.", c->parameter);
900 return true;
901 }
902
903 /* If the file system is read-only we shouldn't suggest an update */
904 r = path_is_read_only_fs(c->parameter);
905 if (r < 0)
906 log_debug_errno(r, "Failed to determine if '%s' is read-only, ignoring: %m", c->parameter);
907 if (r > 0)
908 return false;
909
910 /* Any other failure means we should allow the condition to be true, so that we rather invoke too
911 * many update tools than too few. */
912
913 p = strjoina(c->parameter, "/.updated");
914 if (lstat(p, &other) < 0) {
915 if (errno != ENOENT)
916 log_debug_errno(errno, "Failed to stat() '%s', assuming an update is needed: %m", p);
917 return true;
918 }
919
920 if (lstat("/usr/", &usr) < 0) {
921 log_debug_errno(errno, "Failed to stat() /usr/, assuming an update is needed: %m");
922 return true;
923 }
924
925 /*
926 * First, compare seconds as they are always accurate...
927 */
928 if (usr.st_mtim.tv_sec != other.st_mtim.tv_sec)
929 return usr.st_mtim.tv_sec > other.st_mtim.tv_sec;
930
931 /*
932 * ...then compare nanoseconds.
933 *
934 * A false positive is only possible when /usr's nanoseconds > 0
935 * (otherwise /usr cannot be strictly newer than the target file)
936 * AND the target file's nanoseconds == 0
937 * (otherwise the filesystem supports nsec timestamps, see stat(2)).
938 */
939 if (usr.st_mtim.tv_nsec == 0 || other.st_mtim.tv_nsec > 0)
940 return usr.st_mtim.tv_nsec > other.st_mtim.tv_nsec;
941
942 _cleanup_free_ char *timestamp_str = NULL;
943 r = parse_env_file(NULL, p, "TIMESTAMP_NSEC", &timestamp_str);
944 if (r < 0) {
945 log_debug_errno(r, "Failed to parse timestamp file '%s', using mtime: %m", p);
946 return true;
947 }
948 if (isempty(timestamp_str)) {
949 log_debug("No data in timestamp file '%s', using mtime.", p);
950 return true;
951 }
952
953 uint64_t timestamp;
954 r = safe_atou64(timestamp_str, &timestamp);
955 if (r < 0) {
956 log_debug_errno(r, "Failed to parse timestamp value '%s' in file '%s', using mtime: %m", timestamp_str, p);
957 return true;
958 }
959
960 return timespec_load_nsec(&usr.st_mtim) > timestamp;
961 }
962
963 static bool in_first_boot(void) {
964 static int first_boot = -1;
965 int r;
966
967 if (first_boot >= 0)
968 return first_boot;
969
970 const char *e = secure_getenv("SYSTEMD_FIRST_BOOT");
971 if (e) {
972 r = parse_boolean(e);
973 if (r < 0)
974 log_debug_errno(r, "Failed to parse $SYSTEMD_FIRST_BOOT, ignoring: %m");
975 else
976 return (first_boot = r);
977 }
978
979 r = RET_NERRNO(access("/run/systemd/first-boot", F_OK));
980 if (r < 0 && r != -ENOENT)
981 log_debug_errno(r, "Failed to check if /run/systemd/first-boot exists, assuming no: %m");
982 return r >= 0;
983 }
984
985 static int condition_test_first_boot(Condition *c, char **env) {
986 int r;
987
988 assert(c);
989 assert(c->parameter);
990 assert(c->type == CONDITION_FIRST_BOOT);
991
992 // TODO: Parse c->parameter immediately when reading the config.
993 // Apply negation when parsing too.
994
995 r = parse_boolean(c->parameter);
996 if (r < 0)
997 return r;
998
999 return in_first_boot() == r;
1000 }
1001
1002 static int condition_test_environment(Condition *c, char **env) {
1003 bool equal;
1004
1005 assert(c);
1006 assert(c->parameter);
1007 assert(c->type == CONDITION_ENVIRONMENT);
1008
1009 equal = strchr(c->parameter, '=');
1010
1011 STRV_FOREACH(i, env) {
1012 bool found;
1013
1014 if (equal)
1015 found = streq(c->parameter, *i);
1016 else {
1017 const char *f;
1018
1019 f = startswith(*i, c->parameter);
1020 found = f && IN_SET(*f, 0, '=');
1021 }
1022
1023 if (found)
1024 return true;
1025 }
1026
1027 return false;
1028 }
1029
1030 static int condition_test_path_exists(Condition *c, char **env) {
1031 assert(c);
1032 assert(c->parameter);
1033 assert(c->type == CONDITION_PATH_EXISTS);
1034
1035 return access(c->parameter, F_OK) >= 0;
1036 }
1037
1038 static int condition_test_path_exists_glob(Condition *c, char **env) {
1039 assert(c);
1040 assert(c->parameter);
1041 assert(c->type == CONDITION_PATH_EXISTS_GLOB);
1042
1043 return glob_exists(c->parameter) > 0;
1044 }
1045
1046 static int condition_test_path_is_directory(Condition *c, char **env) {
1047 assert(c);
1048 assert(c->parameter);
1049 assert(c->type == CONDITION_PATH_IS_DIRECTORY);
1050
1051 return is_dir(c->parameter, true) > 0;
1052 }
1053
1054 static int condition_test_path_is_symbolic_link(Condition *c, char **env) {
1055 assert(c);
1056 assert(c->parameter);
1057 assert(c->type == CONDITION_PATH_IS_SYMBOLIC_LINK);
1058
1059 return is_symlink(c->parameter) > 0;
1060 }
1061
1062 static int condition_test_path_is_mount_point(Condition *c, char **env) {
1063 assert(c);
1064 assert(c->parameter);
1065 assert(c->type == CONDITION_PATH_IS_MOUNT_POINT);
1066
1067 return path_is_mount_point_full(c->parameter, /* root= */ NULL, AT_SYMLINK_FOLLOW) > 0;
1068 }
1069
1070 static int condition_test_path_is_read_write(Condition *c, char **env) {
1071 int r;
1072
1073 assert(c);
1074 assert(c->parameter);
1075 assert(c->type == CONDITION_PATH_IS_READ_WRITE);
1076
1077 r = path_is_read_only_fs(c->parameter);
1078
1079 return r <= 0 && r != -ENOENT;
1080 }
1081
1082 static int condition_test_cpufeature(Condition *c, char **env) {
1083 assert(c);
1084 assert(c->parameter);
1085 assert(c->type == CONDITION_CPU_FEATURE);
1086
1087 return has_cpu_with_flag(ascii_strlower(c->parameter));
1088 }
1089
1090 static int condition_test_path_is_encrypted(Condition *c, char **env) {
1091 int r;
1092
1093 assert(c);
1094 assert(c->parameter);
1095 assert(c->type == CONDITION_PATH_IS_ENCRYPTED);
1096
1097 r = path_is_encrypted(c->parameter);
1098 if (r < 0 && r != -ENOENT)
1099 log_debug_errno(r, "Failed to determine if '%s' is encrypted: %m", c->parameter);
1100
1101 return r > 0;
1102 }
1103
1104 static int condition_test_path_is_socket(Condition *c, char **env) {
1105 assert(c);
1106 assert(c->parameter);
1107 assert(c->type == CONDITION_PATH_IS_SOCKET);
1108
1109 return is_socket(c->parameter) > 0;
1110 }
1111
1112 static int condition_test_directory_not_empty(Condition *c, char **env) {
1113 int r;
1114
1115 assert(c);
1116 assert(c->parameter);
1117 assert(c->type == CONDITION_DIRECTORY_NOT_EMPTY);
1118
1119 r = dir_is_empty(c->parameter, /* ignore_hidden_or_backup= */ true);
1120 return r <= 0 && !IN_SET(r, -ENOENT, -ENOTDIR);
1121 }
1122
1123 static int condition_test_file_not_empty(Condition *c, char **env) {
1124 struct stat st;
1125
1126 assert(c);
1127 assert(c->parameter);
1128 assert(c->type == CONDITION_FILE_NOT_EMPTY);
1129
1130 return (stat(c->parameter, &st) >= 0 &&
1131 S_ISREG(st.st_mode) &&
1132 st.st_size > 0);
1133 }
1134
1135 static int condition_test_file_is_executable(Condition *c, char **env) {
1136 struct stat st;
1137
1138 assert(c);
1139 assert(c->parameter);
1140 assert(c->type == CONDITION_FILE_IS_EXECUTABLE);
1141
1142 return (stat(c->parameter, &st) >= 0 &&
1143 S_ISREG(st.st_mode) &&
1144 (st.st_mode & 0111));
1145 }
1146
1147 static int condition_test_psi(Condition *c, char **env) {
1148 _cleanup_free_ char *first = NULL, *second = NULL, *third = NULL, *fourth = NULL, *pressure_path = NULL;
1149 const char *p, *value, *pressure_type;
1150 loadavg_t *current, limit;
1151 ResourcePressure pressure;
1152 PressureType preferred_pressure_type = PRESSURE_TYPE_FULL;
1153 int r;
1154
1155 assert(c);
1156 assert(c->parameter);
1157 assert(IN_SET(c->type, CONDITION_MEMORY_PRESSURE, CONDITION_CPU_PRESSURE, CONDITION_IO_PRESSURE));
1158
1159 if (!is_pressure_supported()) {
1160 log_debug("Pressure Stall Information (PSI) is not supported, skipping.");
1161 return 1;
1162 }
1163
1164 pressure_type = c->type == CONDITION_MEMORY_PRESSURE ? "memory" :
1165 c->type == CONDITION_CPU_PRESSURE ? "cpu" :
1166 "io";
1167
1168 p = c->parameter;
1169 r = extract_many_words(&p, ":", 0, &first, &second);
1170 if (r <= 0)
1171 return log_debug_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1172 /* If only one parameter is passed, then we look at the global system pressure rather than a specific cgroup. */
1173 if (r == 1) {
1174 /* cpu.pressure 'full' is reported but undefined at system level */
1175 if (c->type == CONDITION_CPU_PRESSURE)
1176 preferred_pressure_type = PRESSURE_TYPE_SOME;
1177
1178 pressure_path = path_join("/proc/pressure", pressure_type);
1179 if (!pressure_path)
1180 return log_oom_debug();
1181
1182 value = first;
1183 } else {
1184 const char *controller = strjoina(pressure_type, ".pressure");
1185 _cleanup_free_ char *slice_path = NULL, *root_scope = NULL;
1186 CGroupMask mask, required_mask;
1187 char *slice, *e;
1188
1189 required_mask = c->type == CONDITION_MEMORY_PRESSURE ? CGROUP_MASK_MEMORY :
1190 c->type == CONDITION_CPU_PRESSURE ? CGROUP_MASK_CPU :
1191 CGROUP_MASK_IO;
1192
1193 slice = strstrip(first);
1194 if (!slice)
1195 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s.", c->parameter);
1196
1197 r = cg_mask_supported(&mask);
1198 if (r < 0)
1199 return log_debug_errno(r, "Failed to get supported cgroup controllers: %m");
1200
1201 if (!FLAGS_SET(mask, required_mask)) {
1202 log_debug("Cgroup %s controller not available, skipping PSI condition check.", pressure_type);
1203 return 1;
1204 }
1205
1206 r = cg_slice_to_path(slice, &slice_path);
1207 if (r < 0)
1208 return log_debug_errno(r, "Cannot determine slice \"%s\" cgroup path: %m", slice);
1209
1210 /* We might be running under the user manager, so get the root path and prefix it accordingly. */
1211 r = cg_pid_get_path(getpid_cached(), &root_scope);
1212 if (r < 0)
1213 return log_debug_errno(r, "Failed to get root cgroup path: %m");
1214
1215 /* Drop init.scope, we want the parent. We could get an empty or / path, but that's fine,
1216 * just skip it in that case. */
1217 e = endswith(root_scope, "/" SPECIAL_INIT_SCOPE);
1218 if (e)
1219 *e = 0;
1220 if (!empty_or_root(root_scope)) {
1221 _cleanup_free_ char *slice_joined = NULL;
1222
1223 slice_joined = path_join(root_scope, slice_path);
1224 if (!slice_joined)
1225 return log_oom_debug();
1226
1227 free_and_replace(slice_path, slice_joined);
1228 }
1229
1230 r = cg_get_path(slice_path, controller, &pressure_path);
1231 if (r < 0)
1232 return log_debug_errno(r, "Error getting cgroup pressure path from %s: %m", slice_path);
1233
1234 value = second;
1235 }
1236
1237 /* If a value including a specific timespan (in the intervals allowed by the kernel),
1238 * parse it, otherwise we assume just a plain percentage that will be checked if it is
1239 * smaller or equal to the current pressure average over 5 minutes. */
1240 r = extract_many_words(&value, "/", 0, &third, &fourth);
1241 if (r <= 0)
1242 return log_debug_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1243 if (r == 1)
1244 current = &pressure.avg300;
1245 else {
1246 const char *timespan;
1247
1248 timespan = skip_leading_chars(fourth, NULL);
1249 if (!timespan)
1250 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s.", c->parameter);
1251
1252 if (startswith(timespan, "10sec"))
1253 current = &pressure.avg10;
1254 else if (startswith(timespan, "1min"))
1255 current = &pressure.avg60;
1256 else if (startswith(timespan, "5min"))
1257 current = &pressure.avg300;
1258 else
1259 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s.", c->parameter);
1260 }
1261
1262 value = strstrip(third);
1263 if (!value)
1264 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s.", c->parameter);
1265
1266 r = parse_permyriad(value);
1267 if (r < 0)
1268 return log_debug_errno(r, "Failed to parse permyriad: %s", c->parameter);
1269
1270 r = store_loadavg_fixed_point(r / 100LU, r % 100LU, &limit);
1271 if (r < 0)
1272 return log_debug_errno(r, "Failed to parse loadavg: %s", c->parameter);
1273
1274 r = read_resource_pressure(pressure_path, preferred_pressure_type, &pressure);
1275 /* cpu.pressure 'full' was recently added at cgroup level, fall back to 'some' */
1276 if (r == -ENODATA && preferred_pressure_type == PRESSURE_TYPE_FULL)
1277 r = read_resource_pressure(pressure_path, PRESSURE_TYPE_SOME, &pressure);
1278 if (r == -ENOENT) {
1279 /* We already checked that /proc/pressure exists, so this means we were given a cgroup
1280 * that doesn't exist or doesn't exist any longer. */
1281 log_debug("\"%s\" not found, skipping PSI check.", pressure_path);
1282 return 1;
1283 }
1284 if (r < 0)
1285 return log_debug_errno(r, "Error parsing pressure from %s: %m", pressure_path);
1286
1287 return *current <= limit;
1288 }
1289
1290 static int condition_test_kernel_module_loaded(Condition *c, char **env) {
1291 int r;
1292
1293 assert(c);
1294 assert(c->parameter);
1295 assert(c->type == CONDITION_KERNEL_MODULE_LOADED);
1296
1297 /* Checks whether a specific kernel module is fully loaded (i.e. with the full initialization routine
1298 * complete). */
1299
1300 _cleanup_free_ char *normalized = strreplace(c->parameter, "-", "_");
1301 if (!normalized)
1302 return log_oom_debug();
1303
1304 if (!filename_is_valid(normalized)) {
1305 log_debug("Kernel module name '%s' is not valid, hence reporting it to not be loaded.", normalized);
1306 return false;
1307 }
1308
1309 _cleanup_free_ char *p = path_join("/sys/module/", normalized);
1310 if (!p)
1311 return log_oom_debug();
1312
1313 _cleanup_close_ int dir_fd = open(p, O_PATH|O_DIRECTORY|O_CLOEXEC);
1314 if (dir_fd < 0) {
1315 if (errno == ENOENT) {
1316 log_debug_errno(errno, "'%s/' does not exist, kernel module '%s' not loaded.", p, normalized);
1317 return false;
1318 }
1319
1320 return log_debug_errno(errno, "Failed to open directory '%s/': %m", p);
1321 }
1322
1323 _cleanup_free_ char *initstate = NULL;
1324 r = read_virtual_file_at(dir_fd, "initstate", SIZE_MAX, &initstate, NULL);
1325 if (r == -ENOENT) {
1326 log_debug_errno(r, "'%s/' exists but '%s/initstate' does not, kernel module '%s' is built-in, hence loaded.", p, p, normalized);
1327 return true;
1328 }
1329 if (r < 0)
1330 return log_debug_errno(r, "Failed to open '%s/initstate': %m", p);
1331
1332 delete_trailing_chars(initstate, WHITESPACE);
1333
1334 if (!streq(initstate, "live")) {
1335 log_debug("Kernel module '%s' is reported as '%s', hence not loaded.", normalized, initstate);
1336 return false;
1337 }
1338
1339 log_debug("Kernel module '%s' detected as loaded.", normalized);
1340 return true;
1341 }
1342
1343 int condition_test(Condition *c, char **env) {
1344
1345 static int (*const condition_tests[_CONDITION_TYPE_MAX])(Condition *c, char **env) = {
1346 [CONDITION_PATH_EXISTS] = condition_test_path_exists,
1347 [CONDITION_PATH_EXISTS_GLOB] = condition_test_path_exists_glob,
1348 [CONDITION_PATH_IS_DIRECTORY] = condition_test_path_is_directory,
1349 [CONDITION_PATH_IS_SYMBOLIC_LINK] = condition_test_path_is_symbolic_link,
1350 [CONDITION_PATH_IS_MOUNT_POINT] = condition_test_path_is_mount_point,
1351 [CONDITION_PATH_IS_READ_WRITE] = condition_test_path_is_read_write,
1352 [CONDITION_PATH_IS_ENCRYPTED] = condition_test_path_is_encrypted,
1353 [CONDITION_PATH_IS_SOCKET] = condition_test_path_is_socket,
1354 [CONDITION_DIRECTORY_NOT_EMPTY] = condition_test_directory_not_empty,
1355 [CONDITION_FILE_NOT_EMPTY] = condition_test_file_not_empty,
1356 [CONDITION_FILE_IS_EXECUTABLE] = condition_test_file_is_executable,
1357 [CONDITION_KERNEL_COMMAND_LINE] = condition_test_kernel_command_line,
1358 [CONDITION_VERSION] = condition_test_version,
1359 [CONDITION_CREDENTIAL] = condition_test_credential,
1360 [CONDITION_VIRTUALIZATION] = condition_test_virtualization,
1361 [CONDITION_SECURITY] = condition_test_security,
1362 [CONDITION_CAPABILITY] = condition_test_capability,
1363 [CONDITION_HOST] = condition_test_host,
1364 [CONDITION_FRACTION] = condition_test_fraction,
1365 [CONDITION_AC_POWER] = condition_test_ac_power,
1366 [CONDITION_ARCHITECTURE] = condition_test_architecture,
1367 [CONDITION_FIRMWARE] = condition_test_firmware,
1368 [CONDITION_NEEDS_UPDATE] = condition_test_needs_update,
1369 [CONDITION_FIRST_BOOT] = condition_test_first_boot,
1370 [CONDITION_USER] = condition_test_user,
1371 [CONDITION_GROUP] = condition_test_group,
1372 [CONDITION_CONTROL_GROUP_CONTROLLER] = condition_test_control_group_controller,
1373 [CONDITION_CPUS] = condition_test_cpus,
1374 [CONDITION_MEMORY] = condition_test_memory,
1375 [CONDITION_ENVIRONMENT] = condition_test_environment,
1376 [CONDITION_CPU_FEATURE] = condition_test_cpufeature,
1377 [CONDITION_OS_RELEASE] = condition_test_osrelease,
1378 [CONDITION_MACHINE_TAG] = condition_test_machine_tag,
1379 [CONDITION_MEMORY_PRESSURE] = condition_test_psi,
1380 [CONDITION_CPU_PRESSURE] = condition_test_psi,
1381 [CONDITION_IO_PRESSURE] = condition_test_psi,
1382 [CONDITION_KERNEL_MODULE_LOADED] = condition_test_kernel_module_loaded,
1383 };
1384
1385 int r, b;
1386
1387 assert(c);
1388 assert(c->type >= 0);
1389 assert(c->type < _CONDITION_TYPE_MAX);
1390
1391 r = condition_tests[c->type](c, env);
1392 if (r < 0) {
1393 c->result = CONDITION_ERROR;
1394 return r;
1395 }
1396
1397 b = (r > 0) == !c->negate;
1398 c->result = b ? CONDITION_SUCCEEDED : CONDITION_FAILED;
1399 return b;
1400 }
1401
1402 bool condition_test_list(
1403 Condition *first,
1404 char **env,
1405 condition_to_string_t to_string,
1406 condition_test_logger_t logger,
1407 void *userdata) {
1408
1409 int triggered = -1;
1410
1411 /* If the condition list is empty, then it is true */
1412 if (!first)
1413 return true;
1414
1415 /* Otherwise, if all of the non-trigger conditions apply and
1416 * if any of the trigger conditions apply (unless there are
1417 * none) we return true */
1418 LIST_FOREACH(conditions, c, first) {
1419 int r;
1420
1421 r = condition_test(c, env);
1422
1423 if (logger) {
1424 if (r < 0)
1425 logger(userdata, LOG_WARNING, r, PROJECT_FILE, __LINE__, __func__,
1426 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
1427 to_string(c->type),
1428 c->trigger ? "|" : "",
1429 c->negate ? "!" : "",
1430 c->parameter);
1431 else
1432 logger(userdata, LOG_DEBUG, 0, PROJECT_FILE, __LINE__, __func__,
1433 "%s=%s%s%s %s.",
1434 to_string(c->type),
1435 c->trigger ? "|" : "",
1436 c->negate ? "!" : "",
1437 c->parameter,
1438 condition_result_to_string(c->result));
1439 }
1440
1441 if (!c->trigger && r <= 0)
1442 return false;
1443
1444 if (c->trigger && triggered <= 0)
1445 triggered = r > 0;
1446 }
1447
1448 return triggered != 0;
1449 }
1450
1451 void condition_dump(Condition *c, FILE *f, const char *prefix, condition_to_string_t to_string) {
1452 assert(c);
1453 assert(f);
1454 assert(to_string);
1455
1456 prefix = strempty(prefix);
1457
1458 fprintf(f,
1459 "%s\t%s: %s%s%s %s\n",
1460 prefix,
1461 to_string(c->type),
1462 c->trigger ? "|" : "",
1463 c->negate ? "!" : "",
1464 c->parameter,
1465 condition_result_to_string(c->result));
1466 }
1467
1468 void condition_dump_list(Condition *first, FILE *f, const char *prefix, condition_to_string_t to_string) {
1469 LIST_FOREACH(conditions, c, first)
1470 condition_dump(c, f, prefix, to_string);
1471 }
1472
1473 static const char* const _condition_type_table[_CONDITION_TYPE_MAX] = {
1474 [CONDITION_ARCHITECTURE] = "ConditionArchitecture",
1475 [CONDITION_FIRMWARE] = "ConditionFirmware",
1476 [CONDITION_VIRTUALIZATION] = "ConditionVirtualization",
1477 [CONDITION_HOST] = "ConditionHost",
1478 [CONDITION_FRACTION] = "ConditionFraction",
1479 [CONDITION_KERNEL_COMMAND_LINE] = "ConditionKernelCommandLine",
1480 [CONDITION_VERSION] = "ConditionVersion",
1481 [CONDITION_CREDENTIAL] = "ConditionCredential",
1482 [CONDITION_SECURITY] = "ConditionSecurity",
1483 [CONDITION_CAPABILITY] = "ConditionCapability",
1484 [CONDITION_AC_POWER] = "ConditionACPower",
1485 [CONDITION_NEEDS_UPDATE] = "ConditionNeedsUpdate",
1486 [CONDITION_FIRST_BOOT] = "ConditionFirstBoot",
1487 [CONDITION_PATH_EXISTS] = "ConditionPathExists",
1488 [CONDITION_PATH_EXISTS_GLOB] = "ConditionPathExistsGlob",
1489 [CONDITION_PATH_IS_DIRECTORY] = "ConditionPathIsDirectory",
1490 [CONDITION_PATH_IS_SYMBOLIC_LINK] = "ConditionPathIsSymbolicLink",
1491 [CONDITION_PATH_IS_MOUNT_POINT] = "ConditionPathIsMountPoint",
1492 [CONDITION_PATH_IS_READ_WRITE] = "ConditionPathIsReadWrite",
1493 [CONDITION_PATH_IS_ENCRYPTED] = "ConditionPathIsEncrypted",
1494 [CONDITION_PATH_IS_SOCKET] = "ConditionPathIsSocket",
1495 [CONDITION_DIRECTORY_NOT_EMPTY] = "ConditionDirectoryNotEmpty",
1496 [CONDITION_FILE_NOT_EMPTY] = "ConditionFileNotEmpty",
1497 [CONDITION_FILE_IS_EXECUTABLE] = "ConditionFileIsExecutable",
1498 [CONDITION_USER] = "ConditionUser",
1499 [CONDITION_GROUP] = "ConditionGroup",
1500 [CONDITION_CONTROL_GROUP_CONTROLLER] = "ConditionControlGroupController",
1501 [CONDITION_CPUS] = "ConditionCPUs",
1502 [CONDITION_MEMORY] = "ConditionMemory",
1503 [CONDITION_ENVIRONMENT] = "ConditionEnvironment",
1504 [CONDITION_CPU_FEATURE] = "ConditionCPUFeature",
1505 [CONDITION_OS_RELEASE] = "ConditionOSRelease",
1506 [CONDITION_MACHINE_TAG] = "ConditionMachineTag",
1507 [CONDITION_MEMORY_PRESSURE] = "ConditionMemoryPressure",
1508 [CONDITION_CPU_PRESSURE] = "ConditionCPUPressure",
1509 [CONDITION_IO_PRESSURE] = "ConditionIOPressure",
1510 [CONDITION_KERNEL_MODULE_LOADED] = "ConditionKernelModuleLoaded",
1511 };
1512
1513 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(_condition_type, ConditionType);
1514
1515 const char* condition_type_to_string(ConditionType t) {
1516 return _condition_type_to_string(t);
1517 }
1518
1519 ConditionType condition_type_from_string(const char *s) {
1520 /* for backward compatibility */
1521 if (streq_ptr(s, "ConditionKernelVersion"))
1522 return CONDITION_VERSION;
1523
1524 return _condition_type_from_string(s);
1525 }
1526
1527 void condition_types_list(void) {
1528 DUMP_STRING_TABLE(_condition_type, ConditionType, _CONDITION_TYPE_MAX);
1529 }
1530
1531 static const char* const _assert_type_table[_CONDITION_TYPE_MAX] = {
1532 [CONDITION_ARCHITECTURE] = "AssertArchitecture",
1533 [CONDITION_FIRMWARE] = "AssertFirmware",
1534 [CONDITION_VIRTUALIZATION] = "AssertVirtualization",
1535 [CONDITION_HOST] = "AssertHost",
1536 [CONDITION_FRACTION] = "AssertFraction",
1537 [CONDITION_KERNEL_COMMAND_LINE] = "AssertKernelCommandLine",
1538 [CONDITION_VERSION] = "AssertVersion",
1539 [CONDITION_CREDENTIAL] = "AssertCredential",
1540 [CONDITION_SECURITY] = "AssertSecurity",
1541 [CONDITION_CAPABILITY] = "AssertCapability",
1542 [CONDITION_AC_POWER] = "AssertACPower",
1543 [CONDITION_NEEDS_UPDATE] = "AssertNeedsUpdate",
1544 [CONDITION_FIRST_BOOT] = "AssertFirstBoot",
1545 [CONDITION_PATH_EXISTS] = "AssertPathExists",
1546 [CONDITION_PATH_EXISTS_GLOB] = "AssertPathExistsGlob",
1547 [CONDITION_PATH_IS_DIRECTORY] = "AssertPathIsDirectory",
1548 [CONDITION_PATH_IS_SYMBOLIC_LINK] = "AssertPathIsSymbolicLink",
1549 [CONDITION_PATH_IS_MOUNT_POINT] = "AssertPathIsMountPoint",
1550 [CONDITION_PATH_IS_READ_WRITE] = "AssertPathIsReadWrite",
1551 [CONDITION_PATH_IS_ENCRYPTED] = "AssertPathIsEncrypted",
1552 [CONDITION_PATH_IS_SOCKET] = "AssertPathIsSocket",
1553 [CONDITION_DIRECTORY_NOT_EMPTY] = "AssertDirectoryNotEmpty",
1554 [CONDITION_FILE_NOT_EMPTY] = "AssertFileNotEmpty",
1555 [CONDITION_FILE_IS_EXECUTABLE] = "AssertFileIsExecutable",
1556 [CONDITION_USER] = "AssertUser",
1557 [CONDITION_GROUP] = "AssertGroup",
1558 [CONDITION_CONTROL_GROUP_CONTROLLER] = "AssertControlGroupController",
1559 [CONDITION_CPUS] = "AssertCPUs",
1560 [CONDITION_MEMORY] = "AssertMemory",
1561 [CONDITION_ENVIRONMENT] = "AssertEnvironment",
1562 [CONDITION_CPU_FEATURE] = "AssertCPUFeature",
1563 [CONDITION_OS_RELEASE] = "AssertOSRelease",
1564 [CONDITION_MACHINE_TAG] = "AssertMachineTag",
1565 [CONDITION_MEMORY_PRESSURE] = "AssertMemoryPressure",
1566 [CONDITION_CPU_PRESSURE] = "AssertCPUPressure",
1567 [CONDITION_IO_PRESSURE] = "AssertIOPressure",
1568 [CONDITION_KERNEL_MODULE_LOADED] = "AssertKernelModuleLoaded",
1569 };
1570
1571 DEFINE_PRIVATE_STRING_TABLE_LOOKUP(_assert_type, ConditionType);
1572
1573 const char* assert_type_to_string(ConditionType t) {
1574 return _assert_type_to_string(t);
1575 }
1576
1577 ConditionType assert_type_from_string(const char *s) {
1578 /* for backward compatibility */
1579 if (streq_ptr(s, "AssertKernelVersion"))
1580 return CONDITION_VERSION;
1581
1582 return _assert_type_from_string(s);
1583 }
1584
1585 void assert_types_list(void) {
1586 DUMP_STRING_TABLE(_assert_type, ConditionType, _CONDITION_TYPE_MAX);
1587 }
1588
1589 static const char* const condition_result_table[_CONDITION_RESULT_MAX] = {
1590 [CONDITION_UNTESTED] = "untested",
1591 [CONDITION_SUCCEEDED] = "succeeded",
1592 [CONDITION_FAILED] = "failed",
1593 [CONDITION_ERROR] = "error",
1594 };
1595
1596 DEFINE_STRING_TABLE_LOOKUP(condition_result, ConditionResult);