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