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