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 "uid-alloc-range.h"
54 #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
) {
94 LIST_FOREACH_SAFE(conditions
, c
, n
, head
)
95 if (type
< 0 || c
->type
== type
) {
96 LIST_REMOVE(conditions
, head
, c
);
100 assert(type
>= 0 || !head
);
104 static int condition_test_kernel_command_line(Condition
*c
, char **env
) {
105 _cleanup_free_
char *line
= NULL
;
111 assert(c
->parameter
);
112 assert(c
->type
== CONDITION_KERNEL_COMMAND_LINE
);
114 r
= proc_cmdline(&line
);
118 equal
= strchr(c
->parameter
, '=');
121 _cleanup_free_
char *word
= NULL
;
124 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_UNQUOTE
|EXTRACT_RELAX
);
131 found
= streq(word
, c
->parameter
);
135 f
= startswith(word
, c
->parameter
);
136 found
= f
&& IN_SET(*f
, 0, '=');
147 /* Listed in order of checking. Note that some comparators are prefixes of others, hence the longest
148 * should be listed first. */
149 ORDER_LOWER_OR_EQUAL
,
150 ORDER_GREATER_OR_EQUAL
,
156 _ORDER_INVALID
= -EINVAL
,
159 static OrderOperator
parse_order(const char **s
) {
161 static const char *const prefix
[_ORDER_MAX
] = {
162 [ORDER_LOWER_OR_EQUAL
] = "<=",
163 [ORDER_GREATER_OR_EQUAL
] = ">=",
165 [ORDER_GREATER
] = ">",
167 [ORDER_UNEQUAL
] = "!=",
172 for (i
= 0; i
< _ORDER_MAX
; i
++) {
175 e
= startswith(*s
, prefix
[i
]);
182 return _ORDER_INVALID
;
185 static bool test_order(int k
, OrderOperator p
) {
192 case ORDER_LOWER_OR_EQUAL
:
201 case ORDER_GREATER_OR_EQUAL
:
208 assert_not_reached();
213 static int condition_test_kernel_version(Condition
*c
, char **env
) {
220 assert(c
->parameter
);
221 assert(c
->type
== CONDITION_KERNEL_VERSION
);
223 assert_se(uname(&u
) >= 0);
228 _cleanup_free_
char *word
= NULL
;
232 r
= extract_first_word(&p
, &word
, NULL
, EXTRACT_UNQUOTE
);
234 return log_debug_errno(r
, "Failed to parse condition string \"%s\": %m", p
);
239 order
= parse_order(&s
);
241 s
+= strspn(s
, WHITESPACE
);
244 /* For backwards compatibility, allow whitespace between the operator and
245 * value, without quoting, but only in the first expression. */
247 r
= extract_first_word(&p
, &word
, NULL
, 0);
249 return log_debug_errno(r
, "Failed to parse condition string \"%s\": %m", p
);
251 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected end of expression: %s", p
);
254 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Unexpected end of expression: %s", p
);
257 r
= test_order(strverscmp_improved(u
.release
, s
), order
);
259 /* No prefix? Then treat as glob string */
260 r
= fnmatch(s
, u
.release
, 0) == 0;
271 static int condition_test_osrelease(Condition
*c
, char **env
) {
272 const char *parameter
= c
->parameter
;
276 assert(c
->parameter
);
277 assert(c
->type
== CONDITION_OS_RELEASE
);
280 _cleanup_free_
char *key
= NULL
, *condition
= NULL
, *actual_value
= NULL
;
285 r
= extract_first_word(¶meter
, &condition
, NULL
, EXTRACT_UNQUOTE
);
287 return log_debug_errno(r
, "Failed to parse parameter: %m");
291 /* parse_order() needs the string to start with the comparators */
293 r
= extract_first_word(&word
, &key
, "!<=>", EXTRACT_RETAIN_SEPARATORS
);
295 return log_debug_errno(r
, "Failed to parse parameter: %m");
296 /* The os-release spec mandates env-var-like key names */
297 if (r
== 0 || isempty(word
) || !env_name_is_valid(key
))
298 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
299 "Failed to parse parameter, key/value format expected: %m");
301 /* Do not allow whitespace after the separator, as that's not a valid os-release format */
302 order
= parse_order(&word
);
303 if (order
< 0 || isempty(word
) || strchr(WHITESPACE
, *word
) != NULL
)
304 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
),
305 "Failed to parse parameter, key/value format expected: %m");
307 r
= parse_os_release(NULL
, key
, &actual_value
);
309 return log_debug_errno(r
, "Failed to parse os-release: %m");
311 /* Might not be comparing versions, so do exact string matching */
312 if (order
== ORDER_EQUAL
)
313 matches
= streq_ptr(actual_value
, word
);
314 else if (order
== ORDER_UNEQUAL
)
315 matches
= !streq_ptr(actual_value
, word
);
317 matches
= test_order(strverscmp_improved(actual_value
, word
), order
);
326 static int condition_test_memory(Condition
*c
, char **env
) {
333 assert(c
->parameter
);
334 assert(c
->type
== CONDITION_MEMORY
);
336 m
= physical_memory();
339 order
= parse_order(&p
);
341 order
= ORDER_GREATER_OR_EQUAL
; /* default to >= check, if nothing is specified. */
343 r
= safe_atou64(p
, &k
);
345 return log_debug_errno(r
, "Failed to parse size: %m");
347 return test_order(CMP(m
, k
), order
);
350 static int condition_test_cpus(Condition
*c
, char **env
) {
357 assert(c
->parameter
);
358 assert(c
->type
== CONDITION_CPUS
);
360 n
= cpus_in_affinity_mask();
362 return log_debug_errno(n
, "Failed to determine CPUs in affinity mask: %m");
365 order
= parse_order(&p
);
367 order
= ORDER_GREATER_OR_EQUAL
; /* default to >= check, if nothing is specified. */
369 r
= safe_atou(p
, &k
);
371 return log_debug_errno(r
, "Failed to parse number of CPUs: %m");
373 return test_order(CMP((unsigned) n
, k
), order
);
376 static int condition_test_user(Condition
*c
, char **env
) {
379 _cleanup_free_
char *username
= NULL
;
383 assert(c
->parameter
);
384 assert(c
->type
== CONDITION_USER
);
386 r
= parse_uid(c
->parameter
, &id
);
388 return id
== getuid() || id
== geteuid();
390 if (streq("@system", c
->parameter
))
391 return uid_is_system(getuid()) || uid_is_system(geteuid());
393 username
= getusername_malloc();
397 if (streq(username
, c
->parameter
))
400 if (getpid_cached() == 1)
401 return streq(c
->parameter
, "root");
404 r
= get_user_creds(&u
, &id
, NULL
, NULL
, NULL
, USER_CREDS_ALLOW_MISSING
);
408 return id
== getuid() || id
== geteuid();
411 static int condition_test_control_group_controller(Condition
*c
, char **env
) {
413 CGroupMask system_mask
, wanted_mask
= 0;
416 assert(c
->parameter
);
417 assert(c
->type
== CONDITION_CONTROL_GROUP_CONTROLLER
);
419 if (streq(c
->parameter
, "v2"))
420 return cg_all_unified();
421 if (streq(c
->parameter
, "v1")) {
422 r
= cg_all_unified();
428 r
= cg_mask_supported(&system_mask
);
430 return log_debug_errno(r
, "Failed to determine supported controllers: %m");
432 r
= cg_mask_from_string(c
->parameter
, &wanted_mask
);
433 if (r
< 0 || wanted_mask
<= 0) {
434 /* This won't catch the case that we have an unknown controller
435 * mixed in with valid ones -- these are only assessed on the
436 * validity of the valid controllers found. */
437 log_debug("Failed to parse cgroup string: %s", c
->parameter
);
441 return FLAGS_SET(system_mask
, wanted_mask
);
444 static int condition_test_group(Condition
*c
, char **env
) {
449 assert(c
->parameter
);
450 assert(c
->type
== CONDITION_GROUP
);
452 r
= parse_gid(c
->parameter
, &id
);
456 /* Avoid any NSS lookups if we are PID1 */
457 if (getpid_cached() == 1)
458 return streq(c
->parameter
, "root");
460 return in_group(c
->parameter
) > 0;
463 static int condition_test_virtualization(Condition
*c
, char **env
) {
467 assert(c
->parameter
);
468 assert(c
->type
== CONDITION_VIRTUALIZATION
);
470 if (streq(c
->parameter
, "private-users"))
471 return running_in_userns();
473 v
= detect_virtualization();
477 /* First, compare with yes/no */
478 b
= parse_boolean(c
->parameter
);
482 /* Then, compare categorization */
483 if (streq(c
->parameter
, "vm"))
484 return VIRTUALIZATION_IS_VM(v
);
486 if (streq(c
->parameter
, "container"))
487 return VIRTUALIZATION_IS_CONTAINER(v
);
489 /* Finally compare id */
490 return v
!= VIRTUALIZATION_NONE
&& streq(c
->parameter
, virtualization_to_string(v
));
493 static int condition_test_architecture(Condition
*c
, char **env
) {
497 assert(c
->parameter
);
498 assert(c
->type
== CONDITION_ARCHITECTURE
);
500 a
= uname_architecture();
504 if (streq(c
->parameter
, "native"))
505 b
= native_architecture();
507 b
= architecture_from_string(c
->parameter
);
508 if (b
< 0) /* unknown architecture? Then it's definitely not ours */
515 #define DTCOMPAT_FILE "/proc/device-tree/compatible"
516 static int condition_test_firmware_devicetree_compatible(const char *dtcarg
) {
518 _cleanup_free_
char *dtcompat
= NULL
;
519 _cleanup_strv_free_
char **dtcompatlist
= NULL
;
522 r
= read_full_virtual_file(DTCOMPAT_FILE
, &dtcompat
, &size
);
524 /* if the path doesn't exist it is incompatible */
526 log_debug_errno(r
, "Failed to open() '%s', assuming machine is incompatible: %m", DTCOMPAT_FILE
);
530 /* Not sure this can happen, but play safe. */
532 log_debug("%s has zero length, assuming machine is incompatible", DTCOMPAT_FILE
);
536 /* /proc/device-tree/compatible consists of one or more strings, each ending in '\0'.
537 * So the last character in dtcompat must be a '\0'. */
538 if (dtcompat
[size
- 1] != '\0') {
539 log_debug("%s is in an unknown format, assuming machine is incompatible", DTCOMPAT_FILE
);
543 dtcompatlist
= strv_parse_nulstr(dtcompat
, size
);
547 return strv_contains(dtcompatlist
, dtcarg
);
550 static int condition_test_firmware(Condition
*c
, char **env
) {
554 assert(c
->parameter
);
555 assert(c
->type
== CONDITION_FIRMWARE
);
557 if (streq(c
->parameter
, "device-tree")) {
558 if (access("/sys/firmware/device-tree/", F_OK
) < 0) {
560 log_debug_errno(errno
, "Unexpected error when checking for /sys/firmware/device-tree/: %m");
564 } else if ((dtc
= startswith(c
->parameter
, "device-tree-compatible("))) {
565 _cleanup_free_
char *dtcarg
= NULL
;
568 end
= strchr(dtc
, ')');
569 if (!end
|| *(end
+ 1) != '\0') {
570 log_debug("Malformed Firmware condition \"%s\"", c
->parameter
);
574 dtcarg
= strndup(dtc
, end
- dtc
);
578 return condition_test_firmware_devicetree_compatible(dtcarg
);
579 } else if (streq(c
->parameter
, "uefi"))
580 return is_efi_boot();
582 log_debug("Unsupported Firmware condition \"%s\"", c
->parameter
);
587 static int condition_test_host(Condition
*c
, char **env
) {
588 _cleanup_free_
char *h
= NULL
;
593 assert(c
->parameter
);
594 assert(c
->type
== CONDITION_HOST
);
596 if (sd_id128_from_string(c
->parameter
, &x
) >= 0) {
598 r
= sd_id128_get_machine(&y
);
602 return sd_id128_equal(x
, y
);
605 h
= gethostname_malloc();
609 return fnmatch(c
->parameter
, h
, FNM_CASEFOLD
) == 0;
612 static int condition_test_ac_power(Condition
*c
, char **env
) {
616 assert(c
->parameter
);
617 assert(c
->type
== CONDITION_AC_POWER
);
619 r
= parse_boolean(c
->parameter
);
623 return (on_ac_power() != 0) == !!r
;
626 static int has_tpm2(void) {
629 /* Checks whether the system has at least one TPM2 resource manager device, i.e. at least one "tpmrm"
632 r
= dir_is_empty("/sys/class/tpmrm");
634 return true; /* nice! we have a device */
636 /* Hmm, so Linux doesn't know of the TPM2 device (or we couldn't check for it), most likely because
637 * the driver wasn't loaded yet. Let's see if the firmware knows about a TPM2 device, in this
638 * case. This way we can answer the TPM2 question already during early boot (where we most likely
643 /* OK, this didn't work either, in this case propagate the original errors */
647 return log_debug_errno(r
, "Failed to determine whether system has TPM2 support: %m");
652 static int condition_test_security(Condition
*c
, char **env
) {
654 assert(c
->parameter
);
655 assert(c
->type
== CONDITION_SECURITY
);
657 if (streq(c
->parameter
, "selinux"))
658 return mac_selinux_use();
659 if (streq(c
->parameter
, "smack"))
660 return mac_smack_use();
661 if (streq(c
->parameter
, "apparmor"))
662 return mac_apparmor_use();
663 if (streq(c
->parameter
, "audit"))
665 if (streq(c
->parameter
, "ima"))
667 if (streq(c
->parameter
, "tomoyo"))
668 return mac_tomoyo_use();
669 if (streq(c
->parameter
, "uefi-secureboot"))
670 return is_efi_secure_boot();
671 if (streq(c
->parameter
, "tpm2"))
677 static int condition_test_capability(Condition
*c
, char **env
) {
678 unsigned long long capabilities
= (unsigned long long) -1;
679 _cleanup_fclose_
FILE *f
= NULL
;
683 assert(c
->parameter
);
684 assert(c
->type
== CONDITION_CAPABILITY
);
686 /* If it's an invalid capability, we don't have it */
687 value
= capability_from_name(c
->parameter
);
691 /* If it's a valid capability we default to assume
694 f
= fopen("/proc/self/status", "re");
699 _cleanup_free_
char *line
= NULL
;
702 r
= read_line(f
, LONG_LINE_MAX
, &line
);
708 p
= startswith(line
, "CapBnd:");
710 if (sscanf(line
+7, "%llx", &capabilities
) != 1)
717 return !!(capabilities
& (1ULL << value
));
720 static int condition_test_needs_update(Condition
*c
, char **env
) {
721 struct stat usr
, other
;
727 assert(c
->parameter
);
728 assert(c
->type
== CONDITION_NEEDS_UPDATE
);
730 r
= proc_cmdline_get_bool("systemd.condition-needs-update", &b
);
732 log_debug_errno(r
, "Failed to parse systemd.condition-needs-update= kernel command line argument, ignoring: %m");
737 log_debug("We are in an initrd, not doing any updates.");
741 if (!path_is_absolute(c
->parameter
)) {
742 log_debug("Specified condition parameter '%s' is not absolute, assuming an update is needed.", c
->parameter
);
746 /* If the file system is read-only we shouldn't suggest an update */
747 r
= path_is_read_only_fs(c
->parameter
);
749 log_debug_errno(r
, "Failed to determine if '%s' is read-only, ignoring: %m", c
->parameter
);
753 /* Any other failure means we should allow the condition to be true, so that we rather invoke too
754 * many update tools than too few. */
756 p
= strjoina(c
->parameter
, "/.updated");
757 if (lstat(p
, &other
) < 0) {
759 log_debug_errno(errno
, "Failed to stat() '%s', assuming an update is needed: %m", p
);
763 if (lstat("/usr/", &usr
) < 0) {
764 log_debug_errno(errno
, "Failed to stat() /usr/, assuming an update is needed: %m");
769 * First, compare seconds as they are always accurate...
771 if (usr
.st_mtim
.tv_sec
!= other
.st_mtim
.tv_sec
)
772 return usr
.st_mtim
.tv_sec
> other
.st_mtim
.tv_sec
;
775 * ...then compare nanoseconds.
777 * A false positive is only possible when /usr's nanoseconds > 0
778 * (otherwise /usr cannot be strictly newer than the target file)
779 * AND the target file's nanoseconds == 0
780 * (otherwise the filesystem supports nsec timestamps, see stat(2)).
782 if (usr
.st_mtim
.tv_nsec
== 0 || other
.st_mtim
.tv_nsec
> 0)
783 return usr
.st_mtim
.tv_nsec
> other
.st_mtim
.tv_nsec
;
785 _cleanup_free_
char *timestamp_str
= NULL
;
786 r
= parse_env_file(NULL
, p
, "TIMESTAMP_NSEC", ×tamp_str
);
788 log_debug_errno(r
, "Failed to parse timestamp file '%s', using mtime: %m", p
);
791 log_debug("No data in timestamp file '%s', using mtime.", p
);
796 r
= safe_atou64(timestamp_str
, ×tamp
);
798 log_debug_errno(r
, "Failed to parse timestamp value '%s' in file '%s', using mtime: %m", timestamp_str
, p
);
802 return timespec_load_nsec(&usr
.st_mtim
) > timestamp
;
805 static int condition_test_first_boot(Condition
*c
, char **env
) {
810 assert(c
->parameter
);
811 assert(c
->type
== CONDITION_FIRST_BOOT
);
813 r
= proc_cmdline_get_bool("systemd.condition-first-boot", &b
);
815 log_debug_errno(r
, "Failed to parse systemd.condition-first-boot= kernel command line argument, ignoring: %m");
819 r
= parse_boolean(c
->parameter
);
823 q
= access("/run/systemd/first-boot", F_OK
);
824 if (q
< 0 && errno
!= ENOENT
)
825 log_debug_errno(errno
, "Failed to check if /run/systemd/first-boot exists, ignoring: %m");
827 return (q
>= 0) == !!r
;
830 static int condition_test_environment(Condition
*c
, char **env
) {
835 assert(c
->parameter
);
836 assert(c
->type
== CONDITION_ENVIRONMENT
);
838 equal
= strchr(c
->parameter
, '=');
840 STRV_FOREACH(i
, env
) {
844 found
= streq(c
->parameter
, *i
);
848 f
= startswith(*i
, c
->parameter
);
849 found
= f
&& IN_SET(*f
, 0, '=');
859 static int condition_test_path_exists(Condition
*c
, char **env
) {
861 assert(c
->parameter
);
862 assert(c
->type
== CONDITION_PATH_EXISTS
);
864 return access(c
->parameter
, F_OK
) >= 0;
867 static int condition_test_path_exists_glob(Condition
*c
, char **env
) {
869 assert(c
->parameter
);
870 assert(c
->type
== CONDITION_PATH_EXISTS_GLOB
);
872 return glob_exists(c
->parameter
) > 0;
875 static int condition_test_path_is_directory(Condition
*c
, char **env
) {
877 assert(c
->parameter
);
878 assert(c
->type
== CONDITION_PATH_IS_DIRECTORY
);
880 return is_dir(c
->parameter
, true) > 0;
883 static int condition_test_path_is_symbolic_link(Condition
*c
, char **env
) {
885 assert(c
->parameter
);
886 assert(c
->type
== CONDITION_PATH_IS_SYMBOLIC_LINK
);
888 return is_symlink(c
->parameter
) > 0;
891 static int condition_test_path_is_mount_point(Condition
*c
, char **env
) {
893 assert(c
->parameter
);
894 assert(c
->type
== CONDITION_PATH_IS_MOUNT_POINT
);
896 return path_is_mount_point(c
->parameter
, NULL
, AT_SYMLINK_FOLLOW
) > 0;
899 static int condition_test_path_is_read_write(Condition
*c
, char **env
) {
903 assert(c
->parameter
);
904 assert(c
->type
== CONDITION_PATH_IS_READ_WRITE
);
906 r
= path_is_read_only_fs(c
->parameter
);
908 return r
<= 0 && r
!= -ENOENT
;
911 static int condition_test_cpufeature(Condition
*c
, char **env
) {
913 assert(c
->parameter
);
914 assert(c
->type
== CONDITION_CPU_FEATURE
);
916 return has_cpu_with_flag(ascii_strlower(c
->parameter
));
919 static int condition_test_path_is_encrypted(Condition
*c
, char **env
) {
923 assert(c
->parameter
);
924 assert(c
->type
== CONDITION_PATH_IS_ENCRYPTED
);
926 r
= path_is_encrypted(c
->parameter
);
927 if (r
< 0 && r
!= -ENOENT
)
928 log_debug_errno(r
, "Failed to determine if '%s' is encrypted: %m", c
->parameter
);
933 static int condition_test_directory_not_empty(Condition
*c
, char **env
) {
937 assert(c
->parameter
);
938 assert(c
->type
== CONDITION_DIRECTORY_NOT_EMPTY
);
940 r
= dir_is_empty(c
->parameter
);
941 return r
<= 0 && !IN_SET(r
, -ENOENT
, -ENOTDIR
);
944 static int condition_test_file_not_empty(Condition
*c
, char **env
) {
948 assert(c
->parameter
);
949 assert(c
->type
== CONDITION_FILE_NOT_EMPTY
);
951 return (stat(c
->parameter
, &st
) >= 0 &&
952 S_ISREG(st
.st_mode
) &&
956 static int condition_test_file_is_executable(Condition
*c
, char **env
) {
960 assert(c
->parameter
);
961 assert(c
->type
== CONDITION_FILE_IS_EXECUTABLE
);
963 return (stat(c
->parameter
, &st
) >= 0 &&
964 S_ISREG(st
.st_mode
) &&
965 (st
.st_mode
& 0111));
968 static int condition_test_psi(Condition
*c
, char **env
) {
969 _cleanup_free_
char *first
= NULL
, *second
= NULL
, *third
= NULL
, *fourth
= NULL
, *pressure_path
= NULL
;
970 const char *p
, *value
, *pressure_type
;
971 loadavg_t
*current
, limit
;
972 ResourcePressure pressure
;
976 assert(c
->parameter
);
977 assert(IN_SET(c
->type
, CONDITION_MEMORY_PRESSURE
, CONDITION_CPU_PRESSURE
, CONDITION_IO_PRESSURE
));
979 if (!is_pressure_supported()) {
980 log_debug("Pressure Stall Information (PSI) is not supported, skipping.");
984 pressure_type
= c
->type
== CONDITION_MEMORY_PRESSURE
? "memory" :
985 c
->type
== CONDITION_CPU_PRESSURE
? "cpu" :
989 r
= extract_many_words(&p
, ":", 0, &first
, &second
, NULL
);
991 return log_debug_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
992 /* If only one parameter is passed, then we look at the global system pressure rather than a specific cgroup. */
994 pressure_path
= path_join("/proc/pressure", pressure_type
);
996 return log_oom_debug();
1000 const char *controller
= strjoina(pressure_type
, ".pressure");
1001 _cleanup_free_
char *slice_path
= NULL
, *root_scope
= NULL
;
1002 CGroupMask mask
, required_mask
;
1005 required_mask
= c
->type
== CONDITION_MEMORY_PRESSURE
? CGROUP_MASK_MEMORY
:
1006 c
->type
== CONDITION_CPU_PRESSURE
? CGROUP_MASK_CPU
:
1009 slice
= strstrip(first
);
1011 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1013 r
= cg_all_unified();
1015 return log_debug_errno(r
, "Failed to determine whether the unified cgroups hierarchy is used: %m");
1017 log_debug("PSI condition check requires the unified cgroups hierarchy, skipping.");
1021 r
= cg_mask_supported(&mask
);
1023 return log_debug_errno(r
, "Failed to get supported cgroup controllers: %m");
1025 if (!FLAGS_SET(mask
, required_mask
)) {
1026 log_debug("Cgroup %s controller not available, skipping PSI condition check.", pressure_type
);
1030 r
= cg_slice_to_path(slice
, &slice_path
);
1032 return log_debug_errno(r
, "Cannot determine slice \"%s\" cgroup path: %m", slice
);
1034 /* We might be running under the user manager, so get the root path and prefix it accordingly. */
1035 r
= cg_pid_get_path(SYSTEMD_CGROUP_CONTROLLER
, getpid_cached(), &root_scope
);
1037 return log_debug_errno(r
, "Failed to get root cgroup path: %m");
1039 /* Drop init.scope, we want the parent. We could get an empty or / path, but that's fine,
1040 * just skip it in that case. */
1041 e
= endswith(root_scope
, "/" SPECIAL_INIT_SCOPE
);
1044 if (!empty_or_root(root_scope
)) {
1045 _cleanup_free_
char *slice_joined
= NULL
;
1047 slice_joined
= path_join(root_scope
, slice_path
);
1049 return log_oom_debug();
1051 free_and_replace(slice_path
, slice_joined
);
1054 r
= cg_get_path(SYSTEMD_CGROUP_CONTROLLER
, slice_path
, controller
, &pressure_path
);
1056 return log_debug_errno(r
, "Error getting cgroup pressure path from %s: %m", slice_path
);
1061 /* If a value including a specific timespan (in the intervals allowed by the kernel),
1062 * parse it, otherwise we assume just a plain percentage that will be checked if it is
1063 * smaller or equal to the current pressure average over 5 minutes. */
1064 r
= extract_many_words(&value
, "/", 0, &third
, &fourth
, NULL
);
1066 return log_debug_errno(r
< 0 ? r
: SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1068 current
= &pressure
.avg300
;
1070 const char *timespan
;
1072 timespan
= skip_leading_chars(fourth
, NULL
);
1074 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1076 if (startswith(timespan
, "10sec"))
1077 current
= &pressure
.avg10
;
1078 else if (startswith(timespan
, "1min"))
1079 current
= &pressure
.avg60
;
1080 else if (startswith(timespan
, "5min"))
1081 current
= &pressure
.avg300
;
1083 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1086 value
= strstrip(third
);
1088 return log_debug_errno(SYNTHETIC_ERRNO(EINVAL
), "Failed to parse condition parameter %s: %m", c
->parameter
);
1090 r
= parse_permyriad(value
);
1092 return log_debug_errno(r
, "Failed to parse permyriad: %s", c
->parameter
);
1094 r
= store_loadavg_fixed_point(r
/ 100LU, r
% 100LU, &limit
);
1096 return log_debug_errno(r
, "Failed to parse loadavg: %s", c
->parameter
);
1098 r
= read_resource_pressure(pressure_path
, PRESSURE_TYPE_FULL
, &pressure
);
1099 if (r
== -ENODATA
) /* cpu.pressure 'full' was added recently, fall back to 'some'. */
1100 r
= read_resource_pressure(pressure_path
, PRESSURE_TYPE_SOME
, &pressure
);
1102 /* We already checked that /proc/pressure exists, so this means we were given a cgroup
1103 * that doesn't exist or doesn't exist any longer. */
1104 log_debug("\"%s\" not found, skipping PSI check.", pressure_path
);
1108 return log_debug_errno(r
, "Error parsing pressure from %s: %m", pressure_path
);
1110 return *current
<= limit
;
1113 int condition_test(Condition
*c
, char **env
) {
1115 static int (*const condition_tests
[_CONDITION_TYPE_MAX
])(Condition
*c
, char **env
) = {
1116 [CONDITION_PATH_EXISTS
] = condition_test_path_exists
,
1117 [CONDITION_PATH_EXISTS_GLOB
] = condition_test_path_exists_glob
,
1118 [CONDITION_PATH_IS_DIRECTORY
] = condition_test_path_is_directory
,
1119 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = condition_test_path_is_symbolic_link
,
1120 [CONDITION_PATH_IS_MOUNT_POINT
] = condition_test_path_is_mount_point
,
1121 [CONDITION_PATH_IS_READ_WRITE
] = condition_test_path_is_read_write
,
1122 [CONDITION_PATH_IS_ENCRYPTED
] = condition_test_path_is_encrypted
,
1123 [CONDITION_DIRECTORY_NOT_EMPTY
] = condition_test_directory_not_empty
,
1124 [CONDITION_FILE_NOT_EMPTY
] = condition_test_file_not_empty
,
1125 [CONDITION_FILE_IS_EXECUTABLE
] = condition_test_file_is_executable
,
1126 [CONDITION_KERNEL_COMMAND_LINE
] = condition_test_kernel_command_line
,
1127 [CONDITION_KERNEL_VERSION
] = condition_test_kernel_version
,
1128 [CONDITION_VIRTUALIZATION
] = condition_test_virtualization
,
1129 [CONDITION_SECURITY
] = condition_test_security
,
1130 [CONDITION_CAPABILITY
] = condition_test_capability
,
1131 [CONDITION_HOST
] = condition_test_host
,
1132 [CONDITION_AC_POWER
] = condition_test_ac_power
,
1133 [CONDITION_ARCHITECTURE
] = condition_test_architecture
,
1134 [CONDITION_FIRMWARE
] = condition_test_firmware
,
1135 [CONDITION_NEEDS_UPDATE
] = condition_test_needs_update
,
1136 [CONDITION_FIRST_BOOT
] = condition_test_first_boot
,
1137 [CONDITION_USER
] = condition_test_user
,
1138 [CONDITION_GROUP
] = condition_test_group
,
1139 [CONDITION_CONTROL_GROUP_CONTROLLER
] = condition_test_control_group_controller
,
1140 [CONDITION_CPUS
] = condition_test_cpus
,
1141 [CONDITION_MEMORY
] = condition_test_memory
,
1142 [CONDITION_ENVIRONMENT
] = condition_test_environment
,
1143 [CONDITION_CPU_FEATURE
] = condition_test_cpufeature
,
1144 [CONDITION_OS_RELEASE
] = condition_test_osrelease
,
1145 [CONDITION_MEMORY_PRESSURE
] = condition_test_psi
,
1146 [CONDITION_CPU_PRESSURE
] = condition_test_psi
,
1147 [CONDITION_IO_PRESSURE
] = condition_test_psi
,
1153 assert(c
->type
>= 0);
1154 assert(c
->type
< _CONDITION_TYPE_MAX
);
1156 r
= condition_tests
[c
->type
](c
, env
);
1158 c
->result
= CONDITION_ERROR
;
1162 b
= (r
> 0) == !c
->negate
;
1163 c
->result
= b
? CONDITION_SUCCEEDED
: CONDITION_FAILED
;
1167 bool condition_test_list(
1170 condition_to_string_t to_string
,
1171 condition_test_logger_t logger
,
1177 assert(!!logger
== !!to_string
);
1179 /* If the condition list is empty, then it is true */
1183 /* Otherwise, if all of the non-trigger conditions apply and
1184 * if any of the trigger conditions apply (unless there are
1185 * none) we return true */
1186 LIST_FOREACH(conditions
, c
, first
) {
1189 r
= condition_test(c
, env
);
1193 logger(userdata
, LOG_WARNING
, r
, PROJECT_FILE
, __LINE__
, __func__
,
1194 "Couldn't determine result for %s=%s%s%s, assuming failed: %m",
1196 c
->trigger
? "|" : "",
1197 c
->negate
? "!" : "",
1200 logger(userdata
, LOG_DEBUG
, 0, PROJECT_FILE
, __LINE__
, __func__
,
1203 c
->trigger
? "|" : "",
1204 c
->negate
? "!" : "",
1206 condition_result_to_string(c
->result
));
1209 if (!c
->trigger
&& r
<= 0)
1212 if (c
->trigger
&& triggered
<= 0)
1216 return triggered
!= 0;
1219 void condition_dump(Condition
*c
, FILE *f
, const char *prefix
, condition_to_string_t to_string
) {
1224 prefix
= strempty(prefix
);
1227 "%s\t%s: %s%s%s %s\n",
1230 c
->trigger
? "|" : "",
1231 c
->negate
? "!" : "",
1233 condition_result_to_string(c
->result
));
1236 void condition_dump_list(Condition
*first
, FILE *f
, const char *prefix
, condition_to_string_t to_string
) {
1239 LIST_FOREACH(conditions
, c
, first
)
1240 condition_dump(c
, f
, prefix
, to_string
);
1243 static const char* const condition_type_table
[_CONDITION_TYPE_MAX
] = {
1244 [CONDITION_ARCHITECTURE
] = "ConditionArchitecture",
1245 [CONDITION_FIRMWARE
] = "ConditionFirmware",
1246 [CONDITION_VIRTUALIZATION
] = "ConditionVirtualization",
1247 [CONDITION_HOST
] = "ConditionHost",
1248 [CONDITION_KERNEL_COMMAND_LINE
] = "ConditionKernelCommandLine",
1249 [CONDITION_KERNEL_VERSION
] = "ConditionKernelVersion",
1250 [CONDITION_SECURITY
] = "ConditionSecurity",
1251 [CONDITION_CAPABILITY
] = "ConditionCapability",
1252 [CONDITION_AC_POWER
] = "ConditionACPower",
1253 [CONDITION_NEEDS_UPDATE
] = "ConditionNeedsUpdate",
1254 [CONDITION_FIRST_BOOT
] = "ConditionFirstBoot",
1255 [CONDITION_PATH_EXISTS
] = "ConditionPathExists",
1256 [CONDITION_PATH_EXISTS_GLOB
] = "ConditionPathExistsGlob",
1257 [CONDITION_PATH_IS_DIRECTORY
] = "ConditionPathIsDirectory",
1258 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = "ConditionPathIsSymbolicLink",
1259 [CONDITION_PATH_IS_MOUNT_POINT
] = "ConditionPathIsMountPoint",
1260 [CONDITION_PATH_IS_READ_WRITE
] = "ConditionPathIsReadWrite",
1261 [CONDITION_PATH_IS_ENCRYPTED
] = "ConditionPathIsEncrypted",
1262 [CONDITION_DIRECTORY_NOT_EMPTY
] = "ConditionDirectoryNotEmpty",
1263 [CONDITION_FILE_NOT_EMPTY
] = "ConditionFileNotEmpty",
1264 [CONDITION_FILE_IS_EXECUTABLE
] = "ConditionFileIsExecutable",
1265 [CONDITION_USER
] = "ConditionUser",
1266 [CONDITION_GROUP
] = "ConditionGroup",
1267 [CONDITION_CONTROL_GROUP_CONTROLLER
] = "ConditionControlGroupController",
1268 [CONDITION_CPUS
] = "ConditionCPUs",
1269 [CONDITION_MEMORY
] = "ConditionMemory",
1270 [CONDITION_ENVIRONMENT
] = "ConditionEnvironment",
1271 [CONDITION_CPU_FEATURE
] = "ConditionCPUFeature",
1272 [CONDITION_OS_RELEASE
] = "ConditionOSRelease",
1273 [CONDITION_MEMORY_PRESSURE
] = "ConditionMemoryPressure",
1274 [CONDITION_CPU_PRESSURE
] = "ConditionCPUPressure",
1275 [CONDITION_IO_PRESSURE
] = "ConditionIOPressure",
1278 DEFINE_STRING_TABLE_LOOKUP(condition_type
, ConditionType
);
1280 static const char* const assert_type_table
[_CONDITION_TYPE_MAX
] = {
1281 [CONDITION_ARCHITECTURE
] = "AssertArchitecture",
1282 [CONDITION_FIRMWARE
] = "AssertFirmware",
1283 [CONDITION_VIRTUALIZATION
] = "AssertVirtualization",
1284 [CONDITION_HOST
] = "AssertHost",
1285 [CONDITION_KERNEL_COMMAND_LINE
] = "AssertKernelCommandLine",
1286 [CONDITION_KERNEL_VERSION
] = "AssertKernelVersion",
1287 [CONDITION_SECURITY
] = "AssertSecurity",
1288 [CONDITION_CAPABILITY
] = "AssertCapability",
1289 [CONDITION_AC_POWER
] = "AssertACPower",
1290 [CONDITION_NEEDS_UPDATE
] = "AssertNeedsUpdate",
1291 [CONDITION_FIRST_BOOT
] = "AssertFirstBoot",
1292 [CONDITION_PATH_EXISTS
] = "AssertPathExists",
1293 [CONDITION_PATH_EXISTS_GLOB
] = "AssertPathExistsGlob",
1294 [CONDITION_PATH_IS_DIRECTORY
] = "AssertPathIsDirectory",
1295 [CONDITION_PATH_IS_SYMBOLIC_LINK
] = "AssertPathIsSymbolicLink",
1296 [CONDITION_PATH_IS_MOUNT_POINT
] = "AssertPathIsMountPoint",
1297 [CONDITION_PATH_IS_READ_WRITE
] = "AssertPathIsReadWrite",
1298 [CONDITION_PATH_IS_ENCRYPTED
] = "AssertPathIsEncrypted",
1299 [CONDITION_DIRECTORY_NOT_EMPTY
] = "AssertDirectoryNotEmpty",
1300 [CONDITION_FILE_NOT_EMPTY
] = "AssertFileNotEmpty",
1301 [CONDITION_FILE_IS_EXECUTABLE
] = "AssertFileIsExecutable",
1302 [CONDITION_USER
] = "AssertUser",
1303 [CONDITION_GROUP
] = "AssertGroup",
1304 [CONDITION_CONTROL_GROUP_CONTROLLER
] = "AssertControlGroupController",
1305 [CONDITION_CPUS
] = "AssertCPUs",
1306 [CONDITION_MEMORY
] = "AssertMemory",
1307 [CONDITION_ENVIRONMENT
] = "AssertEnvironment",
1308 [CONDITION_CPU_FEATURE
] = "AssertCPUFeature",
1309 [CONDITION_OS_RELEASE
] = "AssertOSRelease",
1310 [CONDITION_MEMORY_PRESSURE
] = "AssertMemoryPressure",
1311 [CONDITION_CPU_PRESSURE
] = "AssertCPUPressure",
1312 [CONDITION_IO_PRESSURE
] = "AssertIOPressure",
1315 DEFINE_STRING_TABLE_LOOKUP(assert_type
, ConditionType
);
1317 static const char* const condition_result_table
[_CONDITION_RESULT_MAX
] = {
1318 [CONDITION_UNTESTED
] = "untested",
1319 [CONDITION_SUCCEEDED
] = "succeeded",
1320 [CONDITION_FAILED
] = "failed",
1321 [CONDITION_ERROR
] = "error",
1324 DEFINE_STRING_TABLE_LOOKUP(condition_result
, ConditionResult
);