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