]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/shared/condition.c
shared: split out UID allocation range stuff from user-record.h
[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 "uid-alloc-range.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 "/proc/device-tree/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 /* /proc/device-tree/compatible consists of one or more strings, each ending in '\0'.
534 * So the last character in dtcompat must be a '\0'. */
535 if (dtcompat[size - 1] != '\0') {
536 log_debug("%s is in an unknown format, assuming machine is incompatible", DTCOMPAT_FILE);
537 return false;
538 }
539
540 dtcompatlist = strv_parse_nulstr(dtcompat, size);
541 if (!dtcompatlist)
542 return -ENOMEM;
543
544 return strv_contains(dtcompatlist, dtcarg);
545 }
546
547 static int condition_test_firmware(Condition *c, char **env) {
548 sd_char *dtc;
549
550 assert(c);
551 assert(c->parameter);
552 assert(c->type == CONDITION_FIRMWARE);
553
554 if (streq(c->parameter, "device-tree")) {
555 if (access("/sys/firmware/device-tree/", F_OK) < 0) {
556 if (errno != ENOENT)
557 log_debug_errno(errno, "Unexpected error when checking for /sys/firmware/device-tree/: %m");
558 return false;
559 } else
560 return true;
561 } else if ((dtc = startswith(c->parameter, "device-tree-compatible("))) {
562 _cleanup_free_ char *dtcarg = NULL;
563 char *end;
564
565 end = strchr(dtc, ')');
566 if (!end || *(end + 1) != '\0') {
567 log_debug("Malformed Firmware condition \"%s\"", c->parameter);
568 return false;
569 }
570
571 dtcarg = strndup(dtc, end - dtc);
572 if (!dtcarg)
573 return -ENOMEM;
574
575 return condition_test_firmware_devicetree_compatible(dtcarg);
576 } else if (streq(c->parameter, "uefi"))
577 return is_efi_boot();
578 else {
579 log_debug("Unsupported Firmware condition \"%s\"", c->parameter);
580 return false;
581 }
582 }
583
584 static int condition_test_host(Condition *c, char **env) {
585 _cleanup_free_ char *h = NULL;
586 sd_id128_t x, y;
587 int r;
588
589 assert(c);
590 assert(c->parameter);
591 assert(c->type == CONDITION_HOST);
592
593 if (sd_id128_from_string(c->parameter, &x) >= 0) {
594
595 r = sd_id128_get_machine(&y);
596 if (r < 0)
597 return r;
598
599 return sd_id128_equal(x, y);
600 }
601
602 h = gethostname_malloc();
603 if (!h)
604 return -ENOMEM;
605
606 return fnmatch(c->parameter, h, FNM_CASEFOLD) == 0;
607 }
608
609 static int condition_test_ac_power(Condition *c, char **env) {
610 int r;
611
612 assert(c);
613 assert(c->parameter);
614 assert(c->type == CONDITION_AC_POWER);
615
616 r = parse_boolean(c->parameter);
617 if (r < 0)
618 return r;
619
620 return (on_ac_power() != 0) == !!r;
621 }
622
623 static int has_tpm2(void) {
624 int r;
625
626 /* Checks whether the system has at least one TPM2 resource manager device, i.e. at least one "tpmrm"
627 * class device */
628
629 r = dir_is_empty("/sys/class/tpmrm");
630 if (r == 0)
631 return true; /* nice! we have a device */
632
633 /* Hmm, so Linux doesn't know of the TPM2 device (or we couldn't check for it), most likely because
634 * the driver wasn't loaded yet. Let's see if the firmware knows about a TPM2 device, in this
635 * case. This way we can answer the TPM2 question already during early boot (where we most likely
636 * need it) */
637 if (efi_has_tpm2())
638 return true;
639
640 /* OK, this didn't work either, in this case propagate the original errors */
641 if (r == -ENOENT)
642 return false;
643 if (r < 0)
644 return log_debug_errno(r, "Failed to determine whether system has TPM2 support: %m");
645
646 return !r;
647 }
648
649 static int condition_test_security(Condition *c, char **env) {
650 assert(c);
651 assert(c->parameter);
652 assert(c->type == CONDITION_SECURITY);
653
654 if (streq(c->parameter, "selinux"))
655 return mac_selinux_use();
656 if (streq(c->parameter, "smack"))
657 return mac_smack_use();
658 if (streq(c->parameter, "apparmor"))
659 return mac_apparmor_use();
660 if (streq(c->parameter, "audit"))
661 return use_audit();
662 if (streq(c->parameter, "ima"))
663 return use_ima();
664 if (streq(c->parameter, "tomoyo"))
665 return mac_tomoyo_use();
666 if (streq(c->parameter, "uefi-secureboot"))
667 return is_efi_secure_boot();
668 if (streq(c->parameter, "tpm2"))
669 return has_tpm2();
670
671 return false;
672 }
673
674 static int condition_test_capability(Condition *c, char **env) {
675 unsigned long long capabilities = (unsigned long long) -1;
676 _cleanup_fclose_ FILE *f = NULL;
677 int value, r;
678
679 assert(c);
680 assert(c->parameter);
681 assert(c->type == CONDITION_CAPABILITY);
682
683 /* If it's an invalid capability, we don't have it */
684 value = capability_from_name(c->parameter);
685 if (value < 0)
686 return -EINVAL;
687
688 /* If it's a valid capability we default to assume
689 * that we have it */
690
691 f = fopen("/proc/self/status", "re");
692 if (!f)
693 return -errno;
694
695 for (;;) {
696 _cleanup_free_ char *line = NULL;
697 const char *p;
698
699 r = read_line(f, LONG_LINE_MAX, &line);
700 if (r < 0)
701 return r;
702 if (r == 0)
703 break;
704
705 p = startswith(line, "CapBnd:");
706 if (p) {
707 if (sscanf(line+7, "%llx", &capabilities) != 1)
708 return -EIO;
709
710 break;
711 }
712 }
713
714 return !!(capabilities & (1ULL << value));
715 }
716
717 static int condition_test_needs_update(Condition *c, char **env) {
718 struct stat usr, other;
719 const char *p;
720 bool b;
721 int r;
722
723 assert(c);
724 assert(c->parameter);
725 assert(c->type == CONDITION_NEEDS_UPDATE);
726
727 r = proc_cmdline_get_bool("systemd.condition-needs-update", &b);
728 if (r < 0)
729 log_debug_errno(r, "Failed to parse systemd.condition-needs-update= kernel command line argument, ignoring: %m");
730 if (r > 0)
731 return b;
732
733 if (in_initrd()) {
734 log_debug("We are in an initrd, not doing any updates.");
735 return false;
736 }
737
738 if (!path_is_absolute(c->parameter)) {
739 log_debug("Specified condition parameter '%s' is not absolute, assuming an update is needed.", c->parameter);
740 return true;
741 }
742
743 /* If the file system is read-only we shouldn't suggest an update */
744 r = path_is_read_only_fs(c->parameter);
745 if (r < 0)
746 log_debug_errno(r, "Failed to determine if '%s' is read-only, ignoring: %m", c->parameter);
747 if (r > 0)
748 return false;
749
750 /* Any other failure means we should allow the condition to be true, so that we rather invoke too
751 * many update tools than too few. */
752
753 p = strjoina(c->parameter, "/.updated");
754 if (lstat(p, &other) < 0) {
755 if (errno != ENOENT)
756 log_debug_errno(errno, "Failed to stat() '%s', assuming an update is needed: %m", p);
757 return true;
758 }
759
760 if (lstat("/usr/", &usr) < 0) {
761 log_debug_errno(errno, "Failed to stat() /usr/, assuming an update is needed: %m");
762 return true;
763 }
764
765 /*
766 * First, compare seconds as they are always accurate...
767 */
768 if (usr.st_mtim.tv_sec != other.st_mtim.tv_sec)
769 return usr.st_mtim.tv_sec > other.st_mtim.tv_sec;
770
771 /*
772 * ...then compare nanoseconds.
773 *
774 * A false positive is only possible when /usr's nanoseconds > 0
775 * (otherwise /usr cannot be strictly newer than the target file)
776 * AND the target file's nanoseconds == 0
777 * (otherwise the filesystem supports nsec timestamps, see stat(2)).
778 */
779 if (usr.st_mtim.tv_nsec == 0 || other.st_mtim.tv_nsec > 0)
780 return usr.st_mtim.tv_nsec > other.st_mtim.tv_nsec;
781
782 _cleanup_free_ char *timestamp_str = NULL;
783 r = parse_env_file(NULL, p, "TIMESTAMP_NSEC", &timestamp_str);
784 if (r < 0) {
785 log_debug_errno(r, "Failed to parse timestamp file '%s', using mtime: %m", p);
786 return true;
787 } else if (r == 0) {
788 log_debug("No data in timestamp file '%s', using mtime.", p);
789 return true;
790 }
791
792 uint64_t timestamp;
793 r = safe_atou64(timestamp_str, &timestamp);
794 if (r < 0) {
795 log_debug_errno(r, "Failed to parse timestamp value '%s' in file '%s', using mtime: %m", timestamp_str, p);
796 return true;
797 }
798
799 return timespec_load_nsec(&usr.st_mtim) > timestamp;
800 }
801
802 static int condition_test_first_boot(Condition *c, char **env) {
803 int r, q;
804 bool b;
805
806 assert(c);
807 assert(c->parameter);
808 assert(c->type == CONDITION_FIRST_BOOT);
809
810 r = proc_cmdline_get_bool("systemd.condition-first-boot", &b);
811 if (r < 0)
812 log_debug_errno(r, "Failed to parse systemd.condition-first-boot= kernel command line argument, ignoring: %m");
813 if (r > 0)
814 return b == !!r;
815
816 r = parse_boolean(c->parameter);
817 if (r < 0)
818 return r;
819
820 q = access("/run/systemd/first-boot", F_OK);
821 if (q < 0 && errno != ENOENT)
822 log_debug_errno(errno, "Failed to check if /run/systemd/first-boot exists, ignoring: %m");
823
824 return (q >= 0) == !!r;
825 }
826
827 static int condition_test_environment(Condition *c, char **env) {
828 bool equal;
829 char **i;
830
831 assert(c);
832 assert(c->parameter);
833 assert(c->type == CONDITION_ENVIRONMENT);
834
835 equal = strchr(c->parameter, '=');
836
837 STRV_FOREACH(i, env) {
838 bool found;
839
840 if (equal)
841 found = streq(c->parameter, *i);
842 else {
843 const char *f;
844
845 f = startswith(*i, c->parameter);
846 found = f && IN_SET(*f, 0, '=');
847 }
848
849 if (found)
850 return true;
851 }
852
853 return false;
854 }
855
856 static int condition_test_path_exists(Condition *c, char **env) {
857 assert(c);
858 assert(c->parameter);
859 assert(c->type == CONDITION_PATH_EXISTS);
860
861 return access(c->parameter, F_OK) >= 0;
862 }
863
864 static int condition_test_path_exists_glob(Condition *c, char **env) {
865 assert(c);
866 assert(c->parameter);
867 assert(c->type == CONDITION_PATH_EXISTS_GLOB);
868
869 return glob_exists(c->parameter) > 0;
870 }
871
872 static int condition_test_path_is_directory(Condition *c, char **env) {
873 assert(c);
874 assert(c->parameter);
875 assert(c->type == CONDITION_PATH_IS_DIRECTORY);
876
877 return is_dir(c->parameter, true) > 0;
878 }
879
880 static int condition_test_path_is_symbolic_link(Condition *c, char **env) {
881 assert(c);
882 assert(c->parameter);
883 assert(c->type == CONDITION_PATH_IS_SYMBOLIC_LINK);
884
885 return is_symlink(c->parameter) > 0;
886 }
887
888 static int condition_test_path_is_mount_point(Condition *c, char **env) {
889 assert(c);
890 assert(c->parameter);
891 assert(c->type == CONDITION_PATH_IS_MOUNT_POINT);
892
893 return path_is_mount_point(c->parameter, NULL, AT_SYMLINK_FOLLOW) > 0;
894 }
895
896 static int condition_test_path_is_read_write(Condition *c, char **env) {
897 assert(c);
898 assert(c->parameter);
899 assert(c->type == CONDITION_PATH_IS_READ_WRITE);
900
901 return path_is_read_only_fs(c->parameter) <= 0;
902 }
903
904 static int condition_test_cpufeature(Condition *c, char **env) {
905 assert(c);
906 assert(c->parameter);
907 assert(c->type == CONDITION_CPU_FEATURE);
908
909 return has_cpu_with_flag(ascii_strlower(c->parameter));
910 }
911
912 static int condition_test_path_is_encrypted(Condition *c, char **env) {
913 int r;
914
915 assert(c);
916 assert(c->parameter);
917 assert(c->type == CONDITION_PATH_IS_ENCRYPTED);
918
919 r = path_is_encrypted(c->parameter);
920 if (r < 0 && r != -ENOENT)
921 log_debug_errno(r, "Failed to determine if '%s' is encrypted: %m", c->parameter);
922
923 return r > 0;
924 }
925
926 static int condition_test_directory_not_empty(Condition *c, char **env) {
927 int r;
928
929 assert(c);
930 assert(c->parameter);
931 assert(c->type == CONDITION_DIRECTORY_NOT_EMPTY);
932
933 r = dir_is_empty(c->parameter);
934 return r <= 0 && r != -ENOENT;
935 }
936
937 static int condition_test_file_not_empty(Condition *c, char **env) {
938 struct stat st;
939
940 assert(c);
941 assert(c->parameter);
942 assert(c->type == CONDITION_FILE_NOT_EMPTY);
943
944 return (stat(c->parameter, &st) >= 0 &&
945 S_ISREG(st.st_mode) &&
946 st.st_size > 0);
947 }
948
949 static int condition_test_file_is_executable(Condition *c, char **env) {
950 struct stat st;
951
952 assert(c);
953 assert(c->parameter);
954 assert(c->type == CONDITION_FILE_IS_EXECUTABLE);
955
956 return (stat(c->parameter, &st) >= 0 &&
957 S_ISREG(st.st_mode) &&
958 (st.st_mode & 0111));
959 }
960
961 int condition_test(Condition *c, char **env) {
962
963 static int (*const condition_tests[_CONDITION_TYPE_MAX])(Condition *c, char **env) = {
964 [CONDITION_PATH_EXISTS] = condition_test_path_exists,
965 [CONDITION_PATH_EXISTS_GLOB] = condition_test_path_exists_glob,
966 [CONDITION_PATH_IS_DIRECTORY] = condition_test_path_is_directory,
967 [CONDITION_PATH_IS_SYMBOLIC_LINK] = condition_test_path_is_symbolic_link,
968 [CONDITION_PATH_IS_MOUNT_POINT] = condition_test_path_is_mount_point,
969 [CONDITION_PATH_IS_READ_WRITE] = condition_test_path_is_read_write,
970 [CONDITION_PATH_IS_ENCRYPTED] = condition_test_path_is_encrypted,
971 [CONDITION_DIRECTORY_NOT_EMPTY] = condition_test_directory_not_empty,
972 [CONDITION_FILE_NOT_EMPTY] = condition_test_file_not_empty,
973 [CONDITION_FILE_IS_EXECUTABLE] = condition_test_file_is_executable,
974 [CONDITION_KERNEL_COMMAND_LINE] = condition_test_kernel_command_line,
975 [CONDITION_KERNEL_VERSION] = condition_test_kernel_version,
976 [CONDITION_VIRTUALIZATION] = condition_test_virtualization,
977 [CONDITION_SECURITY] = condition_test_security,
978 [CONDITION_CAPABILITY] = condition_test_capability,
979 [CONDITION_HOST] = condition_test_host,
980 [CONDITION_AC_POWER] = condition_test_ac_power,
981 [CONDITION_ARCHITECTURE] = condition_test_architecture,
982 [CONDITION_FIRMWARE] = condition_test_firmware,
983 [CONDITION_NEEDS_UPDATE] = condition_test_needs_update,
984 [CONDITION_FIRST_BOOT] = condition_test_first_boot,
985 [CONDITION_USER] = condition_test_user,
986 [CONDITION_GROUP] = condition_test_group,
987 [CONDITION_CONTROL_GROUP_CONTROLLER] = condition_test_control_group_controller,
988 [CONDITION_CPUS] = condition_test_cpus,
989 [CONDITION_MEMORY] = condition_test_memory,
990 [CONDITION_ENVIRONMENT] = condition_test_environment,
991 [CONDITION_CPU_FEATURE] = condition_test_cpufeature,
992 [CONDITION_OS_RELEASE] = condition_test_osrelease,
993 };
994
995 int r, b;
996
997 assert(c);
998 assert(c->type >= 0);
999 assert(c->type < _CONDITION_TYPE_MAX);
1000
1001 r = condition_tests[c->type](c, env);
1002 if (r < 0) {
1003 c->result = CONDITION_ERROR;
1004 return r;
1005 }
1006
1007 b = (r > 0) == !c->negate;
1008 c->result = b ? CONDITION_SUCCEEDED : CONDITION_FAILED;
1009 return b;
1010 }
1011
1012 bool condition_test_list(
1013 Condition *first,
1014 char **env,
1015 condition_to_string_t to_string,
1016 condition_test_logger_t logger,
1017 void *userdata) {
1018
1019 Condition *c;
1020 int triggered = -1;
1021
1022 assert(!!logger == !!to_string);
1023
1024 /* If the condition list is empty, then it is true */
1025 if (!first)
1026 return true;
1027
1028 /* Otherwise, if all of the non-trigger conditions apply and
1029 * if any of the trigger conditions apply (unless there are
1030 * none) we return true */
1031 LIST_FOREACH(conditions, c, first) {
1032 int r;
1033
1034 r = condition_test(c, env);
1035
1036 if (logger) {
1037 if (r < 0)
1038 logger(userdata, LOG_WARNING, r, PROJECT_FILE, __LINE__, __func__,
1039 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
1040 to_string(c->type),
1041 c->trigger ? "|" : "",
1042 c->negate ? "!" : "",
1043 c->parameter);
1044 else
1045 logger(userdata, LOG_DEBUG, 0, PROJECT_FILE, __LINE__, __func__,
1046 "%s=%s%s%s %s.",
1047 to_string(c->type),
1048 c->trigger ? "|" : "",
1049 c->negate ? "!" : "",
1050 c->parameter,
1051 condition_result_to_string(c->result));
1052 }
1053
1054 if (!c->trigger && r <= 0)
1055 return false;
1056
1057 if (c->trigger && triggered <= 0)
1058 triggered = r > 0;
1059 }
1060
1061 return triggered != 0;
1062 }
1063
1064 void condition_dump(Condition *c, FILE *f, const char *prefix, condition_to_string_t to_string) {
1065 assert(c);
1066 assert(f);
1067 assert(to_string);
1068
1069 prefix = strempty(prefix);
1070
1071 fprintf(f,
1072 "%s\t%s: %s%s%s %s\n",
1073 prefix,
1074 to_string(c->type),
1075 c->trigger ? "|" : "",
1076 c->negate ? "!" : "",
1077 c->parameter,
1078 condition_result_to_string(c->result));
1079 }
1080
1081 void condition_dump_list(Condition *first, FILE *f, const char *prefix, condition_to_string_t to_string) {
1082 Condition *c;
1083
1084 LIST_FOREACH(conditions, c, first)
1085 condition_dump(c, f, prefix, to_string);
1086 }
1087
1088 static const char* const condition_type_table[_CONDITION_TYPE_MAX] = {
1089 [CONDITION_ARCHITECTURE] = "ConditionArchitecture",
1090 [CONDITION_FIRMWARE] = "ConditionFirmware",
1091 [CONDITION_VIRTUALIZATION] = "ConditionVirtualization",
1092 [CONDITION_HOST] = "ConditionHost",
1093 [CONDITION_KERNEL_COMMAND_LINE] = "ConditionKernelCommandLine",
1094 [CONDITION_KERNEL_VERSION] = "ConditionKernelVersion",
1095 [CONDITION_SECURITY] = "ConditionSecurity",
1096 [CONDITION_CAPABILITY] = "ConditionCapability",
1097 [CONDITION_AC_POWER] = "ConditionACPower",
1098 [CONDITION_NEEDS_UPDATE] = "ConditionNeedsUpdate",
1099 [CONDITION_FIRST_BOOT] = "ConditionFirstBoot",
1100 [CONDITION_PATH_EXISTS] = "ConditionPathExists",
1101 [CONDITION_PATH_EXISTS_GLOB] = "ConditionPathExistsGlob",
1102 [CONDITION_PATH_IS_DIRECTORY] = "ConditionPathIsDirectory",
1103 [CONDITION_PATH_IS_SYMBOLIC_LINK] = "ConditionPathIsSymbolicLink",
1104 [CONDITION_PATH_IS_MOUNT_POINT] = "ConditionPathIsMountPoint",
1105 [CONDITION_PATH_IS_READ_WRITE] = "ConditionPathIsReadWrite",
1106 [CONDITION_PATH_IS_ENCRYPTED] = "ConditionPathIsEncrypted",
1107 [CONDITION_DIRECTORY_NOT_EMPTY] = "ConditionDirectoryNotEmpty",
1108 [CONDITION_FILE_NOT_EMPTY] = "ConditionFileNotEmpty",
1109 [CONDITION_FILE_IS_EXECUTABLE] = "ConditionFileIsExecutable",
1110 [CONDITION_USER] = "ConditionUser",
1111 [CONDITION_GROUP] = "ConditionGroup",
1112 [CONDITION_CONTROL_GROUP_CONTROLLER] = "ConditionControlGroupController",
1113 [CONDITION_CPUS] = "ConditionCPUs",
1114 [CONDITION_MEMORY] = "ConditionMemory",
1115 [CONDITION_ENVIRONMENT] = "ConditionEnvironment",
1116 [CONDITION_CPU_FEATURE] = "ConditionCPUFeature",
1117 [CONDITION_OS_RELEASE] = "ConditionOSRelease",
1118 };
1119
1120 DEFINE_STRING_TABLE_LOOKUP(condition_type, ConditionType);
1121
1122 static const char* const assert_type_table[_CONDITION_TYPE_MAX] = {
1123 [CONDITION_ARCHITECTURE] = "AssertArchitecture",
1124 [CONDITION_FIRMWARE] = "AssertFirmware",
1125 [CONDITION_VIRTUALIZATION] = "AssertVirtualization",
1126 [CONDITION_HOST] = "AssertHost",
1127 [CONDITION_KERNEL_COMMAND_LINE] = "AssertKernelCommandLine",
1128 [CONDITION_KERNEL_VERSION] = "AssertKernelVersion",
1129 [CONDITION_SECURITY] = "AssertSecurity",
1130 [CONDITION_CAPABILITY] = "AssertCapability",
1131 [CONDITION_AC_POWER] = "AssertACPower",
1132 [CONDITION_NEEDS_UPDATE] = "AssertNeedsUpdate",
1133 [CONDITION_FIRST_BOOT] = "AssertFirstBoot",
1134 [CONDITION_PATH_EXISTS] = "AssertPathExists",
1135 [CONDITION_PATH_EXISTS_GLOB] = "AssertPathExistsGlob",
1136 [CONDITION_PATH_IS_DIRECTORY] = "AssertPathIsDirectory",
1137 [CONDITION_PATH_IS_SYMBOLIC_LINK] = "AssertPathIsSymbolicLink",
1138 [CONDITION_PATH_IS_MOUNT_POINT] = "AssertPathIsMountPoint",
1139 [CONDITION_PATH_IS_READ_WRITE] = "AssertPathIsReadWrite",
1140 [CONDITION_PATH_IS_ENCRYPTED] = "AssertPathIsEncrypted",
1141 [CONDITION_DIRECTORY_NOT_EMPTY] = "AssertDirectoryNotEmpty",
1142 [CONDITION_FILE_NOT_EMPTY] = "AssertFileNotEmpty",
1143 [CONDITION_FILE_IS_EXECUTABLE] = "AssertFileIsExecutable",
1144 [CONDITION_USER] = "AssertUser",
1145 [CONDITION_GROUP] = "AssertGroup",
1146 [CONDITION_CONTROL_GROUP_CONTROLLER] = "AssertControlGroupController",
1147 [CONDITION_CPUS] = "AssertCPUs",
1148 [CONDITION_MEMORY] = "AssertMemory",
1149 [CONDITION_ENVIRONMENT] = "AssertEnvironment",
1150 [CONDITION_CPU_FEATURE] = "AssertCPUFeature",
1151 [CONDITION_OS_RELEASE] = "AssertOSRelease",
1152 };
1153
1154 DEFINE_STRING_TABLE_LOOKUP(assert_type, ConditionType);
1155
1156 static const char* const condition_result_table[_CONDITION_RESULT_MAX] = {
1157 [CONDITION_UNTESTED] = "untested",
1158 [CONDITION_SUCCEEDED] = "succeeded",
1159 [CONDITION_FAILED] = "failed",
1160 [CONDITION_ERROR] = "error",
1161 };
1162
1163 DEFINE_STRING_TABLE_LOOKUP(condition_result, ConditionResult);