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