1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
10 #include <sys/utsname.h>
16 #include "alloc-util.h"
17 #include "apparmor-util.h"
18 #include "architecture.h"
19 #include "audit-util.h"
20 #include "blockdev-util.h"
22 #include "cgroup-util.h"
23 #include "condition.h"
24 #include "cpu-set-util.h"
25 #include "efi-loader.h"
28 #include "extract-word.h"
32 #include "glob-util.h"
33 #include "hostname-util.h"
35 #include "limits-util.h"
38 #include "mountpoint-util.h"
40 #include "parse-util.h"
41 #include "path-util.h"
42 #include "percent-util.h"
43 #include "proc-cmdline.h"
44 #include "process-util.h"
46 #include "selinux-util.h"
47 #include "smack-util.h"
49 #include "stat-util.h"
50 #include "string-table.h"
51 #include "string-util.h"
52 #include "tomoyo-util.h"
53 #include "udev-util.h"
54 #include "uid-alloc-range.h"
55 #include "user-util.h"
58 Condition
* condition_new(ConditionType type
, const char *parameter
, bool trigger
, bool negate
) {
62 assert(type
< _CONDITION_TYPE_MAX
);
65 c
= new(Condition
, 1);
76 c
->parameter
= strdup(parameter
);
84 Condition
* condition_free(Condition
*c
) {
91 Condition
* condition_free_list_type(Condition
*head
, ConditionType type
) {
92 LIST_FOREACH(conditions
, c
, head
)
93 if (type
< 0 || c
->type
== type
) {
94 LIST_REMOVE(conditions
, head
, c
);
98 assert(type
>= 0 || !head
);
102 static int condition_test_kernel_command_line(Condition
*c
, char **env
) {
103 _cleanup_free_
char *line
= NULL
;
109 assert(c
->parameter
);
110 assert(c
->type
== CONDITION_KERNEL_COMMAND_LINE
);
112 r
= proc_cmdline(&line
);
116 equal
= strchr(c
->parameter
, '=');
119 _cleanup_free_
char *word
= NULL
;
122 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_UNQUOTE
|EXTRACT_RELAX
);
129 found
= streq(word
, c
->parameter
);
133 f
= startswith(word
, c
->parameter
);
134 found
= f
&& IN_SET(*f
, 0, '=');
145 /* Listed in order of checking. Note that some comparators are prefixes of others, hence the longest
146 * should be listed first. */
147 ORDER_LOWER_OR_EQUAL
,
148 ORDER_GREATER_OR_EQUAL
,
154 _ORDER_INVALID
= -EINVAL
,
157 static OrderOperator
parse_order(const char **s
) {
159 static const char *const prefix
[_ORDER_MAX
] = {
160 [ORDER_LOWER_OR_EQUAL
] = "<=",
161 [ORDER_GREATER_OR_EQUAL
] = ">=",
163 [ORDER_GREATER
] = ">",
165 [ORDER_UNEQUAL
] = "!=",
170 for (i
= 0; i
< _ORDER_MAX
; i
++) {
173 e
= startswith(*s
, prefix
[i
]);
180 return _ORDER_INVALID
;
183 static bool test_order(int k
, OrderOperator p
) {
190 case ORDER_LOWER_OR_EQUAL
:
199 case ORDER_GREATER_OR_EQUAL
:
206 assert_not_reached();
211 static int condition_test_kernel_version(Condition
*c
, char **env
) {
218 assert(c
->parameter
);
219 assert(c
->type
== CONDITION_KERNEL_VERSION
);
221 assert_se(uname(&u
) >= 0);
226 _cleanup_free_
char *word
= NULL
;
230 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_UNQUOTE
);
232 return log_debug_errno(r
, "Failed to parse condition string \"%s\": %m", p
);
237 order
= parse_order(&s
);
239 s
+= strspn(s
, WHITESPACE
);
242 /* For backwards compatibility, allow whitespace between the operator and
243 * value, without quoting, but only in the first expression. */
245 r
= extract_first_word(&p
, &word
, NULL
, 0);
247 return log_debug_errno(r
, "Failed to parse condition string \"%s\": %m", p
);
249 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected end of expression: %s", p
);
252 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected end of expression: %s", p
);
255 r
= test_order(strverscmp_improved(u
.release
, s
), order
);
257 /* No prefix? Then treat as glob string */
258 r
= fnmatch(s
, u
.release
, 0) == 0;
269 static int condition_test_osrelease(Condition
*c
, char **env
) {
270 const char *parameter
= c
->parameter
;
274 assert(c
->parameter
);
275 assert(c
->type
== CONDITION_OS_RELEASE
);
278 _cleanup_free_
char *key
= NULL
, *condition
= NULL
, *actual_value
= NULL
;
283 r
= extract_first_word(¶meter
, &condition
, NULL
, EXTRACT_UNQUOTE
);
285 return log_debug_errno(r
, "Failed to parse parameter: %m");
289 /* parse_order() needs the string to start with the comparators */
291 r
= extract_first_word(&word
, &key
, "!<=>", EXTRACT_RETAIN_SEPARATORS
);
293 return log_debug_errno(r
, "Failed to parse parameter: %m");
294 /* The os-release spec mandates env-var-like key names */
295 if (r
== 0 || isempty(word
) || !env_name_is_valid(key
))
296 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
297 "Failed to parse parameter, key/value format expected: %m");
299 /* Do not allow whitespace after the separator, as that's not a valid os-release format */
300 order
= parse_order(&word
);
301 if (order
< 0 || isempty(word
) || strchr(WHITESPACE
, *word
) != NULL
)
302 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
303 "Failed to parse parameter, key/value format expected: %m");
305 r
= parse_os_release(NULL
, key
, &actual_value
);
307 return log_debug_errno(r
, "Failed to parse os-release: %m");
309 /* Might not be comparing versions, so do exact string matching */
310 if (order
== ORDER_EQUAL
)
311 matches
= streq_ptr(actual_value
, word
);
312 else if (order
== ORDER_UNEQUAL
)
313 matches
= !streq_ptr(actual_value
, word
);
315 matches
= test_order(strverscmp_improved(actual_value
, word
), order
);
324 static int condition_test_memory(Condition
*c
, char **env
) {
331 assert(c
->parameter
);
332 assert(c
->type
== CONDITION_MEMORY
);
334 m
= physical_memory();
337 order
= parse_order(&p
);
339 order
= ORDER_GREATER_OR_EQUAL
; /* default to >= check, if nothing is specified. */
341 r
= safe_atou64(p
, &k
);
343 return log_debug_errno(r
, "Failed to parse size: %m");
345 return test_order(CMP(m
, k
), order
);
348 static int condition_test_cpus(Condition
*c
, char **env
) {
355 assert(c
->parameter
);
356 assert(c
->type
== CONDITION_CPUS
);
358 n
= cpus_in_affinity_mask();
360 return log_debug_errno(n
, "Failed to determine CPUs in affinity mask: %m");
363 order
= parse_order(&p
);
365 order
= ORDER_GREATER_OR_EQUAL
; /* default to >= check, if nothing is specified. */
367 r
= safe_atou(p
, &k
);
369 return log_debug_errno(r
, "Failed to parse number of CPUs: %m");
371 return test_order(CMP((unsigned) n
, k
), order
);
374 static int condition_test_user(Condition
*c
, char **env
) {
377 _cleanup_free_
char *username
= NULL
;
381 assert(c
->parameter
);
382 assert(c
->type
== CONDITION_USER
);
384 r
= parse_uid(c
->parameter
, &id
);
386 return id
== getuid() || id
== geteuid();
388 if (streq("@system", c
->parameter
))
389 return uid_is_system(getuid()) || uid_is_system(geteuid());
391 username
= getusername_malloc();
395 if (streq(username
, c
->parameter
))
398 if (getpid_cached() == 1)
399 return streq(c
->parameter
, "root");
402 r
= get_user_creds(&u
, &id
, NULL
, NULL
, NULL
, USER_CREDS_ALLOW_MISSING
);
406 return id
== getuid() || id
== geteuid();
409 static int condition_test_control_group_controller(Condition
*c
, char **env
) {
411 CGroupMask system_mask
, wanted_mask
= 0;
414 assert(c
->parameter
);
415 assert(c
->type
== CONDITION_CONTROL_GROUP_CONTROLLER
);
417 if (streq(c
->parameter
, "v2"))
418 return cg_all_unified();
419 if (streq(c
->parameter
, "v1")) {
420 r
= cg_all_unified();
426 r
= cg_mask_supported(&system_mask
);
428 return log_debug_errno(r
, "Failed to determine supported controllers: %m");
430 r
= cg_mask_from_string(c
->parameter
, &wanted_mask
);
431 if (r
< 0 || wanted_mask
<= 0) {
432 /* This won't catch the case that we have an unknown controller
433 * mixed in with valid ones -- these are only assessed on the
434 * validity of the valid controllers found. */
435 log_debug("Failed to parse cgroup string: %s", c
->parameter
);
439 return FLAGS_SET(system_mask
, wanted_mask
);
442 static int condition_test_group(Condition
*c
, char **env
) {
447 assert(c
->parameter
);
448 assert(c
->type
== CONDITION_GROUP
);
450 r
= parse_gid(c
->parameter
, &id
);
454 /* Avoid any NSS lookups if we are PID1 */
455 if (getpid_cached() == 1)
456 return streq(c
->parameter
, "root");
458 return in_group(c
->parameter
) > 0;
461 static int condition_test_virtualization(Condition
*c
, char **env
) {
465 assert(c
->parameter
);
466 assert(c
->type
== CONDITION_VIRTUALIZATION
);
468 if (streq(c
->parameter
, "private-users"))
469 return running_in_userns();
471 v
= detect_virtualization();
475 /* First, compare with yes/no */
476 b
= parse_boolean(c
->parameter
);
480 /* Then, compare categorization */
481 if (streq(c
->parameter
, "vm"))
482 return VIRTUALIZATION_IS_VM(v
);
484 if (streq(c
->parameter
, "container"))
485 return VIRTUALIZATION_IS_CONTAINER(v
);
487 /* Finally compare id */
488 return v
!= VIRTUALIZATION_NONE
&& streq(c
->parameter
, virtualization_to_string(v
));
491 static int condition_test_architecture(Condition
*c
, char **env
) {
495 assert(c
->parameter
);
496 assert(c
->type
== CONDITION_ARCHITECTURE
);
498 a
= uname_architecture();
502 if (streq(c
->parameter
, "native"))
503 b
= native_architecture();
505 b
= architecture_from_string(c
->parameter
);
506 if (b
< 0) /* unknown architecture? Then it's definitely not ours */
513 #define DTCOMPAT_FILE "/proc/device-tree/compatible"
514 static int condition_test_firmware_devicetree_compatible(const char *dtcarg
) {
516 _cleanup_free_
char *dtcompat
= NULL
;
517 _cleanup_strv_free_
char **dtcompatlist
= NULL
;
520 r
= read_full_virtual_file(DTCOMPAT_FILE
, &dtcompat
, &size
);
522 /* if the path doesn't exist it is incompatible */
524 log_debug_errno(r
, "Failed to open() '%s', assuming machine is incompatible: %m", DTCOMPAT_FILE
);
528 /* Not sure this can happen, but play safe. */
530 log_debug("%s has zero length, assuming machine is incompatible", DTCOMPAT_FILE
);
534 /* /proc/device-tree/compatible consists of one or more strings, each ending in '\0'.
535 * So the last character in dtcompat must be a '\0'. */
536 if (dtcompat
[size
- 1] != '\0') {
537 log_debug("%s is in an unknown format, assuming machine is incompatible", DTCOMPAT_FILE
);
541 dtcompatlist
= strv_parse_nulstr(dtcompat
, size
);
545 return strv_contains(dtcompatlist
, dtcarg
);
548 static int condition_test_firmware(Condition
*c
, char **env
) {
552 assert(c
->parameter
);
553 assert(c
->type
== CONDITION_FIRMWARE
);
555 if (streq(c
->parameter
, "device-tree")) {
556 if (access("/sys/firmware/device-tree/", F_OK
) < 0) {
558 log_debug_errno(errno
, "Unexpected error when checking for /sys/firmware/device-tree/: %m");
562 } else if ((dtc
= startswith(c
->parameter
, "device-tree-compatible("))) {
563 _cleanup_free_
char *dtcarg
= NULL
;
566 end
= strchr(dtc
, ')');
567 if (!end
|| *(end
+ 1) != '\0') {
568 log_debug("Malformed Firmware condition \"%s\"", c
->parameter
);
572 dtcarg
= strndup(dtc
, end
- dtc
);
576 return condition_test_firmware_devicetree_compatible(dtcarg
);
577 } else if (streq(c
->parameter
, "uefi"))
578 return is_efi_boot();
580 log_debug("Unsupported Firmware condition \"%s\"", c
->parameter
);
585 static int condition_test_host(Condition
*c
, char **env
) {
586 _cleanup_free_
char *h
= NULL
;
591 assert(c
->parameter
);
592 assert(c
->type
== CONDITION_HOST
);
594 if (sd_id128_from_string(c
->parameter
, &x
) >= 0) {
596 r
= sd_id128_get_machine(&y
);
600 return sd_id128_equal(x
, y
);
603 h
= gethostname_malloc();
607 return fnmatch(c
->parameter
, h
, FNM_CASEFOLD
) == 0;
610 static int condition_test_ac_power(Condition
*c
, char **env
) {
614 assert(c
->parameter
);
615 assert(c
->type
== CONDITION_AC_POWER
);
617 r
= parse_boolean(c
->parameter
);
621 return (on_ac_power() != 0) == !!r
;
624 static int has_tpm2(void) {
627 /* Checks whether the system has at least one TPM2 resource manager device, i.e. at least one "tpmrm"
630 r
= dir_is_empty("/sys/class/tpmrm");
632 return true; /* nice! we have a device */
634 /* Hmm, so Linux doesn't know of the TPM2 device (or we couldn't check for it), most likely because
635 * the driver wasn't loaded yet. Let's see if the firmware knows about a TPM2 device, in this
636 * case. This way we can answer the TPM2 question already during early boot (where we most likely
641 /* OK, this didn't work either, in this case propagate the original errors */
645 return log_debug_errno(r
, "Failed to determine whether system has TPM2 support: %m");
650 static int condition_test_security(Condition
*c
, char **env
) {
652 assert(c
->parameter
);
653 assert(c
->type
== CONDITION_SECURITY
);
655 if (streq(c
->parameter
, "selinux"))
656 return mac_selinux_use();
657 if (streq(c
->parameter
, "smack"))
658 return mac_smack_use();
659 if (streq(c
->parameter
, "apparmor"))
660 return mac_apparmor_use();
661 if (streq(c
->parameter
, "audit"))
663 if (streq(c
->parameter
, "ima"))
665 if (streq(c
->parameter
, "tomoyo"))
666 return mac_tomoyo_use();
667 if (streq(c
->parameter
, "uefi-secureboot"))
668 return is_efi_secure_boot();
669 if (streq(c
->parameter
, "tpm2"))
675 static int condition_test_capability(Condition
*c
, char **env
) {
676 unsigned long long capabilities
= (unsigned long long) -1;
677 _cleanup_fclose_
FILE *f
= NULL
;
681 assert(c
->parameter
);
682 assert(c
->type
== CONDITION_CAPABILITY
);
684 /* If it's an invalid capability, we don't have it */
685 value
= capability_from_name(c
->parameter
);
689 /* If it's a valid capability we default to assume
692 f
= fopen("/proc/self/status", "re");
697 _cleanup_free_
char *line
= NULL
;
700 r
= read_line(f
, LONG_LINE_MAX
, &line
);
706 p
= startswith(line
, "CapBnd:");
708 if (sscanf(line
+7, "%llx", &capabilities
) != 1)
715 return !!(capabilities
& (1ULL << value
));
718 static int condition_test_needs_update(Condition
*c
, char **env
) {
719 struct stat usr
, other
;
725 assert(c
->parameter
);
726 assert(c
->type
== CONDITION_NEEDS_UPDATE
);
728 r
= proc_cmdline_get_bool("systemd.condition-needs-update", &b
);
730 log_debug_errno(r
, "Failed to parse systemd.condition-needs-update= kernel command line argument, ignoring: %m");
735 log_debug("We are in an initrd, not doing any updates.");
739 if (!path_is_absolute(c
->parameter
)) {
740 log_debug("Specified condition parameter '%s' is not absolute, assuming an update is needed.", c
->parameter
);
744 /* If the file system is read-only we shouldn't suggest an update */
745 r
= path_is_read_only_fs(c
->parameter
);
747 log_debug_errno(r
, "Failed to determine if '%s' is read-only, ignoring: %m", c
->parameter
);
751 /* Any other failure means we should allow the condition to be true, so that we rather invoke too
752 * many update tools than too few. */
754 p
= strjoina(c
->parameter
, "/.updated");
755 if (lstat(p
, &other
) < 0) {
757 log_debug_errno(errno
, "Failed to stat() '%s', assuming an update is needed: %m", p
);
761 if (lstat("/usr/", &usr
) < 0) {
762 log_debug_errno(errno
, "Failed to stat() /usr/, assuming an update is needed: %m");
767 * First, compare seconds as they are always accurate...
769 if (usr
.st_mtim
.tv_sec
!= other
.st_mtim
.tv_sec
)
770 return usr
.st_mtim
.tv_sec
> other
.st_mtim
.tv_sec
;
773 * ...then compare nanoseconds.
775 * A false positive is only possible when /usr's nanoseconds > 0
776 * (otherwise /usr cannot be strictly newer than the target file)
777 * AND the target file's nanoseconds == 0
778 * (otherwise the filesystem supports nsec timestamps, see stat(2)).
780 if (usr
.st_mtim
.tv_nsec
== 0 || other
.st_mtim
.tv_nsec
> 0)
781 return usr
.st_mtim
.tv_nsec
> other
.st_mtim
.tv_nsec
;
783 _cleanup_free_
char *timestamp_str
= NULL
;
784 r
= parse_env_file(NULL
, p
, "TIMESTAMP_NSEC", ×tamp_str
);
786 log_debug_errno(r
, "Failed to parse timestamp file '%s', using mtime: %m", p
);
789 log_debug("No data in timestamp file '%s', using mtime.", p
);
794 r
= safe_atou64(timestamp_str
, ×tamp
);
796 log_debug_errno(r
, "Failed to parse timestamp value '%s' in file '%s', using mtime: %m", timestamp_str
, p
);
800 return timespec_load_nsec(&usr
.st_mtim
) > timestamp
;
803 static int condition_test_first_boot(Condition
*c
, char **env
) {
808 assert(c
->parameter
);
809 assert(c
->type
== CONDITION_FIRST_BOOT
);
811 r
= proc_cmdline_get_bool("systemd.condition-first-boot", &b
);
813 log_debug_errno(r
, "Failed to parse systemd.condition-first-boot= kernel command line argument, ignoring: %m");
817 r
= parse_boolean(c
->parameter
);
821 q
= access("/run/systemd/first-boot", F_OK
);
822 if (q
< 0 && errno
!= ENOENT
)
823 log_debug_errno(errno
, "Failed to check if /run/systemd/first-boot exists, ignoring: %m");
825 return (q
>= 0) == !!r
;
828 static int condition_test_environment(Condition
*c
, char **env
) {
832 assert(c
->parameter
);
833 assert(c
->type
== CONDITION_ENVIRONMENT
);
835 equal
= strchr(c
->parameter
, '=');
837 STRV_FOREACH(i
, env
) {
841 found
= streq(c
->parameter
, *i
);
845 f
= startswith(*i
, c
->parameter
);
846 found
= f
&& IN_SET(*f
, 0, '=');
856 static int condition_test_path_exists(Condition
*c
, char **env
) {
858 assert(c
->parameter
);
859 assert(c
->type
== CONDITION_PATH_EXISTS
);
861 return access(c
->parameter
, F_OK
) >= 0;
864 static int condition_test_path_exists_glob(Condition
*c
, char **env
) {
866 assert(c
->parameter
);
867 assert(c
->type
== CONDITION_PATH_EXISTS_GLOB
);
869 return glob_exists(c
->parameter
) > 0;
872 static int condition_test_path_is_directory(Condition
*c
, char **env
) {
874 assert(c
->parameter
);
875 assert(c
->type
== CONDITION_PATH_IS_DIRECTORY
);
877 return is_dir(c
->parameter
, true) > 0;
880 static int condition_test_path_is_symbolic_link(Condition
*c
, char **env
) {
882 assert(c
->parameter
);
883 assert(c
->type
== CONDITION_PATH_IS_SYMBOLIC_LINK
);
885 return is_symlink(c
->parameter
) > 0;
888 static int condition_test_path_is_mount_point(Condition
*c
, char **env
) {
890 assert(c
->parameter
);
891 assert(c
->type
== CONDITION_PATH_IS_MOUNT_POINT
);
893 return path_is_mount_point(c
->parameter
, NULL
, AT_SYMLINK_FOLLOW
) > 0;
896 static int condition_test_path_is_read_write(Condition
*c
, char **env
) {
900 assert(c
->parameter
);
901 assert(c
->type
== CONDITION_PATH_IS_READ_WRITE
);
903 r
= path_is_read_only_fs(c
->parameter
);
905 return r
<= 0 && r
!= -ENOENT
;
908 static int condition_test_cpufeature(Condition
*c
, char **env
) {
910 assert(c
->parameter
);
911 assert(c
->type
== CONDITION_CPU_FEATURE
);
913 return has_cpu_with_flag(ascii_strlower(c
->parameter
));
916 static int condition_test_path_is_encrypted(Condition
*c
, char **env
) {
920 assert(c
->parameter
);
921 assert(c
->type
== CONDITION_PATH_IS_ENCRYPTED
);
923 r
= path_is_encrypted(c
->parameter
);
924 if (r
< 0 && r
!= -ENOENT
)
925 log_debug_errno(r
, "Failed to determine if '%s' is encrypted: %m", c
->parameter
);
930 static int condition_test_directory_not_empty(Condition
*c
, char **env
) {
934 assert(c
->parameter
);
935 assert(c
->type
== CONDITION_DIRECTORY_NOT_EMPTY
);
937 r
= dir_is_empty(c
->parameter
);
938 return r
<= 0 && !IN_SET(r
, -ENOENT
, -ENOTDIR
);
941 static int condition_test_file_not_empty(Condition
*c
, char **env
) {
945 assert(c
->parameter
);
946 assert(c
->type
== CONDITION_FILE_NOT_EMPTY
);
948 return (stat(c
->parameter
, &st
) >= 0 &&
949 S_ISREG(st
.st_mode
) &&
953 static int condition_test_file_is_executable(Condition
*c
, char **env
) {
957 assert(c
->parameter
);
958 assert(c
->type
== CONDITION_FILE_IS_EXECUTABLE
);
960 return (stat(c
->parameter
, &st
) >= 0 &&
961 S_ISREG(st
.st_mode
) &&
962 (st
.st_mode
& 0111));
965 static int condition_test_psi(Condition
*c
, char **env
) {
966 _cleanup_free_
char *first
= NULL
, *second
= NULL
, *third
= NULL
, *fourth
= NULL
, *pressure_path
= NULL
;
967 const char *p
, *value
, *pressure_type
;
968 loadavg_t
*current
, limit
;
969 ResourcePressure pressure
;
973 assert(c
->parameter
);
974 assert(IN_SET(c
->type
, CONDITION_MEMORY_PRESSURE
, CONDITION_CPU_PRESSURE
, CONDITION_IO_PRESSURE
));
976 if (!is_pressure_supported()) {
977 log_debug("Pressure Stall Information (PSI) is not supported, skipping.");
981 pressure_type
= c
->type
== CONDITION_MEMORY_PRESSURE
? "memory" :
982 c
->type
== CONDITION_CPU_PRESSURE
? "cpu" :
986 r
= extract_many_words(&p
, ":", 0, &first
, &second
, NULL
);
988 return log_debug_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
989 /* If only one parameter is passed, then we look at the global system pressure rather than a specific cgroup. */
991 pressure_path
= path_join("/proc/pressure", pressure_type
);
993 return log_oom_debug();
997 const char *controller
= strjoina(pressure_type
, ".pressure");
998 _cleanup_free_
char *slice_path
= NULL
, *root_scope
= NULL
;
999 CGroupMask mask
, required_mask
;
1002 required_mask
= c
->type
== CONDITION_MEMORY_PRESSURE
? CGROUP_MASK_MEMORY
:
1003 c
->type
== CONDITION_CPU_PRESSURE
? CGROUP_MASK_CPU
:
1006 slice
= strstrip(first
);
1008 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1010 r
= cg_all_unified();
1012 return log_debug_errno(r
, "Failed to determine whether the unified cgroups hierarchy is used: %m");
1014 log_debug("PSI condition check requires the unified cgroups hierarchy, skipping.");
1018 r
= cg_mask_supported(&mask
);
1020 return log_debug_errno(r
, "Failed to get supported cgroup controllers: %m");
1022 if (!FLAGS_SET(mask
, required_mask
)) {
1023 log_debug("Cgroup %s controller not available, skipping PSI condition check.", pressure_type
);
1027 r
= cg_slice_to_path(slice
, &slice_path
);
1029 return log_debug_errno(r
, "Cannot determine slice \"%s\" cgroup path: %m", slice
);
1031 /* We might be running under the user manager, so get the root path and prefix it accordingly. */
1032 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, getpid_cached(), &root_scope
);
1034 return log_debug_errno(r
, "Failed to get root cgroup path: %m");
1036 /* Drop init.scope, we want the parent. We could get an empty or / path, but that's fine,
1037 * just skip it in that case. */
1038 e
= endswith(root_scope
, "/" SPECIAL_INIT_SCOPE
);
1041 if (!empty_or_root(root_scope
)) {
1042 _cleanup_free_
char *slice_joined
= NULL
;
1044 slice_joined
= path_join(root_scope
, slice_path
);
1046 return log_oom_debug();
1048 free_and_replace(slice_path
, slice_joined
);
1051 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, slice_path
, controller
, &pressure_path
);
1053 return log_debug_errno(r
, "Error getting cgroup pressure path from %s: %m", slice_path
);
1058 /* If a value including a specific timespan (in the intervals allowed by the kernel),
1059 * parse it, otherwise we assume just a plain percentage that will be checked if it is
1060 * smaller or equal to the current pressure average over 5 minutes. */
1061 r
= extract_many_words(&value
, "/", 0, &third
, &fourth
, NULL
);
1063 return log_debug_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1065 current
= &pressure
.avg300
;
1067 const char *timespan
;
1069 timespan
= skip_leading_chars(fourth
, NULL
);
1071 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1073 if (startswith(timespan
, "10sec"))
1074 current
= &pressure
.avg10
;
1075 else if (startswith(timespan
, "1min"))
1076 current
= &pressure
.avg60
;
1077 else if (startswith(timespan
, "5min"))
1078 current
= &pressure
.avg300
;
1080 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1083 value
= strstrip(third
);
1085 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1087 r
= parse_permyriad(value
);
1089 return log_debug_errno(r
, "Failed to parse permyriad: %s", c
->parameter
);
1091 r
= store_loadavg_fixed_point(r
/ 100LU, r
% 100LU, &limit
);
1093 return log_debug_errno(r
, "Failed to parse loadavg: %s", c
->parameter
);
1095 r
= read_resource_pressure(pressure_path
, PRESSURE_TYPE_FULL
, &pressure
);
1096 if (r
== -ENODATA
) /* cpu.pressure 'full' was added recently, fall back to 'some'. */
1097 r
= read_resource_pressure(pressure_path
, PRESSURE_TYPE_SOME
, &pressure
);
1099 /* We already checked that /proc/pressure exists, so this means we were given a cgroup
1100 * that doesn't exist or doesn't exist any longer. */
1101 log_debug("\"%s\" not found, skipping PSI check.", pressure_path
);
1105 return log_debug_errno(r
, "Error parsing pressure from %s: %m", pressure_path
);
1107 return *current
<= limit
;
1110 int condition_test(Condition
*c
, char **env
) {
1112 static int (*const condition_tests
[_CONDITION_TYPE_MAX
])(Condition
*c
, char **env
) = {
1113 [CONDITION_PATH_EXISTS
] = condition_test_path_exists
,
1114 [CONDITION_PATH_EXISTS_GLOB
] = condition_test_path_exists_glob
,
1115 [CONDITION_PATH_IS_DIRECTORY
] = condition_test_path_is_directory
,
1116 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = condition_test_path_is_symbolic_link
,
1117 [CONDITION_PATH_IS_MOUNT_POINT
] = condition_test_path_is_mount_point
,
1118 [CONDITION_PATH_IS_READ_WRITE
] = condition_test_path_is_read_write
,
1119 [CONDITION_PATH_IS_ENCRYPTED
] = condition_test_path_is_encrypted
,
1120 [CONDITION_DIRECTORY_NOT_EMPTY
] = condition_test_directory_not_empty
,
1121 [CONDITION_FILE_NOT_EMPTY
] = condition_test_file_not_empty
,
1122 [CONDITION_FILE_IS_EXECUTABLE
] = condition_test_file_is_executable
,
1123 [CONDITION_KERNEL_COMMAND_LINE
] = condition_test_kernel_command_line
,
1124 [CONDITION_KERNEL_VERSION
] = condition_test_kernel_version
,
1125 [CONDITION_VIRTUALIZATION
] = condition_test_virtualization
,
1126 [CONDITION_SECURITY
] = condition_test_security
,
1127 [CONDITION_CAPABILITY
] = condition_test_capability
,
1128 [CONDITION_HOST
] = condition_test_host
,
1129 [CONDITION_AC_POWER
] = condition_test_ac_power
,
1130 [CONDITION_ARCHITECTURE
] = condition_test_architecture
,
1131 [CONDITION_FIRMWARE
] = condition_test_firmware
,
1132 [CONDITION_NEEDS_UPDATE
] = condition_test_needs_update
,
1133 [CONDITION_FIRST_BOOT
] = condition_test_first_boot
,
1134 [CONDITION_USER
] = condition_test_user
,
1135 [CONDITION_GROUP
] = condition_test_group
,
1136 [CONDITION_CONTROL_GROUP_CONTROLLER
] = condition_test_control_group_controller
,
1137 [CONDITION_CPUS
] = condition_test_cpus
,
1138 [CONDITION_MEMORY
] = condition_test_memory
,
1139 [CONDITION_ENVIRONMENT
] = condition_test_environment
,
1140 [CONDITION_CPU_FEATURE
] = condition_test_cpufeature
,
1141 [CONDITION_OS_RELEASE
] = condition_test_osrelease
,
1142 [CONDITION_MEMORY_PRESSURE
] = condition_test_psi
,
1143 [CONDITION_CPU_PRESSURE
] = condition_test_psi
,
1144 [CONDITION_IO_PRESSURE
] = condition_test_psi
,
1150 assert(c
->type
>= 0);
1151 assert(c
->type
< _CONDITION_TYPE_MAX
);
1153 r
= condition_tests
[c
->type
](c
, env
);
1155 c
->result
= CONDITION_ERROR
;
1159 b
= (r
> 0) == !c
->negate
;
1160 c
->result
= b
? CONDITION_SUCCEEDED
: CONDITION_FAILED
;
1164 bool condition_test_list(
1167 condition_to_string_t to_string
,
1168 condition_test_logger_t logger
,
1173 assert(!!logger
== !!to_string
);
1175 /* If the condition list is empty, then it is true */
1179 /* Otherwise, if all of the non-trigger conditions apply and
1180 * if any of the trigger conditions apply (unless there are
1181 * none) we return true */
1182 LIST_FOREACH(conditions
, c
, first
) {
1185 r
= condition_test(c
, env
);
1189 logger(userdata
, LOG_WARNING
, r
, PROJECT_FILE
, __LINE__
, __func__
,
1190 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
1192 c
->trigger
? "|" : "",
1193 c
->negate
? "!" : "",
1196 logger(userdata
, LOG_DEBUG
, 0, PROJECT_FILE
, __LINE__
, __func__
,
1199 c
->trigger
? "|" : "",
1200 c
->negate
? "!" : "",
1202 condition_result_to_string(c
->result
));
1205 if (!c
->trigger
&& r
<= 0)
1208 if (c
->trigger
&& triggered
<= 0)
1212 return triggered
!= 0;
1215 void condition_dump(Condition
*c
, FILE *f
, const char *prefix
, condition_to_string_t to_string
) {
1220 prefix
= strempty(prefix
);
1223 "%s\t%s: %s%s%s %s\n",
1226 c
->trigger
? "|" : "",
1227 c
->negate
? "!" : "",
1229 condition_result_to_string(c
->result
));
1232 void condition_dump_list(Condition
*first
, FILE *f
, const char *prefix
, condition_to_string_t to_string
) {
1233 LIST_FOREACH(conditions
, c
, first
)
1234 condition_dump(c
, f
, prefix
, to_string
);
1237 static const char* const condition_type_table
[_CONDITION_TYPE_MAX
] = {
1238 [CONDITION_ARCHITECTURE
] = "ConditionArchitecture",
1239 [CONDITION_FIRMWARE
] = "ConditionFirmware",
1240 [CONDITION_VIRTUALIZATION
] = "ConditionVirtualization",
1241 [CONDITION_HOST
] = "ConditionHost",
1242 [CONDITION_KERNEL_COMMAND_LINE
] = "ConditionKernelCommandLine",
1243 [CONDITION_KERNEL_VERSION
] = "ConditionKernelVersion",
1244 [CONDITION_SECURITY
] = "ConditionSecurity",
1245 [CONDITION_CAPABILITY
] = "ConditionCapability",
1246 [CONDITION_AC_POWER
] = "ConditionACPower",
1247 [CONDITION_NEEDS_UPDATE
] = "ConditionNeedsUpdate",
1248 [CONDITION_FIRST_BOOT
] = "ConditionFirstBoot",
1249 [CONDITION_PATH_EXISTS
] = "ConditionPathExists",
1250 [CONDITION_PATH_EXISTS_GLOB
] = "ConditionPathExistsGlob",
1251 [CONDITION_PATH_IS_DIRECTORY
] = "ConditionPathIsDirectory",
1252 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = "ConditionPathIsSymbolicLink",
1253 [CONDITION_PATH_IS_MOUNT_POINT
] = "ConditionPathIsMountPoint",
1254 [CONDITION_PATH_IS_READ_WRITE
] = "ConditionPathIsReadWrite",
1255 [CONDITION_PATH_IS_ENCRYPTED
] = "ConditionPathIsEncrypted",
1256 [CONDITION_DIRECTORY_NOT_EMPTY
] = "ConditionDirectoryNotEmpty",
1257 [CONDITION_FILE_NOT_EMPTY
] = "ConditionFileNotEmpty",
1258 [CONDITION_FILE_IS_EXECUTABLE
] = "ConditionFileIsExecutable",
1259 [CONDITION_USER
] = "ConditionUser",
1260 [CONDITION_GROUP
] = "ConditionGroup",
1261 [CONDITION_CONTROL_GROUP_CONTROLLER
] = "ConditionControlGroupController",
1262 [CONDITION_CPUS
] = "ConditionCPUs",
1263 [CONDITION_MEMORY
] = "ConditionMemory",
1264 [CONDITION_ENVIRONMENT
] = "ConditionEnvironment",
1265 [CONDITION_CPU_FEATURE
] = "ConditionCPUFeature",
1266 [CONDITION_OS_RELEASE
] = "ConditionOSRelease",
1267 [CONDITION_MEMORY_PRESSURE
] = "ConditionMemoryPressure",
1268 [CONDITION_CPU_PRESSURE
] = "ConditionCPUPressure",
1269 [CONDITION_IO_PRESSURE
] = "ConditionIOPressure",
1272 DEFINE_STRING_TABLE_LOOKUP(condition_type
, ConditionType
);
1274 static const char* const assert_type_table
[_CONDITION_TYPE_MAX
] = {
1275 [CONDITION_ARCHITECTURE
] = "AssertArchitecture",
1276 [CONDITION_FIRMWARE
] = "AssertFirmware",
1277 [CONDITION_VIRTUALIZATION
] = "AssertVirtualization",
1278 [CONDITION_HOST
] = "AssertHost",
1279 [CONDITION_KERNEL_COMMAND_LINE
] = "AssertKernelCommandLine",
1280 [CONDITION_KERNEL_VERSION
] = "AssertKernelVersion",
1281 [CONDITION_SECURITY
] = "AssertSecurity",
1282 [CONDITION_CAPABILITY
] = "AssertCapability",
1283 [CONDITION_AC_POWER
] = "AssertACPower",
1284 [CONDITION_NEEDS_UPDATE
] = "AssertNeedsUpdate",
1285 [CONDITION_FIRST_BOOT
] = "AssertFirstBoot",
1286 [CONDITION_PATH_EXISTS
] = "AssertPathExists",
1287 [CONDITION_PATH_EXISTS_GLOB
] = "AssertPathExistsGlob",
1288 [CONDITION_PATH_IS_DIRECTORY
] = "AssertPathIsDirectory",
1289 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = "AssertPathIsSymbolicLink",
1290 [CONDITION_PATH_IS_MOUNT_POINT
] = "AssertPathIsMountPoint",
1291 [CONDITION_PATH_IS_READ_WRITE
] = "AssertPathIsReadWrite",
1292 [CONDITION_PATH_IS_ENCRYPTED
] = "AssertPathIsEncrypted",
1293 [CONDITION_DIRECTORY_NOT_EMPTY
] = "AssertDirectoryNotEmpty",
1294 [CONDITION_FILE_NOT_EMPTY
] = "AssertFileNotEmpty",
1295 [CONDITION_FILE_IS_EXECUTABLE
] = "AssertFileIsExecutable",
1296 [CONDITION_USER
] = "AssertUser",
1297 [CONDITION_GROUP
] = "AssertGroup",
1298 [CONDITION_CONTROL_GROUP_CONTROLLER
] = "AssertControlGroupController",
1299 [CONDITION_CPUS
] = "AssertCPUs",
1300 [CONDITION_MEMORY
] = "AssertMemory",
1301 [CONDITION_ENVIRONMENT
] = "AssertEnvironment",
1302 [CONDITION_CPU_FEATURE
] = "AssertCPUFeature",
1303 [CONDITION_OS_RELEASE
] = "AssertOSRelease",
1304 [CONDITION_MEMORY_PRESSURE
] = "AssertMemoryPressure",
1305 [CONDITION_CPU_PRESSURE
] = "AssertCPUPressure",
1306 [CONDITION_IO_PRESSURE
] = "AssertIOPressure",
1309 DEFINE_STRING_TABLE_LOOKUP(assert_type
, ConditionType
);
1311 static const char* const condition_result_table
[_CONDITION_RESULT_MAX
] = {
1312 [CONDITION_UNTESTED
] = "untested",
1313 [CONDITION_SUCCEEDED
] = "succeeded",
1314 [CONDITION_FAILED
] = "failed",
1315 [CONDITION_ERROR
] = "error",
1318 DEFINE_STRING_TABLE_LOOKUP(condition_result
, ConditionResult
);