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
) {
833 assert(c
->parameter
);
834 assert(c
->type
== CONDITION_ENVIRONMENT
);
836 equal
= strchr(c
->parameter
, '=');
838 STRV_FOREACH(i
, env
) {
842 found
= streq(c
->parameter
, *i
);
846 f
= startswith(*i
, c
->parameter
);
847 found
= f
&& IN_SET(*f
, 0, '=');
857 static int condition_test_path_exists(Condition
*c
, char **env
) {
859 assert(c
->parameter
);
860 assert(c
->type
== CONDITION_PATH_EXISTS
);
862 return access(c
->parameter
, F_OK
) >= 0;
865 static int condition_test_path_exists_glob(Condition
*c
, char **env
) {
867 assert(c
->parameter
);
868 assert(c
->type
== CONDITION_PATH_EXISTS_GLOB
);
870 return glob_exists(c
->parameter
) > 0;
873 static int condition_test_path_is_directory(Condition
*c
, char **env
) {
875 assert(c
->parameter
);
876 assert(c
->type
== CONDITION_PATH_IS_DIRECTORY
);
878 return is_dir(c
->parameter
, true) > 0;
881 static int condition_test_path_is_symbolic_link(Condition
*c
, char **env
) {
883 assert(c
->parameter
);
884 assert(c
->type
== CONDITION_PATH_IS_SYMBOLIC_LINK
);
886 return is_symlink(c
->parameter
) > 0;
889 static int condition_test_path_is_mount_point(Condition
*c
, char **env
) {
891 assert(c
->parameter
);
892 assert(c
->type
== CONDITION_PATH_IS_MOUNT_POINT
);
894 return path_is_mount_point(c
->parameter
, NULL
, AT_SYMLINK_FOLLOW
) > 0;
897 static int condition_test_path_is_read_write(Condition
*c
, char **env
) {
901 assert(c
->parameter
);
902 assert(c
->type
== CONDITION_PATH_IS_READ_WRITE
);
904 r
= path_is_read_only_fs(c
->parameter
);
906 return r
<= 0 && r
!= -ENOENT
;
909 static int condition_test_cpufeature(Condition
*c
, char **env
) {
911 assert(c
->parameter
);
912 assert(c
->type
== CONDITION_CPU_FEATURE
);
914 return has_cpu_with_flag(ascii_strlower(c
->parameter
));
917 static int condition_test_path_is_encrypted(Condition
*c
, char **env
) {
921 assert(c
->parameter
);
922 assert(c
->type
== CONDITION_PATH_IS_ENCRYPTED
);
924 r
= path_is_encrypted(c
->parameter
);
925 if (r
< 0 && r
!= -ENOENT
)
926 log_debug_errno(r
, "Failed to determine if '%s' is encrypted: %m", c
->parameter
);
931 static int condition_test_directory_not_empty(Condition
*c
, char **env
) {
935 assert(c
->parameter
);
936 assert(c
->type
== CONDITION_DIRECTORY_NOT_EMPTY
);
938 r
= dir_is_empty(c
->parameter
);
939 return r
<= 0 && !IN_SET(r
, -ENOENT
, -ENOTDIR
);
942 static int condition_test_file_not_empty(Condition
*c
, char **env
) {
946 assert(c
->parameter
);
947 assert(c
->type
== CONDITION_FILE_NOT_EMPTY
);
949 return (stat(c
->parameter
, &st
) >= 0 &&
950 S_ISREG(st
.st_mode
) &&
954 static int condition_test_file_is_executable(Condition
*c
, char **env
) {
958 assert(c
->parameter
);
959 assert(c
->type
== CONDITION_FILE_IS_EXECUTABLE
);
961 return (stat(c
->parameter
, &st
) >= 0 &&
962 S_ISREG(st
.st_mode
) &&
963 (st
.st_mode
& 0111));
966 static int condition_test_psi(Condition
*c
, char **env
) {
967 _cleanup_free_
char *first
= NULL
, *second
= NULL
, *third
= NULL
, *fourth
= NULL
, *pressure_path
= NULL
;
968 const char *p
, *value
, *pressure_type
;
969 loadavg_t
*current
, limit
;
970 ResourcePressure pressure
;
974 assert(c
->parameter
);
975 assert(IN_SET(c
->type
, CONDITION_MEMORY_PRESSURE
, CONDITION_CPU_PRESSURE
, CONDITION_IO_PRESSURE
));
977 if (!is_pressure_supported()) {
978 log_debug("Pressure Stall Information (PSI) is not supported, skipping.");
982 pressure_type
= c
->type
== CONDITION_MEMORY_PRESSURE
? "memory" :
983 c
->type
== CONDITION_CPU_PRESSURE
? "cpu" :
987 r
= extract_many_words(&p
, ":", 0, &first
, &second
, NULL
);
989 return log_debug_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
990 /* If only one parameter is passed, then we look at the global system pressure rather than a specific cgroup. */
992 pressure_path
= path_join("/proc/pressure", pressure_type
);
994 return log_oom_debug();
998 const char *controller
= strjoina(pressure_type
, ".pressure");
999 _cleanup_free_
char *slice_path
= NULL
, *root_scope
= NULL
;
1000 CGroupMask mask
, required_mask
;
1003 required_mask
= c
->type
== CONDITION_MEMORY_PRESSURE
? CGROUP_MASK_MEMORY
:
1004 c
->type
== CONDITION_CPU_PRESSURE
? CGROUP_MASK_CPU
:
1007 slice
= strstrip(first
);
1009 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1011 r
= cg_all_unified();
1013 return log_debug_errno(r
, "Failed to determine whether the unified cgroups hierarchy is used: %m");
1015 log_debug("PSI condition check requires the unified cgroups hierarchy, skipping.");
1019 r
= cg_mask_supported(&mask
);
1021 return log_debug_errno(r
, "Failed to get supported cgroup controllers: %m");
1023 if (!FLAGS_SET(mask
, required_mask
)) {
1024 log_debug("Cgroup %s controller not available, skipping PSI condition check.", pressure_type
);
1028 r
= cg_slice_to_path(slice
, &slice_path
);
1030 return log_debug_errno(r
, "Cannot determine slice \"%s\" cgroup path: %m", slice
);
1032 /* We might be running under the user manager, so get the root path and prefix it accordingly. */
1033 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, getpid_cached(), &root_scope
);
1035 return log_debug_errno(r
, "Failed to get root cgroup path: %m");
1037 /* Drop init.scope, we want the parent. We could get an empty or / path, but that's fine,
1038 * just skip it in that case. */
1039 e
= endswith(root_scope
, "/" SPECIAL_INIT_SCOPE
);
1042 if (!empty_or_root(root_scope
)) {
1043 _cleanup_free_
char *slice_joined
= NULL
;
1045 slice_joined
= path_join(root_scope
, slice_path
);
1047 return log_oom_debug();
1049 free_and_replace(slice_path
, slice_joined
);
1052 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, slice_path
, controller
, &pressure_path
);
1054 return log_debug_errno(r
, "Error getting cgroup pressure path from %s: %m", slice_path
);
1059 /* If a value including a specific timespan (in the intervals allowed by the kernel),
1060 * parse it, otherwise we assume just a plain percentage that will be checked if it is
1061 * smaller or equal to the current pressure average over 5 minutes. */
1062 r
= extract_many_words(&value
, "/", 0, &third
, &fourth
, NULL
);
1064 return log_debug_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1066 current
= &pressure
.avg300
;
1068 const char *timespan
;
1070 timespan
= skip_leading_chars(fourth
, NULL
);
1072 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1074 if (startswith(timespan
, "10sec"))
1075 current
= &pressure
.avg10
;
1076 else if (startswith(timespan
, "1min"))
1077 current
= &pressure
.avg60
;
1078 else if (startswith(timespan
, "5min"))
1079 current
= &pressure
.avg300
;
1081 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1084 value
= strstrip(third
);
1086 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1088 r
= parse_permyriad(value
);
1090 return log_debug_errno(r
, "Failed to parse permyriad: %s", c
->parameter
);
1092 r
= store_loadavg_fixed_point(r
/ 100LU, r
% 100LU, &limit
);
1094 return log_debug_errno(r
, "Failed to parse loadavg: %s", c
->parameter
);
1096 r
= read_resource_pressure(pressure_path
, PRESSURE_TYPE_FULL
, &pressure
);
1097 if (r
== -ENODATA
) /* cpu.pressure 'full' was added recently, fall back to 'some'. */
1098 r
= read_resource_pressure(pressure_path
, PRESSURE_TYPE_SOME
, &pressure
);
1100 /* We already checked that /proc/pressure exists, so this means we were given a cgroup
1101 * that doesn't exist or doesn't exist any longer. */
1102 log_debug("\"%s\" not found, skipping PSI check.", pressure_path
);
1106 return log_debug_errno(r
, "Error parsing pressure from %s: %m", pressure_path
);
1108 return *current
<= limit
;
1111 int condition_test(Condition
*c
, char **env
) {
1113 static int (*const condition_tests
[_CONDITION_TYPE_MAX
])(Condition
*c
, char **env
) = {
1114 [CONDITION_PATH_EXISTS
] = condition_test_path_exists
,
1115 [CONDITION_PATH_EXISTS_GLOB
] = condition_test_path_exists_glob
,
1116 [CONDITION_PATH_IS_DIRECTORY
] = condition_test_path_is_directory
,
1117 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = condition_test_path_is_symbolic_link
,
1118 [CONDITION_PATH_IS_MOUNT_POINT
] = condition_test_path_is_mount_point
,
1119 [CONDITION_PATH_IS_READ_WRITE
] = condition_test_path_is_read_write
,
1120 [CONDITION_PATH_IS_ENCRYPTED
] = condition_test_path_is_encrypted
,
1121 [CONDITION_DIRECTORY_NOT_EMPTY
] = condition_test_directory_not_empty
,
1122 [CONDITION_FILE_NOT_EMPTY
] = condition_test_file_not_empty
,
1123 [CONDITION_FILE_IS_EXECUTABLE
] = condition_test_file_is_executable
,
1124 [CONDITION_KERNEL_COMMAND_LINE
] = condition_test_kernel_command_line
,
1125 [CONDITION_KERNEL_VERSION
] = condition_test_kernel_version
,
1126 [CONDITION_VIRTUALIZATION
] = condition_test_virtualization
,
1127 [CONDITION_SECURITY
] = condition_test_security
,
1128 [CONDITION_CAPABILITY
] = condition_test_capability
,
1129 [CONDITION_HOST
] = condition_test_host
,
1130 [CONDITION_AC_POWER
] = condition_test_ac_power
,
1131 [CONDITION_ARCHITECTURE
] = condition_test_architecture
,
1132 [CONDITION_FIRMWARE
] = condition_test_firmware
,
1133 [CONDITION_NEEDS_UPDATE
] = condition_test_needs_update
,
1134 [CONDITION_FIRST_BOOT
] = condition_test_first_boot
,
1135 [CONDITION_USER
] = condition_test_user
,
1136 [CONDITION_GROUP
] = condition_test_group
,
1137 [CONDITION_CONTROL_GROUP_CONTROLLER
] = condition_test_control_group_controller
,
1138 [CONDITION_CPUS
] = condition_test_cpus
,
1139 [CONDITION_MEMORY
] = condition_test_memory
,
1140 [CONDITION_ENVIRONMENT
] = condition_test_environment
,
1141 [CONDITION_CPU_FEATURE
] = condition_test_cpufeature
,
1142 [CONDITION_OS_RELEASE
] = condition_test_osrelease
,
1143 [CONDITION_MEMORY_PRESSURE
] = condition_test_psi
,
1144 [CONDITION_CPU_PRESSURE
] = condition_test_psi
,
1145 [CONDITION_IO_PRESSURE
] = condition_test_psi
,
1151 assert(c
->type
>= 0);
1152 assert(c
->type
< _CONDITION_TYPE_MAX
);
1154 r
= condition_tests
[c
->type
](c
, env
);
1156 c
->result
= CONDITION_ERROR
;
1160 b
= (r
> 0) == !c
->negate
;
1161 c
->result
= b
? CONDITION_SUCCEEDED
: CONDITION_FAILED
;
1165 bool condition_test_list(
1168 condition_to_string_t to_string
,
1169 condition_test_logger_t logger
,
1174 assert(!!logger
== !!to_string
);
1176 /* If the condition list is empty, then it is true */
1180 /* Otherwise, if all of the non-trigger conditions apply and
1181 * if any of the trigger conditions apply (unless there are
1182 * none) we return true */
1183 LIST_FOREACH(conditions
, c
, first
) {
1186 r
= condition_test(c
, env
);
1190 logger(userdata
, LOG_WARNING
, r
, PROJECT_FILE
, __LINE__
, __func__
,
1191 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
1193 c
->trigger
? "|" : "",
1194 c
->negate
? "!" : "",
1197 logger(userdata
, LOG_DEBUG
, 0, PROJECT_FILE
, __LINE__
, __func__
,
1200 c
->trigger
? "|" : "",
1201 c
->negate
? "!" : "",
1203 condition_result_to_string(c
->result
));
1206 if (!c
->trigger
&& r
<= 0)
1209 if (c
->trigger
&& triggered
<= 0)
1213 return triggered
!= 0;
1216 void condition_dump(Condition
*c
, FILE *f
, const char *prefix
, condition_to_string_t to_string
) {
1221 prefix
= strempty(prefix
);
1224 "%s\t%s: %s%s%s %s\n",
1227 c
->trigger
? "|" : "",
1228 c
->negate
? "!" : "",
1230 condition_result_to_string(c
->result
));
1233 void condition_dump_list(Condition
*first
, FILE *f
, const char *prefix
, condition_to_string_t to_string
) {
1234 LIST_FOREACH(conditions
, c
, first
)
1235 condition_dump(c
, f
, prefix
, to_string
);
1238 static const char* const condition_type_table
[_CONDITION_TYPE_MAX
] = {
1239 [CONDITION_ARCHITECTURE
] = "ConditionArchitecture",
1240 [CONDITION_FIRMWARE
] = "ConditionFirmware",
1241 [CONDITION_VIRTUALIZATION
] = "ConditionVirtualization",
1242 [CONDITION_HOST
] = "ConditionHost",
1243 [CONDITION_KERNEL_COMMAND_LINE
] = "ConditionKernelCommandLine",
1244 [CONDITION_KERNEL_VERSION
] = "ConditionKernelVersion",
1245 [CONDITION_SECURITY
] = "ConditionSecurity",
1246 [CONDITION_CAPABILITY
] = "ConditionCapability",
1247 [CONDITION_AC_POWER
] = "ConditionACPower",
1248 [CONDITION_NEEDS_UPDATE
] = "ConditionNeedsUpdate",
1249 [CONDITION_FIRST_BOOT
] = "ConditionFirstBoot",
1250 [CONDITION_PATH_EXISTS
] = "ConditionPathExists",
1251 [CONDITION_PATH_EXISTS_GLOB
] = "ConditionPathExistsGlob",
1252 [CONDITION_PATH_IS_DIRECTORY
] = "ConditionPathIsDirectory",
1253 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = "ConditionPathIsSymbolicLink",
1254 [CONDITION_PATH_IS_MOUNT_POINT
] = "ConditionPathIsMountPoint",
1255 [CONDITION_PATH_IS_READ_WRITE
] = "ConditionPathIsReadWrite",
1256 [CONDITION_PATH_IS_ENCRYPTED
] = "ConditionPathIsEncrypted",
1257 [CONDITION_DIRECTORY_NOT_EMPTY
] = "ConditionDirectoryNotEmpty",
1258 [CONDITION_FILE_NOT_EMPTY
] = "ConditionFileNotEmpty",
1259 [CONDITION_FILE_IS_EXECUTABLE
] = "ConditionFileIsExecutable",
1260 [CONDITION_USER
] = "ConditionUser",
1261 [CONDITION_GROUP
] = "ConditionGroup",
1262 [CONDITION_CONTROL_GROUP_CONTROLLER
] = "ConditionControlGroupController",
1263 [CONDITION_CPUS
] = "ConditionCPUs",
1264 [CONDITION_MEMORY
] = "ConditionMemory",
1265 [CONDITION_ENVIRONMENT
] = "ConditionEnvironment",
1266 [CONDITION_CPU_FEATURE
] = "ConditionCPUFeature",
1267 [CONDITION_OS_RELEASE
] = "ConditionOSRelease",
1268 [CONDITION_MEMORY_PRESSURE
] = "ConditionMemoryPressure",
1269 [CONDITION_CPU_PRESSURE
] = "ConditionCPUPressure",
1270 [CONDITION_IO_PRESSURE
] = "ConditionIOPressure",
1273 DEFINE_STRING_TABLE_LOOKUP(condition_type
, ConditionType
);
1275 static const char* const assert_type_table
[_CONDITION_TYPE_MAX
] = {
1276 [CONDITION_ARCHITECTURE
] = "AssertArchitecture",
1277 [CONDITION_FIRMWARE
] = "AssertFirmware",
1278 [CONDITION_VIRTUALIZATION
] = "AssertVirtualization",
1279 [CONDITION_HOST
] = "AssertHost",
1280 [CONDITION_KERNEL_COMMAND_LINE
] = "AssertKernelCommandLine",
1281 [CONDITION_KERNEL_VERSION
] = "AssertKernelVersion",
1282 [CONDITION_SECURITY
] = "AssertSecurity",
1283 [CONDITION_CAPABILITY
] = "AssertCapability",
1284 [CONDITION_AC_POWER
] = "AssertACPower",
1285 [CONDITION_NEEDS_UPDATE
] = "AssertNeedsUpdate",
1286 [CONDITION_FIRST_BOOT
] = "AssertFirstBoot",
1287 [CONDITION_PATH_EXISTS
] = "AssertPathExists",
1288 [CONDITION_PATH_EXISTS_GLOB
] = "AssertPathExistsGlob",
1289 [CONDITION_PATH_IS_DIRECTORY
] = "AssertPathIsDirectory",
1290 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = "AssertPathIsSymbolicLink",
1291 [CONDITION_PATH_IS_MOUNT_POINT
] = "AssertPathIsMountPoint",
1292 [CONDITION_PATH_IS_READ_WRITE
] = "AssertPathIsReadWrite",
1293 [CONDITION_PATH_IS_ENCRYPTED
] = "AssertPathIsEncrypted",
1294 [CONDITION_DIRECTORY_NOT_EMPTY
] = "AssertDirectoryNotEmpty",
1295 [CONDITION_FILE_NOT_EMPTY
] = "AssertFileNotEmpty",
1296 [CONDITION_FILE_IS_EXECUTABLE
] = "AssertFileIsExecutable",
1297 [CONDITION_USER
] = "AssertUser",
1298 [CONDITION_GROUP
] = "AssertGroup",
1299 [CONDITION_CONTROL_GROUP_CONTROLLER
] = "AssertControlGroupController",
1300 [CONDITION_CPUS
] = "AssertCPUs",
1301 [CONDITION_MEMORY
] = "AssertMemory",
1302 [CONDITION_ENVIRONMENT
] = "AssertEnvironment",
1303 [CONDITION_CPU_FEATURE
] = "AssertCPUFeature",
1304 [CONDITION_OS_RELEASE
] = "AssertOSRelease",
1305 [CONDITION_MEMORY_PRESSURE
] = "AssertMemoryPressure",
1306 [CONDITION_CPU_PRESSURE
] = "AssertCPUPressure",
1307 [CONDITION_IO_PRESSURE
] = "AssertIOPressure",
1310 DEFINE_STRING_TABLE_LOOKUP(assert_type
, ConditionType
);
1312 static const char* const condition_result_table
[_CONDITION_RESULT_MAX
] = {
1313 [CONDITION_UNTESTED
] = "untested",
1314 [CONDITION_SUCCEEDED
] = "succeeded",
1315 [CONDITION_FAILED
] = "failed",
1316 [CONDITION_ERROR
] = "error",
1319 DEFINE_STRING_TABLE_LOOKUP(condition_result
, ConditionResult
);