]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/condition.c
Merge pull request #21591 from yuwata/core-bpf-firewall-unsupported-reason
[thirdparty/systemd.git] / src / shared / condition.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <errno.h>
4 #include <fcntl.h>
5 #include <fnmatch.h>
6 #include <limits.h>
7 #include <stdlib.h>
8 #include <sys/stat.h>
9 #include <sys/types.h>
10 #include <sys/utsname.h>
11 #include <time.h>
12 #include <unistd.h>
13
14 #include "sd-id128.h"
15
16 #include "alloc-util.h"
17 #include "apparmor-util.h"
18 #include "architecture.h"
19 #include "audit-util.h"
20 #include "blockdev-util.h"
21 #include "cap-list.h"
22 #include "cgroup-util.h"
23 #include "condition.h"
24 #include "cpu-set-util.h"
25 #include "efi-loader.h"
26 #include "env-file.h"
27 #include "env-util.h"
28 #include "extract-word.h"
29 #include "fd-util.h"
30 #include "fileio.h"
31 #include "fs-util.h"
32 #include "glob-util.h"
33 #include "hostname-util.h"
34 #include "ima-util.h"
35 #include "limits-util.h"
36 #include "list.h"
37 #include "macro.h"
38 #include "mountpoint-util.h"
39 #include "os-util.h"
40 #include "parse-util.h"
41 #include "path-util.h"
42 #include "percent-util.h"
43 #include "proc-cmdline.h"
44 #include "process-util.h"
45 #include "psi-util.h"
46 #include "selinux-util.h"
47 #include "smack-util.h"
48 #include "stat-util.h"
49 #include "string-table.h"
50 #include "string-util.h"
51 #include "tomoyo-util.h"
52 #include "uid-alloc-range.h"
53 #include "user-util.h"
54 #include "util.h"
55 #include "virt.h"
56
57 Condition* condition_new(ConditionType type, const char *parameter, bool trigger, bool negate) {
58 Condition *c;
59
60 assert(type >= 0);
61 assert(type < _CONDITION_TYPE_MAX);
62 assert(parameter);
63
64 c = new(Condition, 1);
65 if (!c)
66 return NULL;
67
68 *c = (Condition) {
69 .type = type,
70 .trigger = trigger,
71 .negate = negate,
72 };
73
74 if (parameter) {
75 c->parameter = strdup(parameter);
76 if (!c->parameter)
77 return mfree(c);
78 }
79
80 return c;
81 }
82
83 Condition* condition_free(Condition *c) {
84 assert(c);
85
86 free(c->parameter);
87 return mfree(c);
88 }
89
90 Condition* condition_free_list_type(Condition *head, ConditionType type) {
91 Condition *c, *n;
92
93 LIST_FOREACH_SAFE(conditions, c, n, head)
94 if (type < 0 || c->type == type) {
95 LIST_REMOVE(conditions, head, c);
96 condition_free(c);
97 }
98
99 assert(type >= 0 || !head);
100 return head;
101 }
102
103 static int condition_test_kernel_command_line(Condition *c, char **env) {
104 _cleanup_free_ char *line = NULL;
105 const char *p;
106 bool equal;
107 int r;
108
109 assert(c);
110 assert(c->parameter);
111 assert(c->type == CONDITION_KERNEL_COMMAND_LINE);
112
113 r = proc_cmdline(&line);
114 if (r < 0)
115 return r;
116
117 equal = strchr(c->parameter, '=');
118
119 for (p = line;;) {
120 _cleanup_free_ char *word = NULL;
121 bool found;
122
123 r = extract_first_word(&p, &word, NULL, EXTRACT_UNQUOTE|EXTRACT_RELAX);
124 if (r < 0)
125 return r;
126 if (r == 0)
127 break;
128
129 if (equal)
130 found = streq(word, c->parameter);
131 else {
132 const char *f;
133
134 f = startswith(word, c->parameter);
135 found = f && IN_SET(*f, 0, '=');
136 }
137
138 if (found)
139 return true;
140 }
141
142 return false;
143 }
144
145 typedef enum {
146 /* Listed in order of checking. Note that some comparators are prefixes of others, hence the longest
147 * should be listed first. */
148 ORDER_LOWER_OR_EQUAL,
149 ORDER_GREATER_OR_EQUAL,
150 ORDER_LOWER,
151 ORDER_GREATER,
152 ORDER_EQUAL,
153 ORDER_UNEQUAL,
154 _ORDER_MAX,
155 _ORDER_INVALID = -EINVAL,
156 } OrderOperator;
157
158 static OrderOperator parse_order(const char **s) {
159
160 static const char *const prefix[_ORDER_MAX] = {
161 [ORDER_LOWER_OR_EQUAL] = "<=",
162 [ORDER_GREATER_OR_EQUAL] = ">=",
163 [ORDER_LOWER] = "<",
164 [ORDER_GREATER] = ">",
165 [ORDER_EQUAL] = "=",
166 [ORDER_UNEQUAL] = "!=",
167 };
168
169 OrderOperator i;
170
171 for (i = 0; i < _ORDER_MAX; i++) {
172 const char *e;
173
174 e = startswith(*s, prefix[i]);
175 if (e) {
176 *s = e;
177 return i;
178 }
179 }
180
181 return _ORDER_INVALID;
182 }
183
184 static bool test_order(int k, OrderOperator p) {
185
186 switch (p) {
187
188 case ORDER_LOWER:
189 return k < 0;
190
191 case ORDER_LOWER_OR_EQUAL:
192 return k <= 0;
193
194 case ORDER_EQUAL:
195 return k == 0;
196
197 case ORDER_UNEQUAL:
198 return k != 0;
199
200 case ORDER_GREATER_OR_EQUAL:
201 return k >= 0;
202
203 case ORDER_GREATER:
204 return k > 0;
205
206 default:
207 assert_not_reached();
208
209 }
210 }
211
212 static int condition_test_kernel_version(Condition *c, char **env) {
213 OrderOperator order;
214 struct utsname u;
215 const char *p;
216 bool first = true;
217
218 assert(c);
219 assert(c->parameter);
220 assert(c->type == CONDITION_KERNEL_VERSION);
221
222 assert_se(uname(&u) >= 0);
223
224 p = c->parameter;
225
226 for (;;) {
227 _cleanup_free_ char *word = NULL;
228 const char *s;
229 int r;
230
231 r = extract_first_word(&p, &word, NULL, EXTRACT_UNQUOTE);
232 if (r < 0)
233 return log_debug_errno(r, "Failed to parse condition string \"%s\": %m", p);
234 if (r == 0)
235 break;
236
237 s = strstrip(word);
238 order = parse_order(&s);
239 if (order >= 0) {
240 s += strspn(s, WHITESPACE);
241 if (isempty(s)) {
242 if (first) {
243 /* For backwards compatibility, allow whitespace between the operator and
244 * value, without quoting, but only in the first expression. */
245 word = mfree(word);
246 r = extract_first_word(&p, &word, NULL, 0);
247 if (r < 0)
248 return log_debug_errno(r, "Failed to parse condition string \"%s\": %m", p);
249 if (r == 0)
250 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected end of expression: %s", p);
251 s = word;
252 } else
253 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Unexpected end of expression: %s", p);
254 }
255
256 r = test_order(strverscmp_improved(u.release, s), order);
257 } else
258 /* No prefix? Then treat as glob string */
259 r = fnmatch(s, u.release, 0) == 0;
260
261 if (r == 0)
262 return false;
263
264 first = false;
265 }
266
267 return true;
268 }
269
270 static int condition_test_osrelease(Condition *c, char **env) {
271 const char *parameter = c->parameter;
272 int r;
273
274 assert(c);
275 assert(c->parameter);
276 assert(c->type == CONDITION_OS_RELEASE);
277
278 for (;;) {
279 _cleanup_free_ char *key = NULL, *condition = NULL, *actual_value = NULL;
280 OrderOperator order;
281 const char *word;
282 bool matches;
283
284 r = extract_first_word(&parameter, &condition, NULL, EXTRACT_UNQUOTE);
285 if (r < 0)
286 return log_debug_errno(r, "Failed to parse parameter: %m");
287 if (r == 0)
288 break;
289
290 /* parse_order() needs the string to start with the comparators */
291 word = condition;
292 r = extract_first_word(&word, &key, "!<=>", EXTRACT_RETAIN_SEPARATORS);
293 if (r < 0)
294 return log_debug_errno(r, "Failed to parse parameter: %m");
295 /* The os-release spec mandates env-var-like key names */
296 if (r == 0 || isempty(word) || !env_name_is_valid(key))
297 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
298 "Failed to parse parameter, key/value format expected: %m");
299
300 /* Do not allow whitespace after the separator, as that's not a valid os-release format */
301 order = parse_order(&word);
302 if (order < 0 || isempty(word) || strchr(WHITESPACE, *word) != NULL)
303 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL),
304 "Failed to parse parameter, key/value format expected: %m");
305
306 r = parse_os_release(NULL, key, &actual_value);
307 if (r < 0)
308 return log_debug_errno(r, "Failed to parse os-release: %m");
309
310 /* Might not be comparing versions, so do exact string matching */
311 if (order == ORDER_EQUAL)
312 matches = streq_ptr(actual_value, word);
313 else if (order == ORDER_UNEQUAL)
314 matches = !streq_ptr(actual_value, word);
315 else
316 matches = test_order(strverscmp_improved(actual_value, word), order);
317
318 if (!matches)
319 return false;
320 }
321
322 return true;
323 }
324
325 static int condition_test_memory(Condition *c, char **env) {
326 OrderOperator order;
327 uint64_t m, k;
328 const char *p;
329 int r;
330
331 assert(c);
332 assert(c->parameter);
333 assert(c->type == CONDITION_MEMORY);
334
335 m = physical_memory();
336
337 p = c->parameter;
338 order = parse_order(&p);
339 if (order < 0)
340 order = ORDER_GREATER_OR_EQUAL; /* default to >= check, if nothing is specified. */
341
342 r = safe_atou64(p, &k);
343 if (r < 0)
344 return log_debug_errno(r, "Failed to parse size: %m");
345
346 return test_order(CMP(m, k), order);
347 }
348
349 static int condition_test_cpus(Condition *c, char **env) {
350 OrderOperator order;
351 const char *p;
352 unsigned k;
353 int r, n;
354
355 assert(c);
356 assert(c->parameter);
357 assert(c->type == CONDITION_CPUS);
358
359 n = cpus_in_affinity_mask();
360 if (n < 0)
361 return log_debug_errno(n, "Failed to determine CPUs in affinity mask: %m");
362
363 p = c->parameter;
364 order = parse_order(&p);
365 if (order < 0)
366 order = ORDER_GREATER_OR_EQUAL; /* default to >= check, if nothing is specified. */
367
368 r = safe_atou(p, &k);
369 if (r < 0)
370 return log_debug_errno(r, "Failed to parse number of CPUs: %m");
371
372 return test_order(CMP((unsigned) n, k), order);
373 }
374
375 static int condition_test_user(Condition *c, char **env) {
376 uid_t id;
377 int r;
378 _cleanup_free_ char *username = NULL;
379 const char *u;
380
381 assert(c);
382 assert(c->parameter);
383 assert(c->type == CONDITION_USER);
384
385 r = parse_uid(c->parameter, &id);
386 if (r >= 0)
387 return id == getuid() || id == geteuid();
388
389 if (streq("@system", c->parameter))
390 return uid_is_system(getuid()) || uid_is_system(geteuid());
391
392 username = getusername_malloc();
393 if (!username)
394 return -ENOMEM;
395
396 if (streq(username, c->parameter))
397 return 1;
398
399 if (getpid_cached() == 1)
400 return streq(c->parameter, "root");
401
402 u = c->parameter;
403 r = get_user_creds(&u, &id, NULL, NULL, NULL, USER_CREDS_ALLOW_MISSING);
404 if (r < 0)
405 return 0;
406
407 return id == getuid() || id == geteuid();
408 }
409
410 static int condition_test_control_group_controller(Condition *c, char **env) {
411 int r;
412 CGroupMask system_mask, wanted_mask = 0;
413
414 assert(c);
415 assert(c->parameter);
416 assert(c->type == CONDITION_CONTROL_GROUP_CONTROLLER);
417
418 if (streq(c->parameter, "v2"))
419 return cg_all_unified();
420 if (streq(c->parameter, "v1")) {
421 r = cg_all_unified();
422 if (r < 0)
423 return r;
424 return !r;
425 }
426
427 r = cg_mask_supported(&system_mask);
428 if (r < 0)
429 return log_debug_errno(r, "Failed to determine supported controllers: %m");
430
431 r = cg_mask_from_string(c->parameter, &wanted_mask);
432 if (r < 0 || wanted_mask <= 0) {
433 /* This won't catch the case that we have an unknown controller
434 * mixed in with valid ones -- these are only assessed on the
435 * validity of the valid controllers found. */
436 log_debug("Failed to parse cgroup string: %s", c->parameter);
437 return 1;
438 }
439
440 return FLAGS_SET(system_mask, wanted_mask);
441 }
442
443 static int condition_test_group(Condition *c, char **env) {
444 gid_t id;
445 int r;
446
447 assert(c);
448 assert(c->parameter);
449 assert(c->type == CONDITION_GROUP);
450
451 r = parse_gid(c->parameter, &id);
452 if (r >= 0)
453 return in_gid(id);
454
455 /* Avoid any NSS lookups if we are PID1 */
456 if (getpid_cached() == 1)
457 return streq(c->parameter, "root");
458
459 return in_group(c->parameter) > 0;
460 }
461
462 static int condition_test_virtualization(Condition *c, char **env) {
463 int b, v;
464
465 assert(c);
466 assert(c->parameter);
467 assert(c->type == CONDITION_VIRTUALIZATION);
468
469 if (streq(c->parameter, "private-users"))
470 return running_in_userns();
471
472 v = detect_virtualization();
473 if (v < 0)
474 return v;
475
476 /* First, compare with yes/no */
477 b = parse_boolean(c->parameter);
478 if (b >= 0)
479 return b == !!v;
480
481 /* Then, compare categorization */
482 if (streq(c->parameter, "vm"))
483 return VIRTUALIZATION_IS_VM(v);
484
485 if (streq(c->parameter, "container"))
486 return VIRTUALIZATION_IS_CONTAINER(v);
487
488 /* Finally compare id */
489 return v != VIRTUALIZATION_NONE && streq(c->parameter, virtualization_to_string(v));
490 }
491
492 static int condition_test_architecture(Condition *c, char **env) {
493 int a, b;
494
495 assert(c);
496 assert(c->parameter);
497 assert(c->type == CONDITION_ARCHITECTURE);
498
499 a = uname_architecture();
500 if (a < 0)
501 return a;
502
503 if (streq(c->parameter, "native"))
504 b = native_architecture();
505 else {
506 b = architecture_from_string(c->parameter);
507 if (b < 0) /* unknown architecture? Then it's definitely not ours */
508 return false;
509 }
510
511 return a == b;
512 }
513
514 #define DTCOMPAT_FILE "/proc/device-tree/compatible"
515 static int condition_test_firmware_devicetree_compatible(const char *dtcarg) {
516 int r;
517 _cleanup_free_ char *dtcompat = NULL;
518 _cleanup_strv_free_ char **dtcompatlist = NULL;
519 size_t size;
520
521 r = read_full_virtual_file(DTCOMPAT_FILE, &dtcompat, &size);
522 if (r < 0) {
523 /* if the path doesn't exist it is incompatible */
524 if (r != -ENOENT)
525 log_debug_errno(r, "Failed to open() '%s', assuming machine is incompatible: %m", DTCOMPAT_FILE);
526 return false;
527 }
528
529 /* Not sure this can happen, but play safe. */
530 if (size == 0) {
531 log_debug("%s has zero length, assuming machine is incompatible", DTCOMPAT_FILE);
532 return false;
533 }
534
535 /* /proc/device-tree/compatible consists of one or more strings, each ending in '\0'.
536 * So the last character in dtcompat must be a '\0'. */
537 if (dtcompat[size - 1] != '\0') {
538 log_debug("%s is in an unknown format, assuming machine is incompatible", DTCOMPAT_FILE);
539 return false;
540 }
541
542 dtcompatlist = strv_parse_nulstr(dtcompat, size);
543 if (!dtcompatlist)
544 return -ENOMEM;
545
546 return strv_contains(dtcompatlist, dtcarg);
547 }
548
549 static int condition_test_firmware(Condition *c, char **env) {
550 sd_char *dtc;
551
552 assert(c);
553 assert(c->parameter);
554 assert(c->type == CONDITION_FIRMWARE);
555
556 if (streq(c->parameter, "device-tree")) {
557 if (access("/sys/firmware/device-tree/", F_OK) < 0) {
558 if (errno != ENOENT)
559 log_debug_errno(errno, "Unexpected error when checking for /sys/firmware/device-tree/: %m");
560 return false;
561 } else
562 return true;
563 } else if ((dtc = startswith(c->parameter, "device-tree-compatible("))) {
564 _cleanup_free_ char *dtcarg = NULL;
565 char *end;
566
567 end = strchr(dtc, ')');
568 if (!end || *(end + 1) != '\0') {
569 log_debug("Malformed Firmware condition \"%s\"", c->parameter);
570 return false;
571 }
572
573 dtcarg = strndup(dtc, end - dtc);
574 if (!dtcarg)
575 return -ENOMEM;
576
577 return condition_test_firmware_devicetree_compatible(dtcarg);
578 } else if (streq(c->parameter, "uefi"))
579 return is_efi_boot();
580 else {
581 log_debug("Unsupported Firmware condition \"%s\"", c->parameter);
582 return false;
583 }
584 }
585
586 static int condition_test_host(Condition *c, char **env) {
587 _cleanup_free_ char *h = NULL;
588 sd_id128_t x, y;
589 int r;
590
591 assert(c);
592 assert(c->parameter);
593 assert(c->type == CONDITION_HOST);
594
595 if (sd_id128_from_string(c->parameter, &x) >= 0) {
596
597 r = sd_id128_get_machine(&y);
598 if (r < 0)
599 return r;
600
601 return sd_id128_equal(x, y);
602 }
603
604 h = gethostname_malloc();
605 if (!h)
606 return -ENOMEM;
607
608 return fnmatch(c->parameter, h, FNM_CASEFOLD) == 0;
609 }
610
611 static int condition_test_ac_power(Condition *c, char **env) {
612 int r;
613
614 assert(c);
615 assert(c->parameter);
616 assert(c->type == CONDITION_AC_POWER);
617
618 r = parse_boolean(c->parameter);
619 if (r < 0)
620 return r;
621
622 return (on_ac_power() != 0) == !!r;
623 }
624
625 static int has_tpm2(void) {
626 int r;
627
628 /* Checks whether the system has at least one TPM2 resource manager device, i.e. at least one "tpmrm"
629 * class device */
630
631 r = dir_is_empty("/sys/class/tpmrm");
632 if (r == 0)
633 return true; /* nice! we have a device */
634
635 /* Hmm, so Linux doesn't know of the TPM2 device (or we couldn't check for it), most likely because
636 * the driver wasn't loaded yet. Let's see if the firmware knows about a TPM2 device, in this
637 * case. This way we can answer the TPM2 question already during early boot (where we most likely
638 * need it) */
639 if (efi_has_tpm2())
640 return true;
641
642 /* OK, this didn't work either, in this case propagate the original errors */
643 if (r == -ENOENT)
644 return false;
645 if (r < 0)
646 return log_debug_errno(r, "Failed to determine whether system has TPM2 support: %m");
647
648 return !r;
649 }
650
651 static int condition_test_security(Condition *c, char **env) {
652 assert(c);
653 assert(c->parameter);
654 assert(c->type == CONDITION_SECURITY);
655
656 if (streq(c->parameter, "selinux"))
657 return mac_selinux_use();
658 if (streq(c->parameter, "smack"))
659 return mac_smack_use();
660 if (streq(c->parameter, "apparmor"))
661 return mac_apparmor_use();
662 if (streq(c->parameter, "audit"))
663 return use_audit();
664 if (streq(c->parameter, "ima"))
665 return use_ima();
666 if (streq(c->parameter, "tomoyo"))
667 return mac_tomoyo_use();
668 if (streq(c->parameter, "uefi-secureboot"))
669 return is_efi_secure_boot();
670 if (streq(c->parameter, "tpm2"))
671 return has_tpm2();
672
673 return false;
674 }
675
676 static int condition_test_capability(Condition *c, char **env) {
677 unsigned long long capabilities = (unsigned long long) -1;
678 _cleanup_fclose_ FILE *f = NULL;
679 int value, r;
680
681 assert(c);
682 assert(c->parameter);
683 assert(c->type == CONDITION_CAPABILITY);
684
685 /* If it's an invalid capability, we don't have it */
686 value = capability_from_name(c->parameter);
687 if (value < 0)
688 return -EINVAL;
689
690 /* If it's a valid capability we default to assume
691 * that we have it */
692
693 f = fopen("/proc/self/status", "re");
694 if (!f)
695 return -errno;
696
697 for (;;) {
698 _cleanup_free_ char *line = NULL;
699 const char *p;
700
701 r = read_line(f, LONG_LINE_MAX, &line);
702 if (r < 0)
703 return r;
704 if (r == 0)
705 break;
706
707 p = startswith(line, "CapBnd:");
708 if (p) {
709 if (sscanf(line+7, "%llx", &capabilities) != 1)
710 return -EIO;
711
712 break;
713 }
714 }
715
716 return !!(capabilities & (1ULL << value));
717 }
718
719 static int condition_test_needs_update(Condition *c, char **env) {
720 struct stat usr, other;
721 const char *p;
722 bool b;
723 int r;
724
725 assert(c);
726 assert(c->parameter);
727 assert(c->type == CONDITION_NEEDS_UPDATE);
728
729 r = proc_cmdline_get_bool("systemd.condition-needs-update", &b);
730 if (r < 0)
731 log_debug_errno(r, "Failed to parse systemd.condition-needs-update= kernel command line argument, ignoring: %m");
732 if (r > 0)
733 return b;
734
735 if (in_initrd()) {
736 log_debug("We are in an initrd, not doing any updates.");
737 return false;
738 }
739
740 if (!path_is_absolute(c->parameter)) {
741 log_debug("Specified condition parameter '%s' is not absolute, assuming an update is needed.", c->parameter);
742 return true;
743 }
744
745 /* If the file system is read-only we shouldn't suggest an update */
746 r = path_is_read_only_fs(c->parameter);
747 if (r < 0)
748 log_debug_errno(r, "Failed to determine if '%s' is read-only, ignoring: %m", c->parameter);
749 if (r > 0)
750 return false;
751
752 /* Any other failure means we should allow the condition to be true, so that we rather invoke too
753 * many update tools than too few. */
754
755 p = strjoina(c->parameter, "/.updated");
756 if (lstat(p, &other) < 0) {
757 if (errno != ENOENT)
758 log_debug_errno(errno, "Failed to stat() '%s', assuming an update is needed: %m", p);
759 return true;
760 }
761
762 if (lstat("/usr/", &usr) < 0) {
763 log_debug_errno(errno, "Failed to stat() /usr/, assuming an update is needed: %m");
764 return true;
765 }
766
767 /*
768 * First, compare seconds as they are always accurate...
769 */
770 if (usr.st_mtim.tv_sec != other.st_mtim.tv_sec)
771 return usr.st_mtim.tv_sec > other.st_mtim.tv_sec;
772
773 /*
774 * ...then compare nanoseconds.
775 *
776 * A false positive is only possible when /usr's nanoseconds > 0
777 * (otherwise /usr cannot be strictly newer than the target file)
778 * AND the target file's nanoseconds == 0
779 * (otherwise the filesystem supports nsec timestamps, see stat(2)).
780 */
781 if (usr.st_mtim.tv_nsec == 0 || other.st_mtim.tv_nsec > 0)
782 return usr.st_mtim.tv_nsec > other.st_mtim.tv_nsec;
783
784 _cleanup_free_ char *timestamp_str = NULL;
785 r = parse_env_file(NULL, p, "TIMESTAMP_NSEC", &timestamp_str);
786 if (r < 0) {
787 log_debug_errno(r, "Failed to parse timestamp file '%s', using mtime: %m", p);
788 return true;
789 } else if (r == 0) {
790 log_debug("No data in timestamp file '%s', using mtime.", p);
791 return true;
792 }
793
794 uint64_t timestamp;
795 r = safe_atou64(timestamp_str, &timestamp);
796 if (r < 0) {
797 log_debug_errno(r, "Failed to parse timestamp value '%s' in file '%s', using mtime: %m", timestamp_str, p);
798 return true;
799 }
800
801 return timespec_load_nsec(&usr.st_mtim) > timestamp;
802 }
803
804 static int condition_test_first_boot(Condition *c, char **env) {
805 int r, q;
806 bool b;
807
808 assert(c);
809 assert(c->parameter);
810 assert(c->type == CONDITION_FIRST_BOOT);
811
812 r = proc_cmdline_get_bool("systemd.condition-first-boot", &b);
813 if (r < 0)
814 log_debug_errno(r, "Failed to parse systemd.condition-first-boot= kernel command line argument, ignoring: %m");
815 if (r > 0)
816 return b == !!r;
817
818 r = parse_boolean(c->parameter);
819 if (r < 0)
820 return r;
821
822 q = access("/run/systemd/first-boot", F_OK);
823 if (q < 0 && errno != ENOENT)
824 log_debug_errno(errno, "Failed to check if /run/systemd/first-boot exists, ignoring: %m");
825
826 return (q >= 0) == !!r;
827 }
828
829 static int condition_test_environment(Condition *c, char **env) {
830 bool equal;
831 char **i;
832
833 assert(c);
834 assert(c->parameter);
835 assert(c->type == CONDITION_ENVIRONMENT);
836
837 equal = strchr(c->parameter, '=');
838
839 STRV_FOREACH(i, env) {
840 bool found;
841
842 if (equal)
843 found = streq(c->parameter, *i);
844 else {
845 const char *f;
846
847 f = startswith(*i, c->parameter);
848 found = f && IN_SET(*f, 0, '=');
849 }
850
851 if (found)
852 return true;
853 }
854
855 return false;
856 }
857
858 static int condition_test_path_exists(Condition *c, char **env) {
859 assert(c);
860 assert(c->parameter);
861 assert(c->type == CONDITION_PATH_EXISTS);
862
863 return access(c->parameter, F_OK) >= 0;
864 }
865
866 static int condition_test_path_exists_glob(Condition *c, char **env) {
867 assert(c);
868 assert(c->parameter);
869 assert(c->type == CONDITION_PATH_EXISTS_GLOB);
870
871 return glob_exists(c->parameter) > 0;
872 }
873
874 static int condition_test_path_is_directory(Condition *c, char **env) {
875 assert(c);
876 assert(c->parameter);
877 assert(c->type == CONDITION_PATH_IS_DIRECTORY);
878
879 return is_dir(c->parameter, true) > 0;
880 }
881
882 static int condition_test_path_is_symbolic_link(Condition *c, char **env) {
883 assert(c);
884 assert(c->parameter);
885 assert(c->type == CONDITION_PATH_IS_SYMBOLIC_LINK);
886
887 return is_symlink(c->parameter) > 0;
888 }
889
890 static int condition_test_path_is_mount_point(Condition *c, char **env) {
891 assert(c);
892 assert(c->parameter);
893 assert(c->type == CONDITION_PATH_IS_MOUNT_POINT);
894
895 return path_is_mount_point(c->parameter, NULL, AT_SYMLINK_FOLLOW) > 0;
896 }
897
898 static int condition_test_path_is_read_write(Condition *c, char **env) {
899 int r;
900
901 assert(c);
902 assert(c->parameter);
903 assert(c->type == CONDITION_PATH_IS_READ_WRITE);
904
905 r = path_is_read_only_fs(c->parameter);
906
907 return r <= 0 && r != -ENOENT;
908 }
909
910 static int condition_test_cpufeature(Condition *c, char **env) {
911 assert(c);
912 assert(c->parameter);
913 assert(c->type == CONDITION_CPU_FEATURE);
914
915 return has_cpu_with_flag(ascii_strlower(c->parameter));
916 }
917
918 static int condition_test_path_is_encrypted(Condition *c, char **env) {
919 int r;
920
921 assert(c);
922 assert(c->parameter);
923 assert(c->type == CONDITION_PATH_IS_ENCRYPTED);
924
925 r = path_is_encrypted(c->parameter);
926 if (r < 0 && r != -ENOENT)
927 log_debug_errno(r, "Failed to determine if '%s' is encrypted: %m", c->parameter);
928
929 return r > 0;
930 }
931
932 static int condition_test_directory_not_empty(Condition *c, char **env) {
933 int r;
934
935 assert(c);
936 assert(c->parameter);
937 assert(c->type == CONDITION_DIRECTORY_NOT_EMPTY);
938
939 r = dir_is_empty(c->parameter);
940 return r <= 0 && !IN_SET(r, -ENOENT, -ENOTDIR);
941 }
942
943 static int condition_test_file_not_empty(Condition *c, char **env) {
944 struct stat st;
945
946 assert(c);
947 assert(c->parameter);
948 assert(c->type == CONDITION_FILE_NOT_EMPTY);
949
950 return (stat(c->parameter, &st) >= 0 &&
951 S_ISREG(st.st_mode) &&
952 st.st_size > 0);
953 }
954
955 static int condition_test_file_is_executable(Condition *c, char **env) {
956 struct stat st;
957
958 assert(c);
959 assert(c->parameter);
960 assert(c->type == CONDITION_FILE_IS_EXECUTABLE);
961
962 return (stat(c->parameter, &st) >= 0 &&
963 S_ISREG(st.st_mode) &&
964 (st.st_mode & 0111));
965 }
966
967 static int condition_test_psi(Condition *c, char **env) {
968 _cleanup_free_ char *first = NULL, *second = NULL, *third = NULL, *fourth = NULL, *pressure_path = NULL;
969 const char *p, *value, *pressure_type;
970 loadavg_t *current, limit;
971 ResourcePressure pressure;
972 int r;
973
974 assert(c);
975 assert(c->parameter);
976 assert(IN_SET(c->type, CONDITION_MEMORY_PRESSURE, CONDITION_CPU_PRESSURE, CONDITION_IO_PRESSURE));
977
978 if (!is_pressure_supported()) {
979 log_debug("Pressure Stall Information (PSI) is not supported, skipping.");
980 return 1;
981 }
982
983 pressure_type = c->type == CONDITION_MEMORY_PRESSURE ? "memory" :
984 c->type == CONDITION_CPU_PRESSURE ? "cpu" :
985 "io";
986
987 p = c->parameter;
988 r = extract_many_words(&p, ":", 0, &first, &second, NULL);
989 if (r <= 0)
990 return log_debug_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
991 /* If only one parameter is passed, then we look at the global system pressure rather than a specific cgroup. */
992 if (r == 1) {
993 pressure_path = path_join("/proc/pressure", pressure_type);
994 if (!pressure_path)
995 return log_oom();
996
997 value = first;
998 } else {
999 const char *controller = strjoina(pressure_type, ".pressure");
1000 _cleanup_free_ char *slice_path = NULL;
1001 CGroupMask mask, required_mask;
1002 char *slice;
1003
1004 required_mask = c->type == CONDITION_MEMORY_PRESSURE ? CGROUP_MASK_MEMORY :
1005 c->type == CONDITION_CPU_PRESSURE ? CGROUP_MASK_CPU :
1006 CGROUP_MASK_IO;
1007
1008 slice = strstrip(first);
1009 if (!slice)
1010 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1011
1012 r = cg_all_unified();
1013 if (r < 0)
1014 return log_debug_errno(r, "Failed to determine whether the unified cgroups hierarchy is used: %m");
1015 if (r == 0) {
1016 log_debug("PSI condition check requires the unified cgroups hierarchy, skipping.");
1017 return 1;
1018 }
1019
1020 r = cg_mask_supported(&mask);
1021 if (r < 0)
1022 return log_debug_errno(r, "Failed to get supported cgroup controllers: %m");
1023
1024 if (!FLAGS_SET(mask, required_mask)) {
1025 log_debug("Cgroup %s controller not available, skipping PSI condition check.", pressure_type);
1026 return 1;
1027 }
1028
1029 r = cg_slice_to_path(slice, &slice_path);
1030 if (r < 0)
1031 return log_debug_errno(r, "Cannot determine slice \"%s\" cgroup path: %m", slice);
1032
1033 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, slice_path, controller, &pressure_path);
1034 if (r < 0)
1035 return log_debug_errno(r, "Error getting cgroup pressure path from %s: %m", slice_path);
1036
1037 value = second;
1038 }
1039
1040 /* If a value including a specific timespan (in the intervals allowed by the kernel),
1041 * parse it, otherwise we assume just a plain percentage that will be checked if it is
1042 * smaller or equal to the current pressure average over 5 minutes. */
1043 r = extract_many_words(&value, "/", 0, &third, &fourth, NULL);
1044 if (r <= 0)
1045 return log_debug_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1046 if (r == 1)
1047 current = &pressure.avg300;
1048 else {
1049 const char *timespan;
1050
1051 timespan = skip_leading_chars(fourth, NULL);
1052 if (!timespan)
1053 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1054
1055 if (startswith(timespan, "10sec"))
1056 current = &pressure.avg10;
1057 else if (startswith(timespan, "1min"))
1058 current = &pressure.avg60;
1059 else if (startswith(timespan, "5min"))
1060 current = &pressure.avg300;
1061 else
1062 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1063 }
1064
1065 value = strstrip(third);
1066 if (!value)
1067 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1068
1069 r = parse_permyriad(value);
1070 if (r < 0)
1071 return log_debug_errno(r, "Failed to parse permyriad: %s", c->parameter);
1072
1073 r = store_loadavg_fixed_point(r / 100LU, r % 100LU, &limit);
1074 if (r < 0)
1075 return log_debug_errno(r, "Failed to parse loadavg: %s", c->parameter);
1076
1077 r = read_resource_pressure(pressure_path, PRESSURE_TYPE_FULL, &pressure);
1078 if (r == -ENODATA) /* cpu.pressure 'full' was added recently, fall back to 'some'. */
1079 r = read_resource_pressure(pressure_path, PRESSURE_TYPE_SOME, &pressure);
1080 if (r == -ENOENT) {
1081 /* We already checked that /proc/pressure exists, so this means we were given a cgroup
1082 * that doesn't exist or doesn't exist any longer. */
1083 log_debug("\"%s\" not found, skipping PSI check.", pressure_path);
1084 return 1;
1085 }
1086 if (r < 0)
1087 return log_debug_errno(r, "Error parsing pressure from %s: %m", pressure_path);
1088
1089 return *current <= limit;
1090 }
1091
1092 int condition_test(Condition *c, char **env) {
1093
1094 static int (*const condition_tests[_CONDITION_TYPE_MAX])(Condition *c, char **env) = {
1095 [CONDITION_PATH_EXISTS] = condition_test_path_exists,
1096 [CONDITION_PATH_EXISTS_GLOB] = condition_test_path_exists_glob,
1097 [CONDITION_PATH_IS_DIRECTORY] = condition_test_path_is_directory,
1098 [CONDITION_PATH_IS_SYMBOLIC_LINK] = condition_test_path_is_symbolic_link,
1099 [CONDITION_PATH_IS_MOUNT_POINT] = condition_test_path_is_mount_point,
1100 [CONDITION_PATH_IS_READ_WRITE] = condition_test_path_is_read_write,
1101 [CONDITION_PATH_IS_ENCRYPTED] = condition_test_path_is_encrypted,
1102 [CONDITION_DIRECTORY_NOT_EMPTY] = condition_test_directory_not_empty,
1103 [CONDITION_FILE_NOT_EMPTY] = condition_test_file_not_empty,
1104 [CONDITION_FILE_IS_EXECUTABLE] = condition_test_file_is_executable,
1105 [CONDITION_KERNEL_COMMAND_LINE] = condition_test_kernel_command_line,
1106 [CONDITION_KERNEL_VERSION] = condition_test_kernel_version,
1107 [CONDITION_VIRTUALIZATION] = condition_test_virtualization,
1108 [CONDITION_SECURITY] = condition_test_security,
1109 [CONDITION_CAPABILITY] = condition_test_capability,
1110 [CONDITION_HOST] = condition_test_host,
1111 [CONDITION_AC_POWER] = condition_test_ac_power,
1112 [CONDITION_ARCHITECTURE] = condition_test_architecture,
1113 [CONDITION_FIRMWARE] = condition_test_firmware,
1114 [CONDITION_NEEDS_UPDATE] = condition_test_needs_update,
1115 [CONDITION_FIRST_BOOT] = condition_test_first_boot,
1116 [CONDITION_USER] = condition_test_user,
1117 [CONDITION_GROUP] = condition_test_group,
1118 [CONDITION_CONTROL_GROUP_CONTROLLER] = condition_test_control_group_controller,
1119 [CONDITION_CPUS] = condition_test_cpus,
1120 [CONDITION_MEMORY] = condition_test_memory,
1121 [CONDITION_ENVIRONMENT] = condition_test_environment,
1122 [CONDITION_CPU_FEATURE] = condition_test_cpufeature,
1123 [CONDITION_OS_RELEASE] = condition_test_osrelease,
1124 [CONDITION_MEMORY_PRESSURE] = condition_test_psi,
1125 [CONDITION_CPU_PRESSURE] = condition_test_psi,
1126 [CONDITION_IO_PRESSURE] = condition_test_psi,
1127 };
1128
1129 int r, b;
1130
1131 assert(c);
1132 assert(c->type >= 0);
1133 assert(c->type < _CONDITION_TYPE_MAX);
1134
1135 r = condition_tests[c->type](c, env);
1136 if (r < 0) {
1137 c->result = CONDITION_ERROR;
1138 return r;
1139 }
1140
1141 b = (r > 0) == !c->negate;
1142 c->result = b ? CONDITION_SUCCEEDED : CONDITION_FAILED;
1143 return b;
1144 }
1145
1146 bool condition_test_list(
1147 Condition *first,
1148 char **env,
1149 condition_to_string_t to_string,
1150 condition_test_logger_t logger,
1151 void *userdata) {
1152
1153 Condition *c;
1154 int triggered = -1;
1155
1156 assert(!!logger == !!to_string);
1157
1158 /* If the condition list is empty, then it is true */
1159 if (!first)
1160 return true;
1161
1162 /* Otherwise, if all of the non-trigger conditions apply and
1163 * if any of the trigger conditions apply (unless there are
1164 * none) we return true */
1165 LIST_FOREACH(conditions, c, first) {
1166 int r;
1167
1168 r = condition_test(c, env);
1169
1170 if (logger) {
1171 if (r < 0)
1172 logger(userdata, LOG_WARNING, r, PROJECT_FILE, __LINE__, __func__,
1173 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
1174 to_string(c->type),
1175 c->trigger ? "|" : "",
1176 c->negate ? "!" : "",
1177 c->parameter);
1178 else
1179 logger(userdata, LOG_DEBUG, 0, PROJECT_FILE, __LINE__, __func__,
1180 "%s=%s%s%s %s.",
1181 to_string(c->type),
1182 c->trigger ? "|" : "",
1183 c->negate ? "!" : "",
1184 c->parameter,
1185 condition_result_to_string(c->result));
1186 }
1187
1188 if (!c->trigger && r <= 0)
1189 return false;
1190
1191 if (c->trigger && triggered <= 0)
1192 triggered = r > 0;
1193 }
1194
1195 return triggered != 0;
1196 }
1197
1198 void condition_dump(Condition *c, FILE *f, const char *prefix, condition_to_string_t to_string) {
1199 assert(c);
1200 assert(f);
1201 assert(to_string);
1202
1203 prefix = strempty(prefix);
1204
1205 fprintf(f,
1206 "%s\t%s: %s%s%s %s\n",
1207 prefix,
1208 to_string(c->type),
1209 c->trigger ? "|" : "",
1210 c->negate ? "!" : "",
1211 c->parameter,
1212 condition_result_to_string(c->result));
1213 }
1214
1215 void condition_dump_list(Condition *first, FILE *f, const char *prefix, condition_to_string_t to_string) {
1216 Condition *c;
1217
1218 LIST_FOREACH(conditions, c, first)
1219 condition_dump(c, f, prefix, to_string);
1220 }
1221
1222 static const char* const condition_type_table[_CONDITION_TYPE_MAX] = {
1223 [CONDITION_ARCHITECTURE] = "ConditionArchitecture",
1224 [CONDITION_FIRMWARE] = "ConditionFirmware",
1225 [CONDITION_VIRTUALIZATION] = "ConditionVirtualization",
1226 [CONDITION_HOST] = "ConditionHost",
1227 [CONDITION_KERNEL_COMMAND_LINE] = "ConditionKernelCommandLine",
1228 [CONDITION_KERNEL_VERSION] = "ConditionKernelVersion",
1229 [CONDITION_SECURITY] = "ConditionSecurity",
1230 [CONDITION_CAPABILITY] = "ConditionCapability",
1231 [CONDITION_AC_POWER] = "ConditionACPower",
1232 [CONDITION_NEEDS_UPDATE] = "ConditionNeedsUpdate",
1233 [CONDITION_FIRST_BOOT] = "ConditionFirstBoot",
1234 [CONDITION_PATH_EXISTS] = "ConditionPathExists",
1235 [CONDITION_PATH_EXISTS_GLOB] = "ConditionPathExistsGlob",
1236 [CONDITION_PATH_IS_DIRECTORY] = "ConditionPathIsDirectory",
1237 [CONDITION_PATH_IS_SYMBOLIC_LINK] = "ConditionPathIsSymbolicLink",
1238 [CONDITION_PATH_IS_MOUNT_POINT] = "ConditionPathIsMountPoint",
1239 [CONDITION_PATH_IS_READ_WRITE] = "ConditionPathIsReadWrite",
1240 [CONDITION_PATH_IS_ENCRYPTED] = "ConditionPathIsEncrypted",
1241 [CONDITION_DIRECTORY_NOT_EMPTY] = "ConditionDirectoryNotEmpty",
1242 [CONDITION_FILE_NOT_EMPTY] = "ConditionFileNotEmpty",
1243 [CONDITION_FILE_IS_EXECUTABLE] = "ConditionFileIsExecutable",
1244 [CONDITION_USER] = "ConditionUser",
1245 [CONDITION_GROUP] = "ConditionGroup",
1246 [CONDITION_CONTROL_GROUP_CONTROLLER] = "ConditionControlGroupController",
1247 [CONDITION_CPUS] = "ConditionCPUs",
1248 [CONDITION_MEMORY] = "ConditionMemory",
1249 [CONDITION_ENVIRONMENT] = "ConditionEnvironment",
1250 [CONDITION_CPU_FEATURE] = "ConditionCPUFeature",
1251 [CONDITION_OS_RELEASE] = "ConditionOSRelease",
1252 [CONDITION_MEMORY_PRESSURE] = "ConditionMemoryPressure",
1253 [CONDITION_CPU_PRESSURE] = "ConditionCPUPressure",
1254 [CONDITION_IO_PRESSURE] = "ConditionIOPressure",
1255 };
1256
1257 DEFINE_STRING_TABLE_LOOKUP(condition_type, ConditionType);
1258
1259 static const char* const assert_type_table[_CONDITION_TYPE_MAX] = {
1260 [CONDITION_ARCHITECTURE] = "AssertArchitecture",
1261 [CONDITION_FIRMWARE] = "AssertFirmware",
1262 [CONDITION_VIRTUALIZATION] = "AssertVirtualization",
1263 [CONDITION_HOST] = "AssertHost",
1264 [CONDITION_KERNEL_COMMAND_LINE] = "AssertKernelCommandLine",
1265 [CONDITION_KERNEL_VERSION] = "AssertKernelVersion",
1266 [CONDITION_SECURITY] = "AssertSecurity",
1267 [CONDITION_CAPABILITY] = "AssertCapability",
1268 [CONDITION_AC_POWER] = "AssertACPower",
1269 [CONDITION_NEEDS_UPDATE] = "AssertNeedsUpdate",
1270 [CONDITION_FIRST_BOOT] = "AssertFirstBoot",
1271 [CONDITION_PATH_EXISTS] = "AssertPathExists",
1272 [CONDITION_PATH_EXISTS_GLOB] = "AssertPathExistsGlob",
1273 [CONDITION_PATH_IS_DIRECTORY] = "AssertPathIsDirectory",
1274 [CONDITION_PATH_IS_SYMBOLIC_LINK] = "AssertPathIsSymbolicLink",
1275 [CONDITION_PATH_IS_MOUNT_POINT] = "AssertPathIsMountPoint",
1276 [CONDITION_PATH_IS_READ_WRITE] = "AssertPathIsReadWrite",
1277 [CONDITION_PATH_IS_ENCRYPTED] = "AssertPathIsEncrypted",
1278 [CONDITION_DIRECTORY_NOT_EMPTY] = "AssertDirectoryNotEmpty",
1279 [CONDITION_FILE_NOT_EMPTY] = "AssertFileNotEmpty",
1280 [CONDITION_FILE_IS_EXECUTABLE] = "AssertFileIsExecutable",
1281 [CONDITION_USER] = "AssertUser",
1282 [CONDITION_GROUP] = "AssertGroup",
1283 [CONDITION_CONTROL_GROUP_CONTROLLER] = "AssertControlGroupController",
1284 [CONDITION_CPUS] = "AssertCPUs",
1285 [CONDITION_MEMORY] = "AssertMemory",
1286 [CONDITION_ENVIRONMENT] = "AssertEnvironment",
1287 [CONDITION_CPU_FEATURE] = "AssertCPUFeature",
1288 [CONDITION_OS_RELEASE] = "AssertOSRelease",
1289 [CONDITION_MEMORY_PRESSURE] = "AssertMemoryPressure",
1290 [CONDITION_CPU_PRESSURE] = "AssertCPUPressure",
1291 [CONDITION_IO_PRESSURE] = "AssertIOPressure",
1292 };
1293
1294 DEFINE_STRING_TABLE_LOOKUP(assert_type, ConditionType);
1295
1296 static const char* const condition_result_table[_CONDITION_RESULT_MAX] = {
1297 [CONDITION_UNTESTED] = "untested",
1298 [CONDITION_SUCCEEDED] = "succeeded",
1299 [CONDITION_FAILED] = "failed",
1300 [CONDITION_ERROR] = "error",
1301 };
1302
1303 DEFINE_STRING_TABLE_LOOKUP(condition_result, ConditionResult);