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