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