]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/condition.c
204f2a1a8d31ef6b51c5c11d587f9ebd7c75aec8
[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 char **i;
831
832 assert(c);
833 assert(c->parameter);
834 assert(c->type == CONDITION_ENVIRONMENT);
835
836 equal = strchr(c->parameter, '=');
837
838 STRV_FOREACH(i, env) {
839 bool found;
840
841 if (equal)
842 found = streq(c->parameter, *i);
843 else {
844 const char *f;
845
846 f = startswith(*i, c->parameter);
847 found = f && IN_SET(*f, 0, '=');
848 }
849
850 if (found)
851 return true;
852 }
853
854 return false;
855 }
856
857 static int condition_test_path_exists(Condition *c, char **env) {
858 assert(c);
859 assert(c->parameter);
860 assert(c->type == CONDITION_PATH_EXISTS);
861
862 return access(c->parameter, F_OK) >= 0;
863 }
864
865 static int condition_test_path_exists_glob(Condition *c, char **env) {
866 assert(c);
867 assert(c->parameter);
868 assert(c->type == CONDITION_PATH_EXISTS_GLOB);
869
870 return glob_exists(c->parameter) > 0;
871 }
872
873 static int condition_test_path_is_directory(Condition *c, char **env) {
874 assert(c);
875 assert(c->parameter);
876 assert(c->type == CONDITION_PATH_IS_DIRECTORY);
877
878 return is_dir(c->parameter, true) > 0;
879 }
880
881 static int condition_test_path_is_symbolic_link(Condition *c, char **env) {
882 assert(c);
883 assert(c->parameter);
884 assert(c->type == CONDITION_PATH_IS_SYMBOLIC_LINK);
885
886 return is_symlink(c->parameter) > 0;
887 }
888
889 static int condition_test_path_is_mount_point(Condition *c, char **env) {
890 assert(c);
891 assert(c->parameter);
892 assert(c->type == CONDITION_PATH_IS_MOUNT_POINT);
893
894 return path_is_mount_point(c->parameter, NULL, AT_SYMLINK_FOLLOW) > 0;
895 }
896
897 static int condition_test_path_is_read_write(Condition *c, char **env) {
898 int r;
899
900 assert(c);
901 assert(c->parameter);
902 assert(c->type == CONDITION_PATH_IS_READ_WRITE);
903
904 r = path_is_read_only_fs(c->parameter);
905
906 return r <= 0 && r != -ENOENT;
907 }
908
909 static int condition_test_cpufeature(Condition *c, char **env) {
910 assert(c);
911 assert(c->parameter);
912 assert(c->type == CONDITION_CPU_FEATURE);
913
914 return has_cpu_with_flag(ascii_strlower(c->parameter));
915 }
916
917 static int condition_test_path_is_encrypted(Condition *c, char **env) {
918 int r;
919
920 assert(c);
921 assert(c->parameter);
922 assert(c->type == CONDITION_PATH_IS_ENCRYPTED);
923
924 r = path_is_encrypted(c->parameter);
925 if (r < 0 && r != -ENOENT)
926 log_debug_errno(r, "Failed to determine if '%s' is encrypted: %m", c->parameter);
927
928 return r > 0;
929 }
930
931 static int condition_test_directory_not_empty(Condition *c, char **env) {
932 int r;
933
934 assert(c);
935 assert(c->parameter);
936 assert(c->type == CONDITION_DIRECTORY_NOT_EMPTY);
937
938 r = dir_is_empty(c->parameter);
939 return r <= 0 && !IN_SET(r, -ENOENT, -ENOTDIR);
940 }
941
942 static int condition_test_file_not_empty(Condition *c, char **env) {
943 struct stat st;
944
945 assert(c);
946 assert(c->parameter);
947 assert(c->type == CONDITION_FILE_NOT_EMPTY);
948
949 return (stat(c->parameter, &st) >= 0 &&
950 S_ISREG(st.st_mode) &&
951 st.st_size > 0);
952 }
953
954 static int condition_test_file_is_executable(Condition *c, char **env) {
955 struct stat st;
956
957 assert(c);
958 assert(c->parameter);
959 assert(c->type == CONDITION_FILE_IS_EXECUTABLE);
960
961 return (stat(c->parameter, &st) >= 0 &&
962 S_ISREG(st.st_mode) &&
963 (st.st_mode & 0111));
964 }
965
966 static int condition_test_psi(Condition *c, char **env) {
967 _cleanup_free_ char *first = NULL, *second = NULL, *third = NULL, *fourth = NULL, *pressure_path = NULL;
968 const char *p, *value, *pressure_type;
969 loadavg_t *current, limit;
970 ResourcePressure pressure;
971 int r;
972
973 assert(c);
974 assert(c->parameter);
975 assert(IN_SET(c->type, CONDITION_MEMORY_PRESSURE, CONDITION_CPU_PRESSURE, CONDITION_IO_PRESSURE));
976
977 if (!is_pressure_supported()) {
978 log_debug("Pressure Stall Information (PSI) is not supported, skipping.");
979 return 1;
980 }
981
982 pressure_type = c->type == CONDITION_MEMORY_PRESSURE ? "memory" :
983 c->type == CONDITION_CPU_PRESSURE ? "cpu" :
984 "io";
985
986 p = c->parameter;
987 r = extract_many_words(&p, ":", 0, &first, &second, NULL);
988 if (r <= 0)
989 return log_debug_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
990 /* If only one parameter is passed, then we look at the global system pressure rather than a specific cgroup. */
991 if (r == 1) {
992 pressure_path = path_join("/proc/pressure", pressure_type);
993 if (!pressure_path)
994 return log_oom_debug();
995
996 value = first;
997 } else {
998 const char *controller = strjoina(pressure_type, ".pressure");
999 _cleanup_free_ char *slice_path = NULL, *root_scope = NULL;
1000 CGroupMask mask, required_mask;
1001 char *slice, *e;
1002
1003 required_mask = c->type == CONDITION_MEMORY_PRESSURE ? CGROUP_MASK_MEMORY :
1004 c->type == CONDITION_CPU_PRESSURE ? CGROUP_MASK_CPU :
1005 CGROUP_MASK_IO;
1006
1007 slice = strstrip(first);
1008 if (!slice)
1009 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1010
1011 r = cg_all_unified();
1012 if (r < 0)
1013 return log_debug_errno(r, "Failed to determine whether the unified cgroups hierarchy is used: %m");
1014 if (r == 0) {
1015 log_debug("PSI condition check requires the unified cgroups hierarchy, skipping.");
1016 return 1;
1017 }
1018
1019 r = cg_mask_supported(&mask);
1020 if (r < 0)
1021 return log_debug_errno(r, "Failed to get supported cgroup controllers: %m");
1022
1023 if (!FLAGS_SET(mask, required_mask)) {
1024 log_debug("Cgroup %s controller not available, skipping PSI condition check.", pressure_type);
1025 return 1;
1026 }
1027
1028 r = cg_slice_to_path(slice, &slice_path);
1029 if (r < 0)
1030 return log_debug_errno(r, "Cannot determine slice \"%s\" cgroup path: %m", slice);
1031
1032 /* We might be running under the user manager, so get the root path and prefix it accordingly. */
1033 r = cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER, getpid_cached(), &root_scope);
1034 if (r < 0)
1035 return log_debug_errno(r, "Failed to get root cgroup path: %m");
1036
1037 /* Drop init.scope, we want the parent. We could get an empty or / path, but that's fine,
1038 * just skip it in that case. */
1039 e = endswith(root_scope, "/" SPECIAL_INIT_SCOPE);
1040 if (e)
1041 *e = 0;
1042 if (!empty_or_root(root_scope)) {
1043 _cleanup_free_ char *slice_joined = NULL;
1044
1045 slice_joined = path_join(root_scope, slice_path);
1046 if (!slice_joined)
1047 return log_oom_debug();
1048
1049 free_and_replace(slice_path, slice_joined);
1050 }
1051
1052 r = cg_get_path(SYSTEMD_CGROUP_CONTROLLER, slice_path, controller, &pressure_path);
1053 if (r < 0)
1054 return log_debug_errno(r, "Error getting cgroup pressure path from %s: %m", slice_path);
1055
1056 value = second;
1057 }
1058
1059 /* If a value including a specific timespan (in the intervals allowed by the kernel),
1060 * parse it, otherwise we assume just a plain percentage that will be checked if it is
1061 * smaller or equal to the current pressure average over 5 minutes. */
1062 r = extract_many_words(&value, "/", 0, &third, &fourth, NULL);
1063 if (r <= 0)
1064 return log_debug_errno(r < 0 ? r : SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1065 if (r == 1)
1066 current = &pressure.avg300;
1067 else {
1068 const char *timespan;
1069
1070 timespan = skip_leading_chars(fourth, NULL);
1071 if (!timespan)
1072 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1073
1074 if (startswith(timespan, "10sec"))
1075 current = &pressure.avg10;
1076 else if (startswith(timespan, "1min"))
1077 current = &pressure.avg60;
1078 else if (startswith(timespan, "5min"))
1079 current = &pressure.avg300;
1080 else
1081 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1082 }
1083
1084 value = strstrip(third);
1085 if (!value)
1086 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL), "Failed to parse condition parameter %s: %m", c->parameter);
1087
1088 r = parse_permyriad(value);
1089 if (r < 0)
1090 return log_debug_errno(r, "Failed to parse permyriad: %s", c->parameter);
1091
1092 r = store_loadavg_fixed_point(r / 100LU, r % 100LU, &limit);
1093 if (r < 0)
1094 return log_debug_errno(r, "Failed to parse loadavg: %s", c->parameter);
1095
1096 r = read_resource_pressure(pressure_path, PRESSURE_TYPE_FULL, &pressure);
1097 if (r == -ENODATA) /* cpu.pressure 'full' was added recently, fall back to 'some'. */
1098 r = read_resource_pressure(pressure_path, PRESSURE_TYPE_SOME, &pressure);
1099 if (r == -ENOENT) {
1100 /* We already checked that /proc/pressure exists, so this means we were given a cgroup
1101 * that doesn't exist or doesn't exist any longer. */
1102 log_debug("\"%s\" not found, skipping PSI check.", pressure_path);
1103 return 1;
1104 }
1105 if (r < 0)
1106 return log_debug_errno(r, "Error parsing pressure from %s: %m", pressure_path);
1107
1108 return *current <= limit;
1109 }
1110
1111 int condition_test(Condition *c, char **env) {
1112
1113 static int (*const condition_tests[_CONDITION_TYPE_MAX])(Condition *c, char **env) = {
1114 [CONDITION_PATH_EXISTS] = condition_test_path_exists,
1115 [CONDITION_PATH_EXISTS_GLOB] = condition_test_path_exists_glob,
1116 [CONDITION_PATH_IS_DIRECTORY] = condition_test_path_is_directory,
1117 [CONDITION_PATH_IS_SYMBOLIC_LINK] = condition_test_path_is_symbolic_link,
1118 [CONDITION_PATH_IS_MOUNT_POINT] = condition_test_path_is_mount_point,
1119 [CONDITION_PATH_IS_READ_WRITE] = condition_test_path_is_read_write,
1120 [CONDITION_PATH_IS_ENCRYPTED] = condition_test_path_is_encrypted,
1121 [CONDITION_DIRECTORY_NOT_EMPTY] = condition_test_directory_not_empty,
1122 [CONDITION_FILE_NOT_EMPTY] = condition_test_file_not_empty,
1123 [CONDITION_FILE_IS_EXECUTABLE] = condition_test_file_is_executable,
1124 [CONDITION_KERNEL_COMMAND_LINE] = condition_test_kernel_command_line,
1125 [CONDITION_KERNEL_VERSION] = condition_test_kernel_version,
1126 [CONDITION_VIRTUALIZATION] = condition_test_virtualization,
1127 [CONDITION_SECURITY] = condition_test_security,
1128 [CONDITION_CAPABILITY] = condition_test_capability,
1129 [CONDITION_HOST] = condition_test_host,
1130 [CONDITION_AC_POWER] = condition_test_ac_power,
1131 [CONDITION_ARCHITECTURE] = condition_test_architecture,
1132 [CONDITION_FIRMWARE] = condition_test_firmware,
1133 [CONDITION_NEEDS_UPDATE] = condition_test_needs_update,
1134 [CONDITION_FIRST_BOOT] = condition_test_first_boot,
1135 [CONDITION_USER] = condition_test_user,
1136 [CONDITION_GROUP] = condition_test_group,
1137 [CONDITION_CONTROL_GROUP_CONTROLLER] = condition_test_control_group_controller,
1138 [CONDITION_CPUS] = condition_test_cpus,
1139 [CONDITION_MEMORY] = condition_test_memory,
1140 [CONDITION_ENVIRONMENT] = condition_test_environment,
1141 [CONDITION_CPU_FEATURE] = condition_test_cpufeature,
1142 [CONDITION_OS_RELEASE] = condition_test_osrelease,
1143 [CONDITION_MEMORY_PRESSURE] = condition_test_psi,
1144 [CONDITION_CPU_PRESSURE] = condition_test_psi,
1145 [CONDITION_IO_PRESSURE] = condition_test_psi,
1146 };
1147
1148 int r, b;
1149
1150 assert(c);
1151 assert(c->type >= 0);
1152 assert(c->type < _CONDITION_TYPE_MAX);
1153
1154 r = condition_tests[c->type](c, env);
1155 if (r < 0) {
1156 c->result = CONDITION_ERROR;
1157 return r;
1158 }
1159
1160 b = (r > 0) == !c->negate;
1161 c->result = b ? CONDITION_SUCCEEDED : CONDITION_FAILED;
1162 return b;
1163 }
1164
1165 bool condition_test_list(
1166 Condition *first,
1167 char **env,
1168 condition_to_string_t to_string,
1169 condition_test_logger_t logger,
1170 void *userdata) {
1171
1172 int triggered = -1;
1173
1174 assert(!!logger == !!to_string);
1175
1176 /* If the condition list is empty, then it is true */
1177 if (!first)
1178 return true;
1179
1180 /* Otherwise, if all of the non-trigger conditions apply and
1181 * if any of the trigger conditions apply (unless there are
1182 * none) we return true */
1183 LIST_FOREACH(conditions, c, first) {
1184 int r;
1185
1186 r = condition_test(c, env);
1187
1188 if (logger) {
1189 if (r < 0)
1190 logger(userdata, LOG_WARNING, r, PROJECT_FILE, __LINE__, __func__,
1191 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
1192 to_string(c->type),
1193 c->trigger ? "|" : "",
1194 c->negate ? "!" : "",
1195 c->parameter);
1196 else
1197 logger(userdata, LOG_DEBUG, 0, PROJECT_FILE, __LINE__, __func__,
1198 "%s=%s%s%s %s.",
1199 to_string(c->type),
1200 c->trigger ? "|" : "",
1201 c->negate ? "!" : "",
1202 c->parameter,
1203 condition_result_to_string(c->result));
1204 }
1205
1206 if (!c->trigger && r <= 0)
1207 return false;
1208
1209 if (c->trigger && triggered <= 0)
1210 triggered = r > 0;
1211 }
1212
1213 return triggered != 0;
1214 }
1215
1216 void condition_dump(Condition *c, FILE *f, const char *prefix, condition_to_string_t to_string) {
1217 assert(c);
1218 assert(f);
1219 assert(to_string);
1220
1221 prefix = strempty(prefix);
1222
1223 fprintf(f,
1224 "%s\t%s: %s%s%s %s\n",
1225 prefix,
1226 to_string(c->type),
1227 c->trigger ? "|" : "",
1228 c->negate ? "!" : "",
1229 c->parameter,
1230 condition_result_to_string(c->result));
1231 }
1232
1233 void condition_dump_list(Condition *first, FILE *f, const char *prefix, condition_to_string_t to_string) {
1234 LIST_FOREACH(conditions, c, first)
1235 condition_dump(c, f, prefix, to_string);
1236 }
1237
1238 static const char* const condition_type_table[_CONDITION_TYPE_MAX] = {
1239 [CONDITION_ARCHITECTURE] = "ConditionArchitecture",
1240 [CONDITION_FIRMWARE] = "ConditionFirmware",
1241 [CONDITION_VIRTUALIZATION] = "ConditionVirtualization",
1242 [CONDITION_HOST] = "ConditionHost",
1243 [CONDITION_KERNEL_COMMAND_LINE] = "ConditionKernelCommandLine",
1244 [CONDITION_KERNEL_VERSION] = "ConditionKernelVersion",
1245 [CONDITION_SECURITY] = "ConditionSecurity",
1246 [CONDITION_CAPABILITY] = "ConditionCapability",
1247 [CONDITION_AC_POWER] = "ConditionACPower",
1248 [CONDITION_NEEDS_UPDATE] = "ConditionNeedsUpdate",
1249 [CONDITION_FIRST_BOOT] = "ConditionFirstBoot",
1250 [CONDITION_PATH_EXISTS] = "ConditionPathExists",
1251 [CONDITION_PATH_EXISTS_GLOB] = "ConditionPathExistsGlob",
1252 [CONDITION_PATH_IS_DIRECTORY] = "ConditionPathIsDirectory",
1253 [CONDITION_PATH_IS_SYMBOLIC_LINK] = "ConditionPathIsSymbolicLink",
1254 [CONDITION_PATH_IS_MOUNT_POINT] = "ConditionPathIsMountPoint",
1255 [CONDITION_PATH_IS_READ_WRITE] = "ConditionPathIsReadWrite",
1256 [CONDITION_PATH_IS_ENCRYPTED] = "ConditionPathIsEncrypted",
1257 [CONDITION_DIRECTORY_NOT_EMPTY] = "ConditionDirectoryNotEmpty",
1258 [CONDITION_FILE_NOT_EMPTY] = "ConditionFileNotEmpty",
1259 [CONDITION_FILE_IS_EXECUTABLE] = "ConditionFileIsExecutable",
1260 [CONDITION_USER] = "ConditionUser",
1261 [CONDITION_GROUP] = "ConditionGroup",
1262 [CONDITION_CONTROL_GROUP_CONTROLLER] = "ConditionControlGroupController",
1263 [CONDITION_CPUS] = "ConditionCPUs",
1264 [CONDITION_MEMORY] = "ConditionMemory",
1265 [CONDITION_ENVIRONMENT] = "ConditionEnvironment",
1266 [CONDITION_CPU_FEATURE] = "ConditionCPUFeature",
1267 [CONDITION_OS_RELEASE] = "ConditionOSRelease",
1268 [CONDITION_MEMORY_PRESSURE] = "ConditionMemoryPressure",
1269 [CONDITION_CPU_PRESSURE] = "ConditionCPUPressure",
1270 [CONDITION_IO_PRESSURE] = "ConditionIOPressure",
1271 };
1272
1273 DEFINE_STRING_TABLE_LOOKUP(condition_type, ConditionType);
1274
1275 static const char* const assert_type_table[_CONDITION_TYPE_MAX] = {
1276 [CONDITION_ARCHITECTURE] = "AssertArchitecture",
1277 [CONDITION_FIRMWARE] = "AssertFirmware",
1278 [CONDITION_VIRTUALIZATION] = "AssertVirtualization",
1279 [CONDITION_HOST] = "AssertHost",
1280 [CONDITION_KERNEL_COMMAND_LINE] = "AssertKernelCommandLine",
1281 [CONDITION_KERNEL_VERSION] = "AssertKernelVersion",
1282 [CONDITION_SECURITY] = "AssertSecurity",
1283 [CONDITION_CAPABILITY] = "AssertCapability",
1284 [CONDITION_AC_POWER] = "AssertACPower",
1285 [CONDITION_NEEDS_UPDATE] = "AssertNeedsUpdate",
1286 [CONDITION_FIRST_BOOT] = "AssertFirstBoot",
1287 [CONDITION_PATH_EXISTS] = "AssertPathExists",
1288 [CONDITION_PATH_EXISTS_GLOB] = "AssertPathExistsGlob",
1289 [CONDITION_PATH_IS_DIRECTORY] = "AssertPathIsDirectory",
1290 [CONDITION_PATH_IS_SYMBOLIC_LINK] = "AssertPathIsSymbolicLink",
1291 [CONDITION_PATH_IS_MOUNT_POINT] = "AssertPathIsMountPoint",
1292 [CONDITION_PATH_IS_READ_WRITE] = "AssertPathIsReadWrite",
1293 [CONDITION_PATH_IS_ENCRYPTED] = "AssertPathIsEncrypted",
1294 [CONDITION_DIRECTORY_NOT_EMPTY] = "AssertDirectoryNotEmpty",
1295 [CONDITION_FILE_NOT_EMPTY] = "AssertFileNotEmpty",
1296 [CONDITION_FILE_IS_EXECUTABLE] = "AssertFileIsExecutable",
1297 [CONDITION_USER] = "AssertUser",
1298 [CONDITION_GROUP] = "AssertGroup",
1299 [CONDITION_CONTROL_GROUP_CONTROLLER] = "AssertControlGroupController",
1300 [CONDITION_CPUS] = "AssertCPUs",
1301 [CONDITION_MEMORY] = "AssertMemory",
1302 [CONDITION_ENVIRONMENT] = "AssertEnvironment",
1303 [CONDITION_CPU_FEATURE] = "AssertCPUFeature",
1304 [CONDITION_OS_RELEASE] = "AssertOSRelease",
1305 [CONDITION_MEMORY_PRESSURE] = "AssertMemoryPressure",
1306 [CONDITION_CPU_PRESSURE] = "AssertCPUPressure",
1307 [CONDITION_IO_PRESSURE] = "AssertIOPressure",
1308 };
1309
1310 DEFINE_STRING_TABLE_LOOKUP(assert_type, ConditionType);
1311
1312 static const char* const condition_result_table[_CONDITION_RESULT_MAX] = {
1313 [CONDITION_UNTESTED] = "untested",
1314 [CONDITION_SUCCEEDED] = "succeeded",
1315 [CONDITION_FAILED] = "failed",
1316 [CONDITION_ERROR] = "error",
1317 };
1318
1319 DEFINE_STRING_TABLE_LOOKUP(condition_result, ConditionResult);