]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/condition.c
Add support for conditions on the machines firmware
[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 (!path_is_absolute(c->parameter)) {
679 log_debug("Specified condition parameter '%s' is not absolute, assuming an update is needed.", c->parameter);
680 return true;
681 }
682
683 /* If the file system is read-only we shouldn't suggest an update */
684 r = path_is_read_only_fs(c->parameter);
685 if (r < 0)
686 log_debug_errno(r, "Failed to determine if '%s' is read-only, ignoring: %m", c->parameter);
687 if (r > 0)
688 return false;
689
690 /* Any other failure means we should allow the condition to be true, so that we rather invoke too
691 * many update tools than too few. */
692
693 p = strjoina(c->parameter, "/.updated");
694 if (lstat(p, &other) < 0) {
695 if (errno != ENOENT)
696 log_debug_errno(errno, "Failed to stat() '%s', assuming an update is needed: %m", p);
697 return true;
698 }
699
700 if (lstat("/usr/", &usr) < 0) {
701 log_debug_errno(errno, "Failed to stat() /usr/, assuming an update is needed: %m");
702 return true;
703 }
704
705 /*
706 * First, compare seconds as they are always accurate...
707 */
708 if (usr.st_mtim.tv_sec != other.st_mtim.tv_sec)
709 return usr.st_mtim.tv_sec > other.st_mtim.tv_sec;
710
711 /*
712 * ...then compare nanoseconds.
713 *
714 * A false positive is only possible when /usr's nanoseconds > 0
715 * (otherwise /usr cannot be strictly newer than the target file)
716 * AND the target file's nanoseconds == 0
717 * (otherwise the filesystem supports nsec timestamps, see stat(2)).
718 */
719 if (usr.st_mtim.tv_nsec == 0 || other.st_mtim.tv_nsec > 0)
720 return usr.st_mtim.tv_nsec > other.st_mtim.tv_nsec;
721
722 _cleanup_free_ char *timestamp_str = NULL;
723 r = parse_env_file(NULL, p, "TIMESTAMP_NSEC", &timestamp_str);
724 if (r < 0) {
725 log_debug_errno(r, "Failed to parse timestamp file '%s', using mtime: %m", p);
726 return true;
727 } else if (r == 0) {
728 log_debug("No data in timestamp file '%s', using mtime.", p);
729 return true;
730 }
731
732 uint64_t timestamp;
733 r = safe_atou64(timestamp_str, &timestamp);
734 if (r < 0) {
735 log_debug_errno(r, "Failed to parse timestamp value '%s' in file '%s', using mtime: %m", timestamp_str, p);
736 return true;
737 }
738
739 return timespec_load_nsec(&usr.st_mtim) > timestamp;
740 }
741
742 static int condition_test_first_boot(Condition *c, char **env) {
743 int r, q;
744 bool b;
745
746 assert(c);
747 assert(c->parameter);
748 assert(c->type == CONDITION_FIRST_BOOT);
749
750 r = proc_cmdline_get_bool("systemd.condition-first-boot", &b);
751 if (r < 0)
752 log_debug_errno(r, "Failed to parse systemd.condition-first-boot= kernel command line argument, ignoring: %m");
753 if (r > 0)
754 return b == !!r;
755
756 r = parse_boolean(c->parameter);
757 if (r < 0)
758 return r;
759
760 q = access("/run/systemd/first-boot", F_OK);
761 if (q < 0 && errno != ENOENT)
762 log_debug_errno(errno, "Failed to check if /run/systemd/first-boot exists, ignoring: %m");
763
764 return (q >= 0) == !!r;
765 }
766
767 static int condition_test_environment(Condition *c, char **env) {
768 bool equal;
769 char **i;
770
771 assert(c);
772 assert(c->parameter);
773 assert(c->type == CONDITION_ENVIRONMENT);
774
775 equal = strchr(c->parameter, '=');
776
777 STRV_FOREACH(i, env) {
778 bool found;
779
780 if (equal)
781 found = streq(c->parameter, *i);
782 else {
783 const char *f;
784
785 f = startswith(*i, c->parameter);
786 found = f && IN_SET(*f, 0, '=');
787 }
788
789 if (found)
790 return true;
791 }
792
793 return false;
794 }
795
796 static int condition_test_path_exists(Condition *c, char **env) {
797 assert(c);
798 assert(c->parameter);
799 assert(c->type == CONDITION_PATH_EXISTS);
800
801 return access(c->parameter, F_OK) >= 0;
802 }
803
804 static int condition_test_path_exists_glob(Condition *c, char **env) {
805 assert(c);
806 assert(c->parameter);
807 assert(c->type == CONDITION_PATH_EXISTS_GLOB);
808
809 return glob_exists(c->parameter) > 0;
810 }
811
812 static int condition_test_path_is_directory(Condition *c, char **env) {
813 assert(c);
814 assert(c->parameter);
815 assert(c->type == CONDITION_PATH_IS_DIRECTORY);
816
817 return is_dir(c->parameter, true) > 0;
818 }
819
820 static int condition_test_path_is_symbolic_link(Condition *c, char **env) {
821 assert(c);
822 assert(c->parameter);
823 assert(c->type == CONDITION_PATH_IS_SYMBOLIC_LINK);
824
825 return is_symlink(c->parameter) > 0;
826 }
827
828 static int condition_test_path_is_mount_point(Condition *c, char **env) {
829 assert(c);
830 assert(c->parameter);
831 assert(c->type == CONDITION_PATH_IS_MOUNT_POINT);
832
833 return path_is_mount_point(c->parameter, NULL, AT_SYMLINK_FOLLOW) > 0;
834 }
835
836 static int condition_test_path_is_read_write(Condition *c, char **env) {
837 assert(c);
838 assert(c->parameter);
839 assert(c->type == CONDITION_PATH_IS_READ_WRITE);
840
841 return path_is_read_only_fs(c->parameter) <= 0;
842 }
843
844 static int condition_test_cpufeature(Condition *c, char **env) {
845 assert(c);
846 assert(c->parameter);
847 assert(c->type == CONDITION_CPU_FEATURE);
848
849 return has_cpu_with_flag(ascii_strlower(c->parameter));
850 }
851
852 static int condition_test_path_is_encrypted(Condition *c, char **env) {
853 int r;
854
855 assert(c);
856 assert(c->parameter);
857 assert(c->type == CONDITION_PATH_IS_ENCRYPTED);
858
859 r = path_is_encrypted(c->parameter);
860 if (r < 0 && r != -ENOENT)
861 log_debug_errno(r, "Failed to determine if '%s' is encrypted: %m", c->parameter);
862
863 return r > 0;
864 }
865
866 static int condition_test_directory_not_empty(Condition *c, char **env) {
867 int r;
868
869 assert(c);
870 assert(c->parameter);
871 assert(c->type == CONDITION_DIRECTORY_NOT_EMPTY);
872
873 r = dir_is_empty(c->parameter);
874 return r <= 0 && r != -ENOENT;
875 }
876
877 static int condition_test_file_not_empty(Condition *c, char **env) {
878 struct stat st;
879
880 assert(c);
881 assert(c->parameter);
882 assert(c->type == CONDITION_FILE_NOT_EMPTY);
883
884 return (stat(c->parameter, &st) >= 0 &&
885 S_ISREG(st.st_mode) &&
886 st.st_size > 0);
887 }
888
889 static int condition_test_file_is_executable(Condition *c, char **env) {
890 struct stat st;
891
892 assert(c);
893 assert(c->parameter);
894 assert(c->type == CONDITION_FILE_IS_EXECUTABLE);
895
896 return (stat(c->parameter, &st) >= 0 &&
897 S_ISREG(st.st_mode) &&
898 (st.st_mode & 0111));
899 }
900
901 int condition_test(Condition *c, char **env) {
902
903 static int (*const condition_tests[_CONDITION_TYPE_MAX])(Condition *c, char **env) = {
904 [CONDITION_PATH_EXISTS] = condition_test_path_exists,
905 [CONDITION_PATH_EXISTS_GLOB] = condition_test_path_exists_glob,
906 [CONDITION_PATH_IS_DIRECTORY] = condition_test_path_is_directory,
907 [CONDITION_PATH_IS_SYMBOLIC_LINK] = condition_test_path_is_symbolic_link,
908 [CONDITION_PATH_IS_MOUNT_POINT] = condition_test_path_is_mount_point,
909 [CONDITION_PATH_IS_READ_WRITE] = condition_test_path_is_read_write,
910 [CONDITION_PATH_IS_ENCRYPTED] = condition_test_path_is_encrypted,
911 [CONDITION_DIRECTORY_NOT_EMPTY] = condition_test_directory_not_empty,
912 [CONDITION_FILE_NOT_EMPTY] = condition_test_file_not_empty,
913 [CONDITION_FILE_IS_EXECUTABLE] = condition_test_file_is_executable,
914 [CONDITION_KERNEL_COMMAND_LINE] = condition_test_kernel_command_line,
915 [CONDITION_KERNEL_VERSION] = condition_test_kernel_version,
916 [CONDITION_VIRTUALIZATION] = condition_test_virtualization,
917 [CONDITION_SECURITY] = condition_test_security,
918 [CONDITION_CAPABILITY] = condition_test_capability,
919 [CONDITION_HOST] = condition_test_host,
920 [CONDITION_AC_POWER] = condition_test_ac_power,
921 [CONDITION_ARCHITECTURE] = condition_test_architecture,
922 [CONDITION_FIRMWARE] = condition_test_firmware,
923 [CONDITION_NEEDS_UPDATE] = condition_test_needs_update,
924 [CONDITION_FIRST_BOOT] = condition_test_first_boot,
925 [CONDITION_USER] = condition_test_user,
926 [CONDITION_GROUP] = condition_test_group,
927 [CONDITION_CONTROL_GROUP_CONTROLLER] = condition_test_control_group_controller,
928 [CONDITION_CPUS] = condition_test_cpus,
929 [CONDITION_MEMORY] = condition_test_memory,
930 [CONDITION_ENVIRONMENT] = condition_test_environment,
931 [CONDITION_CPU_FEATURE] = condition_test_cpufeature,
932 };
933
934 int r, b;
935
936 assert(c);
937 assert(c->type >= 0);
938 assert(c->type < _CONDITION_TYPE_MAX);
939
940 r = condition_tests[c->type](c, env);
941 if (r < 0) {
942 c->result = CONDITION_ERROR;
943 return r;
944 }
945
946 b = (r > 0) == !c->negate;
947 c->result = b ? CONDITION_SUCCEEDED : CONDITION_FAILED;
948 return b;
949 }
950
951 bool condition_test_list(
952 Condition *first,
953 char **env,
954 condition_to_string_t to_string,
955 condition_test_logger_t logger,
956 void *userdata) {
957
958 Condition *c;
959 int triggered = -1;
960
961 assert(!!logger == !!to_string);
962
963 /* If the condition list is empty, then it is true */
964 if (!first)
965 return true;
966
967 /* Otherwise, if all of the non-trigger conditions apply and
968 * if any of the trigger conditions apply (unless there are
969 * none) we return true */
970 LIST_FOREACH(conditions, c, first) {
971 int r;
972
973 r = condition_test(c, env);
974
975 if (logger) {
976 if (r < 0)
977 logger(userdata, LOG_WARNING, r, PROJECT_FILE, __LINE__, __func__,
978 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
979 to_string(c->type),
980 c->trigger ? "|" : "",
981 c->negate ? "!" : "",
982 c->parameter);
983 else
984 logger(userdata, LOG_DEBUG, 0, PROJECT_FILE, __LINE__, __func__,
985 "%s=%s%s%s %s.",
986 to_string(c->type),
987 c->trigger ? "|" : "",
988 c->negate ? "!" : "",
989 c->parameter,
990 condition_result_to_string(c->result));
991 }
992
993 if (!c->trigger && r <= 0)
994 return false;
995
996 if (c->trigger && triggered <= 0)
997 triggered = r > 0;
998 }
999
1000 return triggered != 0;
1001 }
1002
1003 void condition_dump(Condition *c, FILE *f, const char *prefix, condition_to_string_t to_string) {
1004 assert(c);
1005 assert(f);
1006 assert(to_string);
1007
1008 prefix = strempty(prefix);
1009
1010 fprintf(f,
1011 "%s\t%s: %s%s%s %s\n",
1012 prefix,
1013 to_string(c->type),
1014 c->trigger ? "|" : "",
1015 c->negate ? "!" : "",
1016 c->parameter,
1017 condition_result_to_string(c->result));
1018 }
1019
1020 void condition_dump_list(Condition *first, FILE *f, const char *prefix, condition_to_string_t to_string) {
1021 Condition *c;
1022
1023 LIST_FOREACH(conditions, c, first)
1024 condition_dump(c, f, prefix, to_string);
1025 }
1026
1027 static const char* const condition_type_table[_CONDITION_TYPE_MAX] = {
1028 [CONDITION_ARCHITECTURE] = "ConditionArchitecture",
1029 [CONDITION_FIRMWARE] = "ConditionFirmware",
1030 [CONDITION_VIRTUALIZATION] = "ConditionVirtualization",
1031 [CONDITION_HOST] = "ConditionHost",
1032 [CONDITION_KERNEL_COMMAND_LINE] = "ConditionKernelCommandLine",
1033 [CONDITION_KERNEL_VERSION] = "ConditionKernelVersion",
1034 [CONDITION_SECURITY] = "ConditionSecurity",
1035 [CONDITION_CAPABILITY] = "ConditionCapability",
1036 [CONDITION_AC_POWER] = "ConditionACPower",
1037 [CONDITION_NEEDS_UPDATE] = "ConditionNeedsUpdate",
1038 [CONDITION_FIRST_BOOT] = "ConditionFirstBoot",
1039 [CONDITION_PATH_EXISTS] = "ConditionPathExists",
1040 [CONDITION_PATH_EXISTS_GLOB] = "ConditionPathExistsGlob",
1041 [CONDITION_PATH_IS_DIRECTORY] = "ConditionPathIsDirectory",
1042 [CONDITION_PATH_IS_SYMBOLIC_LINK] = "ConditionPathIsSymbolicLink",
1043 [CONDITION_PATH_IS_MOUNT_POINT] = "ConditionPathIsMountPoint",
1044 [CONDITION_PATH_IS_READ_WRITE] = "ConditionPathIsReadWrite",
1045 [CONDITION_PATH_IS_ENCRYPTED] = "ConditionPathIsEncrypted",
1046 [CONDITION_DIRECTORY_NOT_EMPTY] = "ConditionDirectoryNotEmpty",
1047 [CONDITION_FILE_NOT_EMPTY] = "ConditionFileNotEmpty",
1048 [CONDITION_FILE_IS_EXECUTABLE] = "ConditionFileIsExecutable",
1049 [CONDITION_USER] = "ConditionUser",
1050 [CONDITION_GROUP] = "ConditionGroup",
1051 [CONDITION_CONTROL_GROUP_CONTROLLER] = "ConditionControlGroupController",
1052 [CONDITION_CPUS] = "ConditionCPUs",
1053 [CONDITION_MEMORY] = "ConditionMemory",
1054 [CONDITION_ENVIRONMENT] = "ConditionEnvironment",
1055 [CONDITION_CPU_FEATURE] = "ConditionCPUFeature",
1056 };
1057
1058 DEFINE_STRING_TABLE_LOOKUP(condition_type, ConditionType);
1059
1060 static const char* const assert_type_table[_CONDITION_TYPE_MAX] = {
1061 [CONDITION_ARCHITECTURE] = "AssertArchitecture",
1062 [CONDITION_FIRMWARE] = "AssertFirmware",
1063 [CONDITION_VIRTUALIZATION] = "AssertVirtualization",
1064 [CONDITION_HOST] = "AssertHost",
1065 [CONDITION_KERNEL_COMMAND_LINE] = "AssertKernelCommandLine",
1066 [CONDITION_KERNEL_VERSION] = "AssertKernelVersion",
1067 [CONDITION_SECURITY] = "AssertSecurity",
1068 [CONDITION_CAPABILITY] = "AssertCapability",
1069 [CONDITION_AC_POWER] = "AssertACPower",
1070 [CONDITION_NEEDS_UPDATE] = "AssertNeedsUpdate",
1071 [CONDITION_FIRST_BOOT] = "AssertFirstBoot",
1072 [CONDITION_PATH_EXISTS] = "AssertPathExists",
1073 [CONDITION_PATH_EXISTS_GLOB] = "AssertPathExistsGlob",
1074 [CONDITION_PATH_IS_DIRECTORY] = "AssertPathIsDirectory",
1075 [CONDITION_PATH_IS_SYMBOLIC_LINK] = "AssertPathIsSymbolicLink",
1076 [CONDITION_PATH_IS_MOUNT_POINT] = "AssertPathIsMountPoint",
1077 [CONDITION_PATH_IS_READ_WRITE] = "AssertPathIsReadWrite",
1078 [CONDITION_PATH_IS_ENCRYPTED] = "AssertPathIsEncrypted",
1079 [CONDITION_DIRECTORY_NOT_EMPTY] = "AssertDirectoryNotEmpty",
1080 [CONDITION_FILE_NOT_EMPTY] = "AssertFileNotEmpty",
1081 [CONDITION_FILE_IS_EXECUTABLE] = "AssertFileIsExecutable",
1082 [CONDITION_USER] = "AssertUser",
1083 [CONDITION_GROUP] = "AssertGroup",
1084 [CONDITION_CONTROL_GROUP_CONTROLLER] = "AssertControlGroupController",
1085 [CONDITION_CPUS] = "AssertCPUs",
1086 [CONDITION_MEMORY] = "AssertMemory",
1087 [CONDITION_ENVIRONMENT] = "AssertEnvironment",
1088 [CONDITION_CPU_FEATURE] = "AssertCPUFeature",
1089 };
1090
1091 DEFINE_STRING_TABLE_LOOKUP(assert_type, ConditionType);
1092
1093 static const char* const condition_result_table[_CONDITION_RESULT_MAX] = {
1094 [CONDITION_UNTESTED] = "untested",
1095 [CONDITION_SUCCEEDED] = "succeeded",
1096 [CONDITION_FAILED] = "failed",
1097 [CONDITION_ERROR] = "error",
1098 };
1099
1100 DEFINE_STRING_TABLE_LOOKUP(condition_result, ConditionResult);