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