]> git.ipfire.org Git - thirdparty/systemd.git/commitdiff
Merge pull request #29525 from poettering/confext-sysext-multimodal
authorLuca Boccassi <bluca@debian.org>
Fri, 13 Oct 2023 23:28:47 +0000 (00:28 +0100)
committerGitHub <noreply@github.com>
Fri, 13 Oct 2023 23:28:47 +0000 (00:28 +0100)
dissect: make sure we can dissect and inspect DDIs that are both confext *and* sysext

108 files changed:
NEWS
TODO
docs/ARCHITECTURE.md
man/kernel-install.xml
man/loader.conf.xml
man/systemd-boot.xml
man/systemd.exec.xml
man/systemd.network.xml
meson.build
po/fr.po
src/basic/cgroup-util.h
src/basic/env-util.c
src/basic/env-util.h
src/basic/macro.h
src/basic/process-util.c
src/basic/process-util.h
src/boot/efi/boot.c
src/core/bpf-lsm.c
src/core/bpf-lsm.h
src/core/cgroup.c
src/core/cgroup.h
src/core/core-varlink.c
src/core/dbus-cgroup.c
src/core/dynamic-user.c
src/core/dynamic-user.h
src/core/exec-credential.c
src/core/exec-invoke.c [new file with mode: 0644]
src/core/exec-invoke.h [new file with mode: 0644]
src/core/execute-serialize.c [new file with mode: 0644]
src/core/execute-serialize.h [new file with mode: 0644]
src/core/execute.c
src/core/execute.h
src/core/executor.c [new file with mode: 0644]
src/core/fuzz-manager-serialize.c
src/core/fuzz-unit-file.c
src/core/manager-serialize.c
src/core/manager.c
src/core/manager.h
src/core/meson.build
src/core/mount.c
src/core/namespace.c
src/core/service.c
src/core/socket.c
src/core/swap.c
src/core/unit-serialize.c
src/core/unit-serialize.h
src/core/unit.c
src/core/unit.h
src/fundamental/macro-fundamental.h
src/hibernate-resume/hibernate-resume-config.c
src/kernel-install/60-ukify.install.in
src/kernel-install/90-loaderentry.install.in
src/kernel-install/test-kernel-install.sh
src/libsystemd-network/dhcp-lease-internal.h
src/libsystemd-network/dhcp-protocol.h
src/libsystemd-network/dhcp-server-internal.h
src/libsystemd-network/sd-dhcp-client.c
src/libsystemd-network/sd-dhcp-lease.c
src/libsystemd-network/sd-dhcp-server.c
src/libsystemd/libsystemd.sym
src/libsystemd/sd-device/device-enumerator.c
src/libsystemd/sd-device/test-sd-device.c
src/network/networkd-address.c
src/network/networkd-dhcp-server.c
src/network/networkd-dhcp-server.h
src/network/networkd-dhcp4.c
src/network/networkd-dhcp4.h
src/network/networkd-link-bus.c
src/network/networkd-link.c
src/network/networkd-link.h
src/network/networkd-network-gperf.gperf
src/network/networkd-network.c
src/network/networkd-network.h
src/network/networkd-route-util.c
src/network/networkd-route-util.h
src/network/networkd-route.c
src/run/run.c
src/shared/dissect-image.c
src/shared/dissect-image.h
src/shared/dns-domain.c
src/shared/mount-util.c
src/shared/serialize.c
src/shared/serialize.h
src/shared/tpm2-util.c
src/shared/varlink-idl.c
src/shared/varlink-org.varlink.service.c
src/shared/varlink.c
src/shared/varlink.h
src/systemd/sd-device.h
src/systemd/sd-dhcp-client.h
src/systemd/sd-dhcp-server.h
src/test/test-fd-util.c
src/test/test-serialize.c
src/test/test-varlink-idl.c
src/timedate/timedatectl.c
src/timedate/timedated.c
src/ukify/ukify.py
src/varlinkctl/varlinkctl.c
test/test-network/conf/25-dhcp-client-ipv6-only-mode.network [new file with mode: 0644]
test/test-network/conf/25-dhcp-client-ipv6-only.network
test/test-network/conf/25-dhcp-server-ipv6-only-mode.network [new file with mode: 0644]
test/test-network/systemd-networkd-tests.py
test/testsuite-04.units/logs-filtering.service
test/testsuite-23.units/testsuite-23-binds-to.service
test/units/testsuite-04.LogFilterPatterns.sh
test/units/testsuite-35.sh
test/units/testsuite-55.sh
units/systemd-journal-upload.service.in

diff --git a/NEWS b/NEWS
index 6cf2a0d937a1d6a25d1d748522df5724b3beb8c8..7ab2c88db9a1e202b55663c8cf56fb3104e7d9a1 100644 (file)
--- a/NEWS
+++ b/NEWS
@@ -5764,7 +5764,8 @@ CHANGES WITH 246:
           started automatically as part of the desktop session.
 
         * "bootctl" gained a new verb "reboot-to-firmware" that may be used
-          to query and change the firmware's 'reboot into firmware' setup flag.
+          to query and change the firmware's 'Reboot Into Firmware Interface'
+          setup flag.
 
         * systemd-firstboot gained a new switch --kernel-command-line= that may
           be used to initialize the /etc/kernel/cmdline file of the image. It
diff --git a/TODO b/TODO
index 81fc1f3cae14c01baf4da34097a6c05d8f2792df..e72240a3d0a0ae74d5c85ea6294635126f7c0e52 100644 (file)
--- a/TODO
+++ b/TODO
@@ -133,6 +133,42 @@ Deprecations and removals:
 
 Features:
 
+* in sd-boot and sd-stub measure the SMBIOS vendor strings to some PCR (at
+  least some subset of them that look like systemd stuff), because apparently
+  some firmware does not, but systemd honours it. avoid duplicate measurement
+  by sd-boot and sd-stub by adding LoaderFeatures/StubFeatures flag for this,
+  so that sd-stub can avoid it if sd-boot already did it.
+
+* cryptsetup: a mechanism that allows signing a volume key with some key that
+  has to be present in the kernel keyring, or similar, to ensure that confext
+  DDIs can be encrypted against the local SRK but signed with the admin's key
+  and thus can authenticated locally before they are decrypted.
+
+* image policy should be extended to allow dictating *how* a disk is unlocked,
+  i.e. root=encrypted-tpm2+encrypted-fido2 would mean "root fs must be
+  encrypted and unlocked via fido2 or tpm2, but not otherwise"
+
+* systemd-repart: add support for formatting dm-crypt + dm-integrity file
+  systems.
+
+* homed: add small tool that exposes a homed home dir via nvme-over-tcp (just a
+  bunch of sysfs writes). Then, teach homed/pam_systemd_homed with a user name
+  such as lennart%nvmettcp_192.168.100.77_8787_nqn to log in from any linux
+  host with the same home dir. Similar maybe for nbd, iscsi? this should then
+  first ask for the local root pw, to authenticate that logging in like this is
+  ok, and would then be followed by another password prompt asking for the
+  user's own password. Also, do something similar for CIFS: if you log in via
+  lennart%cifs-someserver_someshare, then set up the homed dir for it
+  automatically. The PAM module should update the user name used for login to the
+  short version once it set up the user. Some care should be taken, so that the
+  long version can be still be resolved via NSS afterwards, to deal with PAM
+  clients that do not support PAM sessions where PAM_USER changes half-way.
+
+* redefine /var/lib/extensions/ as the dir one can place all three of sysext,
+  confext as well is multi-modal DDIs that qualify as both. Then introduce
+  /var/lib/sysexts/ which can be used to place only DDIs that shall be used as
+  sysext
+
 * in pid1: move out all cgroup state settings from Unit into a new object
   CGroupState or so which is allocated when we realize the unit into a cgroup,
   and then remains referenced by it. The new object should also carry an fd to
@@ -233,11 +269,8 @@ Features:
   2nd key derived from volume key of the user, with which to wrap all
   keys. maintain keys in kernel keyring if possible.
 
-* use sd-event ratelimit feature optionally for .socket units to "pause" overly
-  busy sockets temporarily. (as a less drastic version of the trigger
-  ratelimit)
-
-* similar, add the same for journal stream clients that log too much
+* use sd-event ratelimit feature optionally for journal stream clients that log
+  too much
 
 * systemd-mount should only consider modern file systems when mounting, similar
   to systemd-dissect
@@ -341,13 +374,6 @@ Features:
   intended for a different OS. Take inspiration from how confext/sysext are
   matched against OS.
 
-* use different sbat for sd-boot and sd-stub (so that people can revoke one
-  without the other)
-
-* in ukify merge sbat info from kernel (if it has any, upstream kernels so far
-  dont), of sd-stub and data supplied by user. Then measure sbat too in
-  sd-stub, explicitly.
-
 * figure out what to do about credentials sealed to PCRs in kexec + soft-reboot
   scenarios. Maybe insist sealing is done additionally against some keypair in
   the TPM to which access is updated on each boot, for the next, or so?
@@ -627,11 +653,6 @@ Features:
   of the activated configuration and the image that is being activated (in case
   verity is used, hash of the root hash).
 
-* whenever we measure something into a TPM PCR from userspace, write a record in
-  TCG's "Canonical Event Log" format to some file, so that we can reason about
-  how PCR values we manage came to
-  be. https://trustedcomputinggroup.org/resource/canonical-event-log-format/
-
 * bootspec: permit graceful "update" from type #2 to type #1. If both a type #1
   and a type #2 entry exist under otherwise the exact same name, then use the
   type #1 entry, and ignore the type #2 entry. This way, people can "upgrade"
@@ -677,9 +698,6 @@ Features:
   line. Benefit: works also on non-EFI systems, and can be requested on one
   boot, for the next.
 
-* figure out a sane way when building UKIs how to extract SBAT data from inner
-  kernel, extend it with component info, and add to outer kernel.
-
 * systemd-sysupdate: make transport pluggable, so people can plug casync or
   similar behind it, instead of http.
 
@@ -1086,8 +1104,6 @@ Features:
   images as OS payloads. i.e. have a generic OS image you can point to any
   payload you like, which is then downloaded, securely verified and run.
 
-* improve scope units to support creation by pidfd instead of by PID
-
 * deprecate cgroupsv1 further (print log message at boot)
 
 * systemd-dissect: add --cat switch for dumping files such as /etc/os-release
@@ -1527,9 +1543,6 @@ Features:
 
 * maybe extend .path units to expose fanotify() per-mount change events
 
-* When reloading configuration PID 1 should reset all its properties to the
-  original defaults before calling parse_config()
-
 * hibernate/s2h: if swap is on weird storage and refuse if so
 
 * cgroups: use inotify to get notified when somebody else modifies cgroups
@@ -1642,9 +1655,6 @@ Features:
 * In DynamicUser= mode: before selecting a UID, use disk quota APIs on relevant
   disks to see if the UID is already in use.
 
-* expose IO accounting data on the bus, show it in systemd-run --wait and log
-  about it in the resource log message
-
 * Add AddUser= setting to unit files, similar to DynamicUser=1 which however
   creates a static, persistent user rather than a dynamic, transient user. We
   can leverage code from sysusers.d for this.
@@ -1826,8 +1836,8 @@ Features:
   - when reloading configuration, apply new cgroup configuration
   - when recursively showing the cgroup hierarchy, optionally also show
     the hierarchies of child processes
-- add settings for cgroup.max.descendants and cgroup.max.depth,
-  maybe use them for user@.service
+  - add settings for cgroup.max.descendants and cgroup.max.depth,
+    maybe use them for user@.service
 
 * transient units:
   - add field to transient units that indicate whether systemd or somebody else saves/restores its settings, for integration with libvirt
@@ -1840,8 +1850,6 @@ Features:
 
 * rfkill,backlight: we probably should run the load tools inside of the udev rules so that the state is properly initialized by the time other software sees it
 
-* After coming back from hibernation reset hibernation swap partition using the /dev/snapshot ioctl APIs
-
 * If we try to find a unit via a dangling symlink, generate a clean
   error. Currently, we just ignore it and read the unit from the search
   path anyway.
@@ -2293,8 +2301,6 @@ Features:
   if the output file exists, so a repeated invocation will usually fail if
   something goes wrong on the way.
 
-* systemd-repart: drop pager mode on normal operation?
-
 * systemd-repart: by default generate minimized partition tables (i.e. tables
   that only cover the space actually used, excluding any free space at the
   end), in order to maximize dd'ability. Requires libfdisk work, see
index c777fa75de5cf12cfdb1766b60e35b2ffeba0f58..33486203a6553b130a1f2513c1389be4d669f65b 100644 (file)
@@ -201,3 +201,25 @@ can be found under various directories such as `factory/`, `modprobe.d/`, `netwo
 `tools/`, `coccinelle/`, `.github/`, `.semaphore/`, `.mkosi/` host various
 utilities and scripts that are used by maintainers and developers. They are not
 shipped or installed.
+
+# Service Manager Overview
+
+The Service Manager takes configuration in the form of unit files, credentials,
+kernel command line options and D-Bus commands, and based on those manages the
+system and spawns other processes. It runs in system mode as PID1, and in user
+mode with one instance per user session.
+
+When starting a unit requires forking a new process, configuration for the new
+process will be serialized and passed over to the new process, created via a
+posix_spawn() call. This is done in order to avoid excessive processing after
+a fork() but before an exec(), which is against glibc's best practices and can
+also result in a copy-on-write trap. The new process will start as the
+`systemd-executor` binary, which will deserialize the configuration and apply
+all the options (sandboxing, namespacing, cgroup, etc.) before exec'ing the
+configured executable.
+
+```
+ ┌──────┐posix_spawn() ┌───────────┐execve() ┌────────┐
+ │ PID1 ├─────────────►│sd-executor├────────►│program │
+ └──────┘  (memfd)     └───────────┘         └────────┘
+```
index ddcc2184ac456a91efaf30674d38acad0173a61c..889520ff6e057167462caaeff122fea423fba5dd 100644 (file)
     <title>Files</title>
     <variablelist>
       <varlistentry>
-        <term>
-          <filename>/usr/lib/kernel/install.d/*.install</filename>
-          <filename>/etc/kernel/install.d/*.install</filename>
-        </term>
-          <listitem>
-            <para>Drop-in files which are executed by kernel-install.</para>
+        <term><filename>/etc/kernel/install.d/*.install</filename></term>
+        <term><filename>/usr/lib/kernel/install.d/*.install</filename></term>
+        <listitem>
+          <para>Drop-in files which are executed by <command>kernel-install</command>.</para>
 
           <xi:include href="version-info.xml" xpointer="v198"/>
-          </listitem>
+        </listitem>
       </varlistentry>
+
       <varlistentry>
-        <term>
-          <filename>/usr/lib/kernel/cmdline</filename>
-          <filename>/etc/kernel/cmdline</filename>
-          <filename>/proc/cmdline</filename>
-        </term>
-          <listitem>
-            <para>Read by <filename>90-loaderentry.install</filename>. The content of the file
-            <filename>/etc/kernel/cmdline</filename> specifies the kernel command line to use. If that file
-            does not exist, <filename>/usr/lib/kernel/cmdline</filename> is used. If that also does not
-            exist, <filename>/proc/cmdline</filename> is used. <varname>$KERNEL_INSTALL_CONF_ROOT</varname>
-            may be used to override the path.</para>
+        <term><filename>/etc/kernel/cmdline</filename></term>
+        <term><filename>/usr/lib/kernel/cmdline</filename></term>
+        <term><filename>/proc/cmdline</filename></term>
+        <listitem>
+          <para>Specifies the kernel command line to use. The first of the files that is found will be used.
+          <varname>$KERNEL_INSTALL_CONF_ROOT</varname> may be used to override the search path; see below for
+          details.</para>
 
           <xi:include href="version-info.xml" xpointer="v198"/>
-          </listitem>
+        </listitem>
+      </varlistentry>
+
+      <varlistentry>
+        <term><filename>/etc/kernel/devicetree</filename></term>
+        <term><filename>/usr/lib/kernel/devicetree</filename></term>
+        <listitem>
+          <para>Specifies the partial path to the file containing the device tree blob to install with the
+          kernel and use at boot. The first of the files that is found will be used.
+          <varname>$KERNEL_INSTALL_CONF_ROOT</varname> may be used to override the search path; see below for
+          details.</para>
+
+          <para>The <filename>devicetree</filename> file contains a path, and this path specifies a location
+          relative to the kernel install tree. A set of locations is checked, including in particular
+          <filename>/usr/lib/modules/<replaceable>KERNEL_VERSION</replaceable>/dtb/</filename>, which is the
+          recommended location to place the dtb files under. For example, with
+          <literal>broadcom/bcm2711-rpi-4-b.dtb</literal> in the <filename>devicetree</filename> file, the
+          device tree blob for the Raspberry Pi 4 Model B would be installed, and the actual file would be
+          <filename index='false'>/usr/lib/modules/<replaceable>KERNEL_VERSION</replaceable>/dtb/broadcom/bcm2711-rpi-4-b.dtb</filename>.
+          </para>
+
+          <xi:include href="version-info.xml" xpointer="v255"/>
+        </listitem>
       </varlistentry>
+
       <varlistentry>
-        <term>
-          <filename>/etc/kernel/tries</filename>
-        </term>
-          <listitem>
-            <para>Read by <filename>90-loaderentry.install</filename> and
-            <filename>90-uki-copy.install</filename>. If this file exists a numeric value is read from it
-            and the naming of the generated entry file or UKI is slightly altered to include it as
-            <filename>$BOOT/loader/entries/<replaceable>ENTRY-TOKEN</replaceable>-<replaceable>KERNEL-VERSION</replaceable>+<replaceable>TRIES</replaceable>.conf</filename>
-            or
-            <filename>$BOOT/EFI/Linux/<replaceable>ENTRY-TOKEN</replaceable>-<replaceable>KERNEL-VERSION</replaceable>+<replaceable>TRIES</replaceable>.efi</filename>, respectively. This
-            is useful for boot loaders such as
-            <citerefentry><refentrytitle>systemd-boot</refentrytitle><manvolnum>7</manvolnum></citerefentry>
-            which implement boot attempt counting with a counter embedded in the entry file name.
-            <varname>$KERNEL_INSTALL_CONF_ROOT</varname> may be used to override the path.</para>
+        <term><filename>/etc/kernel/tries</filename></term>
+        <listitem>
+          <para>Read by <filename>90-loaderentry.install</filename> and
+          <filename>90-uki-copy.install</filename>. If this file exists, a numeric value is read from it and
+          the naming of the generated entry file or UKI is altered to include it as
+          <filename>$BOOT/loader/entries/<replaceable>ENTRY-TOKEN</replaceable>-<replaceable>KERNEL-VERSION</replaceable>+<replaceable>TRIES</replaceable>.conf</filename>
+          or
+          <filename>$BOOT/EFI/Linux/<replaceable>ENTRY-TOKEN</replaceable>-<replaceable>KERNEL-VERSION</replaceable>+<replaceable>TRIES</replaceable>.efi</filename>,
+          respectively. This is useful for boot loaders such as
+          <citerefentry><refentrytitle>systemd-boot</refentrytitle><manvolnum>7</manvolnum></citerefentry>
+          which implement boot attempt counting with a counter embedded in the entry file name.
+          <varname>$KERNEL_INSTALL_CONF_ROOT</varname> may be used to override the search path; see below for
+          details.</para>
 
           <xi:include href="version-info.xml" xpointer="v240"/>
-          </listitem>
+        </listitem>
       </varlistentry>
+
       <varlistentry>
-        <term>
-          <filename>/etc/kernel/entry-token</filename>
-        </term>
-          <listitem>
-            <para>If this file exists it is read and used as "entry token" for this system, i.e. is used for
-            naming Boot Loader Specification entries, see <varname>$KERNEL_INSTALL_ENTRY_TOKEN</varname>
-            above for details. <varname>$KERNEL_INSTALL_CONF_ROOT</varname> may be used to override the
-            path.</para>
+        <term><filename>/etc/kernel/entry-token</filename></term>
+        <listitem>
+          <para>If this file exists it is read and used as "entry token" for this system, i.e. is used for
+          naming Boot Loader Specification entries. See <varname>$KERNEL_INSTALL_ENTRY_TOKEN</varname> above
+          for details. <varname>$KERNEL_INSTALL_CONF_ROOT</varname> may be used to override the search path; see
+          below for details.</para>
 
-            <xi:include href="version-info.xml" xpointer="v251"/>
-          </listitem>
+          <xi:include href="version-info.xml" xpointer="v251"/>
+        </listitem>
       </varlistentry>
+
       <varlistentry>
         <term>
           <filename>/etc/machine-id</filename>
             <xi:include href="version-info.xml" xpointer="v198"/>
           </listitem>
       </varlistentry>
+
       <varlistentry>
-        <term>
-          <filename>/etc/os-release</filename>
-          <filename>/usr/lib/os-release</filename>
-        </term>
+        <term><filename>/etc/os-release</filename></term>
+        <term><filename>/usr/lib/os-release</filename></term>
         <listitem>
-            <para>Read by <filename>90-loaderentry.install</filename>.
-            If available, <varname>PRETTY_NAME=</varname> is read from these files and used as the title of the boot menu entry.
-            Otherwise, <literal>Linux <replaceable>KERNEL-VERSION</replaceable></literal> will be used.</para>
+            <para>Read by <filename>90-loaderentry.install</filename>. If available,
+            <varname>PRETTY_NAME=</varname> is read from these files and used as the title of the boot menu
+            entry. Otherwise, <literal>Linux <replaceable>KERNEL-VERSION</replaceable></literal> will be
+            used.</para>
 
-        <xi:include href="version-info.xml" xpointer="v198"/>
+            <xi:include href="version-info.xml" xpointer="v198"/>
           </listitem>
       </varlistentry>
       <varlistentry>
-        <term>
-          <filename>/usr/lib/kernel/install.conf</filename>
-          <filename>/etc/kernel/install.conf</filename>
-        </term>
-          <listitem>
-            <para>Configuration options for <command>kernel-install</command>, as a series of
-            <varname>KEY=</varname><replaceable>VALUE</replaceable> assignments, compatible with shell
-            syntax, following the same rules as described in
-            <citerefentry><refentrytitle>os-release</refentrytitle><manvolnum>5</manvolnum></citerefentry>.
-            <filename>/etc/kernel/install.conf</filename> will be read if present, and
-            <filename>/usr/lib/kernel/install.conf</filename> otherwise. This file is optional.
-            <varname>$KERNEL_INSTALL_CONF_ROOT</varname> may be used to override the path.
-            </para>
-
-            <para>Currently, the following keys are supported:
-            <varname>MACHINE_ID=</varname>,
-            <varname>BOOT_ROOT=</varname>,
-            <varname>layout=</varname>,
-            <varname>initrd_generator=</varname>,
-            <varname>uki_generator=</varname>.
-            See the Environment variables section above for details.</para>
+        <term><filename>/etc/kernel/install.conf</filename></term>
+        <term><filename>/usr/lib/kernel/install.conf</filename></term>
+        <listitem>
+          <para>Configuration file with options for <command>kernel-install</command>, as a series of
+          <varname>KEY=</varname><replaceable>VALUE</replaceable> assignments, compatible with shell syntax,
+          following the same rules as described in
+          <citerefentry><refentrytitle>os-release</refentrytitle><manvolnum>5</manvolnum></citerefentry>. The
+          first of the files that is found will be used. <varname>$KERNEL_INSTALL_CONF_ROOT</varname> may be
+          used to override the search path; see below for details.</para>
+
+          <para>Currently, the following keys are supported:
+          <varname>MACHINE_ID=</varname>,
+          <varname>BOOT_ROOT=</varname>,
+          <varname>layout=</varname>,
+          <varname>initrd_generator=</varname>,
+          <varname>uki_generator=</varname>.
+          See the Environment variables section above for details.</para>
 
-            <xi:include href="version-info.xml" xpointer="v250"/>
-          </listitem>
+          <xi:include href="version-info.xml" xpointer="v250"/>
+        </listitem>
       </varlistentry>
       <varlistentry>
-        <term>
-          <filename>/etc/kernel/uki.conf</filename>
-        </term>
-          <listitem>
-            <para>Ini-style configuration file for
-            <citerefentry><refentrytitle>ukify</refentrytitle><manvolnum>1</manvolnum></citerefentry> which
-            is only effective when <varname>$KERNEL_INSTALL_LAYOUT</varname> or <varname>layout=</varname> in
-            <filename>install.conf</filename> is set to <option>uki</option> and
-            <varname>$KERNEL_INSTALL_UKI_GENERATOR</varname> or <varname>uki_generator=</varname> in
-            <filename>install.conf</filename> is set to <option>ukify</option>.
-            <varname>$KERNEL_INSTALL_CONF_ROOT</varname> may be used to override the path.
-            </para>
-
-            <xi:include href="version-info.xml" xpointer="v255"/>
-          </listitem>
+        <term><filename>/etc/kernel/uki.conf</filename></term>
+        <listitem>
+          <para>Ini-style configuration file for
+          <citerefentry><refentrytitle>ukify</refentrytitle><manvolnum>1</manvolnum></citerefentry> which is
+          only effective when <varname>$KERNEL_INSTALL_LAYOUT</varname> or <varname>layout=</varname> in
+          <filename>install.conf</filename> is set to <option>uki</option> and
+          <varname>$KERNEL_INSTALL_UKI_GENERATOR</varname> or <varname>uki_generator=</varname> in
+          <filename>install.conf</filename> is set to <option>ukify</option>.
+          <varname>$KERNEL_INSTALL_CONF_ROOT</varname> may be used to override the search path; see below for
+          details.</para>
+
+          <xi:include href="version-info.xml" xpointer="v255"/>
+        </listitem>
       </varlistentry>
     </variablelist>
+
+    <para>For various cases listed above, if the <varname>$KERNEL_INSTALL_CONF_ROOT</varname> environment
+    variable is set, it will override the search path. The files will be loaded <emphasis>only</emphasis>
+    from the directory specified by the environment variable. When the variable is not set, the listed paths
+    are tried in turn, and the first file that exists is used.</para>
   </refsect1>
 
   <refsect1>
index 748276c9cfdcccaf1ce4f064a6ed334c2df88f4e..a94f09c1ad2ed2f20f2d17e0a62d7f8f097376c7 100644 (file)
       <varlistentry>
         <term>auto-firmware</term>
 
-        <listitem><para>A boolean controlling the presence of the "Reboot into firmware" entry
-        (enabled by default). If this is disabled, the firmware interface may still be reached
-        by using the <keycap>f</keycap> key.</para>
+        <listitem><para>A boolean controlling the presence of the <literal>Reboot Into Firmware
+        Interface</literal> entry (enabled by default). If this is disabled, the firmware interface may still
+        be reached by using the <keycap>f</keycap> key.</para>
 
         <xi:include href="version-info.xml" xpointer="v239"/></listitem>
       </varlistentry>
index b6efd8927c937ca1a17c0e7a5a93e32fd4491415..2b0ea9be34701c7d524f12957d585a9f7d15ec7a 100644 (file)
@@ -54,7 +54,8 @@
 
       <listitem><para>The EFI Shell binary, if installed.</para></listitem>
 
-      <listitem><para>A reboot into the UEFI firmware setup option, if supported by the firmware.</para></listitem>
+      <listitem><para>A <literal>Reboot Into Firmware Interface option</literal>, if supported by the UEFI
+      firmware.</para></listitem>
 
       <listitem><para>Secure Boot variables enrollment if the UEFI firmware is in setup-mode and files are provided
       on the ESP.</para></listitem>
index 52cce9bc308024e146247f1c411634dd3c799d84..79d56a5d0f1f7f9f96879bb70dc9530f5f166db2 100644 (file)
@@ -3900,6 +3900,14 @@ StandardInputData=V2XigLJyZSBubyBzdHJhbmdlcnMgdG8gbG92ZQpZb3Uga25vdyB0aGUgcnVsZX
                   <entry><literal>watchdog</literal></entry>
                   <entry>Watchdog keep-alive ping was enabled for the service, but the deadline was missed.</entry>
                 </row>
+                <row>
+                  <entry><literal>exec-condition</literal></entry>
+                  <entry>Service did not run because <varname>ExecCondition=</varname> failed.</entry>
+                </row>
+                <row>
+                  <entry><literal>oom-kill</literal></entry>
+                  <entry>A service process was terminated by the Out-Of-Memory (OOM) killer.</entry>
+                </row>
                 <row>
                   <entry><literal>start-limit-hit</literal></entry>
                   <entry>A start limit was defined for the unit and it was hit, causing the unit to fail to start. See <citerefentry><refentrytitle>systemd.unit</refentrytitle><manvolnum>5</manvolnum></citerefentry>'s <varname>StartLimitIntervalSec=</varname> and <varname>StartLimitBurst=</varname> for details.</entry>
index 33c559cddb5223a073ab3ad6c03a9c735c421b90..d939c29f716a5e227e4a165daaf0b16d5872a8e8 100644 (file)
@@ -2573,6 +2573,19 @@ NFTSet=prefix:netdev:filter:eth_ipv4_prefix</programlisting>
         </listitem>
       </varlistentry>
 
+      <varlistentry>
+        <term><varname>IPv6OnlyMode=</varname></term>
+        <listitem>
+          <para>When true, the DHCPv4 configuration will be delayed by the timespan provided by the DHCP
+          server and skip to configure dynamic IPv4 network connectivity if IPv6 connectivity is provided
+          within the timespan. See <ulink url="https://tools.ietf.org/html/rfc8925">RFC 8925</ulink>.
+          Defaults to true when <varname>IPv6AcceptRA=</varname> is enabled or DHCPv6 client is enabled
+          (i.e., <varname>DHCP=yes</varname>), and false otherwise.</para>
+
+          <xi:include href="version-info.xml" xpointer="v255"/>
+        </listitem>
+      </varlistentry>
+
       <varlistentry>
         <term><varname>FallbackLeaseLifetimeSec=</varname></term>
         <listitem>
@@ -3604,6 +3617,20 @@ ServerAddress=192.168.0.1/24</programlisting>
         </listitem>
       </varlistentry>
 
+      <varlistentry>
+        <term><varname>IPv6OnlyPreferredSec=</varname></term>
+
+        <listitem>
+          <para>Takes a timespan. Controls the
+          <ulink url="https://tools.ietf.org/html/rfc8925">RFC 8925</ulink> IPv6-Only Preferred option.
+          Specifies the DHCPv4 option to indicate that a host supports an IPv6-only mode and is willing to
+          forgo obtaining an IPv4 address if the network provides IPv6 connectivity. Defaults to unset, and
+          not send the option. The minimum allowed value is 300 seconds.</para>
+
+          <xi:include href="version-info.xml" xpointer="v255"/>
+        </listitem>
+      </varlistentry>
+
       <varlistentry>
         <term><varname>SendOption=</varname></term>
         <listitem>
index b01dd9cd73d320158561e3236cdefe69af902015..5b6b928276261379d918c38bfef21bfd6c45ee90 100644 (file)
@@ -225,6 +225,7 @@ conf.set_quoted('SYSCONF_DIR',                                sysconfdir)
 conf.set_quoted('SYSCTL_DIR',                                 sysctldir)
 conf.set_quoted('SYSTEMCTL_BINARY_PATH',                      bindir / 'systemctl')
 conf.set_quoted('SYSTEMD_BINARY_PATH',                        libexecdir / 'systemd')
+conf.set_quoted('SYSTEMD_EXECUTOR_BINARY_PATH',               libexecdir / 'systemd-executor')
 conf.set_quoted('SYSTEMD_CATALOG_DIR',                        catalogdir)
 conf.set_quoted('SYSTEMD_CGROUPS_AGENT_PATH',                 libexecdir / 'systemd-cgroups-agent')
 conf.set_quoted('SYSTEMD_CRYPTSETUP_PATH',                    bindir / 'systemd-cryptsetup')
@@ -483,7 +484,7 @@ if cxx_cmd != ''
         add_project_arguments(cxx.get_supported_arguments(basic_disabled_warnings), language : 'cpp')
 endif
 
-cpp = ' '.join(cc.cmd_array()) + ' -E'
+cpp = ' '.join(cc.cmd_array() + get_option('c_args')) + ' -E'
 
 has_wstringop_truncation = cc.has_argument('-Wstringop-truncation')
 
index 37656e4690b4d26a92723234521dff29fdc7d3be..55c8d538bff2aa1802336229b972961acfe7b3bb 100644 (file)
--- a/po/fr.po
+++ b/po/fr.po
@@ -11,7 +11,7 @@ msgid ""
 msgstr ""
 "Report-Msgid-Bugs-To: \n"
 "POT-Creation-Date: 2023-07-14 10:32+0100\n"
-"PO-Revision-Date: 2023-07-31 22:21+0000\n"
+"PO-Revision-Date: 2023-10-12 16:36+0000\n"
 "Last-Translator: Pierre GRASSER <pierre.grasser@proton.me>\n"
 "Language-Team: French <https://translate.fedoraproject.org/projects/systemd/"
 "master/fr/>\n"
@@ -20,7 +20,7 @@ msgstr ""
 "Content-Type: text/plain; charset=UTF-8\n"
 "Content-Transfer-Encoding: 8bit\n"
 "Plural-Forms: nplurals=2; plural=n > 1;\n"
-"X-Generator: Weblate 4.18.2\n"
+"X-Generator: Weblate 5.0.2\n"
 
 #: src/core/org.freedesktop.systemd1.policy.in:22
 msgid "Send passphrase back to system"
index 625816d9cf1de2960f68918681d7115367323d35..80ea7e7ffa80bfdf6379af65e33e714feef1caad 100644 (file)
@@ -36,7 +36,7 @@ typedef enum CGroupController {
         CGROUP_CONTROLLER_BPF_SOCKET_BIND,
         CGROUP_CONTROLLER_BPF_RESTRICT_NETWORK_INTERFACES,
         /* The BPF hook implementing RestrictFileSystems= is not defined here.
-         * It's applied as late as possible in exec_child() so we don't block
+         * It's applied as late as possible in exec_invoke() so we don't block
          * our own unit setup code. */
 
         _CGROUP_CONTROLLER_MAX,
index 44772f778dedbbb47809206d2a4425df5ec63bd5..d3bf73385fbcf64ccc35263a105c43b0d2ddc476 100644 (file)
@@ -1074,3 +1074,22 @@ int getenv_steal_erase(const char *name, char **ret) {
 
         return 1;
 }
+
+int set_full_environment(char **env) {
+        int r;
+
+        clearenv();
+
+        STRV_FOREACH(e, env) {
+                _cleanup_free_ char *k = NULL, *v = NULL;
+
+                r = split_pair(*e, "=", &k, &v);
+                if (r < 0)
+                        return r;
+
+                if (setenv(k, v, /* overwrite= */ true) < 0)
+                        return -errno;
+        }
+
+        return 0;
+}
index ec3ac199efe22081d8788b9f3539dd9c48d035fc..f7fb1e90823d9735c581325e30166274d95ce583 100644 (file)
@@ -77,3 +77,5 @@ int setenv_systemd_exec_pid(bool update_only);
 int getenv_path_list(const char *name, char ***ret_paths);
 
 int getenv_steal_erase(const char *name, char **ret);
+
+int set_full_environment(char **env);
index 7f650d0719e77cf2ec4a1959b5c33a2011f3e250..dcd1ca96fd48c58e409d7daaec8150fb305f0060 100644 (file)
 #define _function_no_sanitize_float_cast_overflow_
 #endif
 
-/* Temporarily disable some warnings */
-#define DISABLE_WARNING_DEPRECATED_DECLARATIONS                         \
-        _Pragma("GCC diagnostic push");                                 \
-        _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
-
-#define DISABLE_WARNING_FORMAT_NONLITERAL                               \
-        _Pragma("GCC diagnostic push");                                 \
-        _Pragma("GCC diagnostic ignored \"-Wformat-nonliteral\"")
-
-#define DISABLE_WARNING_MISSING_PROTOTYPES                              \
-        _Pragma("GCC diagnostic push");                                 \
-        _Pragma("GCC diagnostic ignored \"-Wmissing-prototypes\"")
-
-#define DISABLE_WARNING_NONNULL                                         \
-        _Pragma("GCC diagnostic push");                                 \
-        _Pragma("GCC diagnostic ignored \"-Wnonnull\"")
-
-#define DISABLE_WARNING_SHADOW                                          \
-        _Pragma("GCC diagnostic push");                                 \
-        _Pragma("GCC diagnostic ignored \"-Wshadow\"")
-
-#define DISABLE_WARNING_INCOMPATIBLE_POINTER_TYPES                      \
-        _Pragma("GCC diagnostic push");                                 \
-        _Pragma("GCC diagnostic ignored \"-Wincompatible-pointer-types\"")
-
 #if HAVE_WSTRINGOP_TRUNCATION
 #  define DISABLE_WARNING_STRINGOP_TRUNCATION                           \
         _Pragma("GCC diagnostic push");                                 \
         _Pragma("GCC diagnostic push")
 #endif
 
-#define DISABLE_WARNING_TYPE_LIMITS                                     \
-        _Pragma("GCC diagnostic push");                                 \
-        _Pragma("GCC diagnostic ignored \"-Wtype-limits\"")
-
-#define DISABLE_WARNING_ADDRESS                                         \
-        _Pragma("GCC diagnostic push");                                 \
-        _Pragma("GCC diagnostic ignored \"-Waddress\"")
-
-#define REENABLE_WARNING                                                \
-        _Pragma("GCC diagnostic pop")
-
-/* automake test harness */
+/* test harness */
 #define EXIT_TEST_SKIP 77
 
 /* builtins */
@@ -310,42 +274,6 @@ static inline int __coverity_check_and_return__(int condition) {
 #define FOREACH_ARRAY(i, array, num)                                    \
         _FOREACH_ARRAY(i, array, num, UNIQ_T(m, UNIQ), UNIQ_T(end, UNIQ))
 
-/* A wrapper for 'func' to return void.
- * Only useful when a void-returning function is required by some API. */
-#define DEFINE_TRIVIAL_DESTRUCTOR(name, type, func)             \
-        static inline void name(type *p) {                      \
-                func(p);                                        \
-        }
-
-/* When func() returns the void value (NULL, -1, …) of the appropriate type */
-#define DEFINE_TRIVIAL_CLEANUP_FUNC(type, func)                 \
-        static inline void func##p(type *p) {                   \
-                if (*p)                                         \
-                        *p = func(*p);                          \
-        }
-
-/* When func() doesn't return the appropriate type, set variable to empty afterwards.
- * The func() may be provided by a dynamically loaded shared library, hence add an assertion. */
-#define DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(type, func, empty)     \
-        static inline void func##p(type *p) {                   \
-                if (*p != (empty)) {                            \
-                        DISABLE_WARNING_ADDRESS;                \
-                        assert(func);                           \
-                        REENABLE_WARNING;                       \
-                        func(*p);                               \
-                        *p = (empty);                           \
-                }                                               \
-        }
-
-/* When func() doesn't return the appropriate type, and is also a macro, set variable to empty afterwards. */
-#define DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_MACRO(type, func, empty)       \
-        static inline void func##p(type *p) {                           \
-                if (*p != (empty)) {                                    \
-                        func(*p);                                       \
-                        *p = (empty);                                   \
-                }                                                       \
-        }
-
 #define _DEFINE_TRIVIAL_REF_FUNC(type, name, scope)             \
         scope type *name##_ref(type *p) {                       \
                 if (!p)                                         \
index 4928379bd757a8ffbc045f4d46a9aef2b8027f37..d0ffb2d61410a71b0225351b2ce855f16ff06cef 100644 (file)
@@ -5,6 +5,7 @@
 #include <limits.h>
 #include <linux/oom.h>
 #include <pthread.h>
+#include <spawn.h>
 #include <stdbool.h>
 #include <stdio.h>
 #include <stdlib.h>
@@ -1732,6 +1733,51 @@ int make_reaper_process(bool b) {
         return 0;
 }
 
+int posix_spawn_wrapper(const char *path, char *const *argv, char *const *envp, pid_t *ret_pid) {
+        posix_spawnattr_t attr;
+        sigset_t mask;
+        pid_t pid;
+        int r;
+
+        /* Forks and invokes 'path' with 'argv' and 'envp' using CLONE_VM and CLONE_VFORK, which means the
+         * caller will be blocked until the child either exits or exec's. The memory of the child will be
+         * fully shared with the memory of the parent, so that there are no copy-on-write or memory.max
+         * issues. */
+
+        assert(path);
+        assert(argv);
+        assert(ret_pid);
+
+        assert_se(sigfillset(&mask) >= 0);
+
+        r = posix_spawnattr_init(&attr);
+        if (r != 0)
+                return -r; /* These functions return a positive errno on failure */
+        r = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGMASK);
+        if (r != 0)
+                goto fail;
+        r = posix_spawnattr_setflags(&attr, POSIX_SPAWN_SETSIGDEF); /* Set all signals to SIG_DFL */
+        if (r != 0)
+                goto fail;
+        r = posix_spawnattr_setsigmask(&attr, &mask);
+        if (r != 0)
+                goto fail;
+
+        r = posix_spawn(&pid, path, NULL, &attr, argv, envp);
+        if (r != 0)
+                goto fail;
+
+        *ret_pid = pid;
+
+        posix_spawnattr_destroy(&attr);
+        return 0;
+
+fail:
+        assert(r > 0);
+        posix_spawnattr_destroy(&attr);
+        return -r;
+}
+
 static const char *const sigchld_code_table[] = {
         [CLD_EXITED] = "exited",
         [CLD_KILLED] = "killed",
index 8f87fdc2ae74f578fe129046668d7a0e8f925f77..0d50e797e536640fadff9b39e6933565c5fae9d4 100644 (file)
@@ -210,3 +210,5 @@ int get_process_threads(pid_t pid);
 
 int is_reaper_process(void);
 int make_reaper_process(bool b);
+
+int posix_spawn_wrapper(const char *path, char *const *argv, char *const *envp, pid_t *ret_pid);
index c28ec01975307d84f19adb8b3beeb7e8fcd35389..2c2d0bf735a174118638d96a1e2b127a9518e891 100644 (file)
@@ -72,10 +72,10 @@ typedef struct {
         char16_t *path;
         char16_t *current_name;
         char16_t *next_name;
-} ConfigEntry;
+} BootEntry;
 
 typedef struct {
-        ConfigEntry **entries;
+        BootEntry **entries;
         size_t n_entries;
         size_t idx_default;
         size_t idx_default_efivar;
@@ -142,6 +142,8 @@ static bool line_edit(char16_t **line_in, size_t x_max, size_t y_pos) {
         _cleanup_free_ char16_t *line = NULL, *print = NULL;
         size_t size, len, first = 0, cursor = 0, clear = 0;
 
+        /* Edit the line and return true if it should be executed, false if not. */
+
         assert(line_in);
 
         len = strlen16(*line_in);
@@ -379,7 +381,7 @@ static size_t entry_lookup_key(Config *config, size_t start, char16_t key) {
                 return i-1;
         }
 
-        /* find matching key in config entries */
+        /* find matching key in boot entries */
         for (size_t i = start; i < config->n_entries; i++)
                 if (config->entries[i]->key == key)
                         return i;
@@ -391,27 +393,29 @@ static size_t entry_lookup_key(Config *config, size_t start, char16_t key) {
         return IDX_INVALID;
 }
 
-static char16_t *update_timeout_efivar(uint32_t *t, bool inc) {
-        assert(t);
+static char16_t* update_timeout_efivar(Config *config, bool inc) {
+        assert(config);
 
-        switch (*t) {
+        switch (config->timeout_sec) {
         case TIMEOUT_MAX:
-                *t = inc ? TIMEOUT_MAX : (*t - 1);
+                config->timeout_sec = inc ? TIMEOUT_MAX : config->timeout_sec - 1;
                 break;
         case TIMEOUT_UNSET:
-                *t = inc ? TIMEOUT_MENU_FORCE : TIMEOUT_UNSET;
+                config->timeout_sec = inc ? TIMEOUT_MENU_FORCE : TIMEOUT_UNSET;
                 break;
         case TIMEOUT_MENU_FORCE:
-                *t = inc ? TIMEOUT_MENU_HIDDEN : TIMEOUT_UNSET;
+                config->timeout_sec = inc ? TIMEOUT_MENU_HIDDEN : TIMEOUT_MENU_FORCE;
                 break;
         case TIMEOUT_MENU_HIDDEN:
-                *t = inc ? TIMEOUT_MIN : TIMEOUT_MENU_FORCE;
+                config->timeout_sec = inc ? TIMEOUT_MIN : TIMEOUT_MENU_FORCE;
                 break;
         default:
-                *t += inc ? 1 : -1;
+                config->timeout_sec = config->timeout_sec + (inc ? 1 : -1);
         }
 
-        switch (*t) {
+        config->timeout_sec_efivar = config->timeout_sec;
+
+        switch (config->timeout_sec) {
         case TIMEOUT_UNSET:
                 return xstrdup16(u"Menu timeout defined by configuration file.");
         case TIMEOUT_MENU_FORCE:
@@ -419,7 +423,7 @@ static char16_t *update_timeout_efivar(uint32_t *t, bool inc) {
         case TIMEOUT_MENU_HIDDEN:
                 return xstrdup16(u"Menu disabled. Hold down key at bootup to show menu.");
         default:
-                return xasprintf("Menu timeout set to %u s.", *t);
+                return xasprintf("Menu timeout set to %u s.", config->timeout_sec_efivar);
         }
 }
 
@@ -443,6 +447,19 @@ static bool ps_continue(void) {
                         !IN_SET(key, KEYPRESS(0, SCAN_ESC, 0), KEYPRESS(0, 0, 'q'), KEYPRESS(0, 0, 'Q'));
 }
 
+static void print_timeout_status(const char *label, uint32_t t) {
+        switch (t) {
+        case TIMEOUT_UNSET:
+                return;
+        case TIMEOUT_MENU_FORCE:
+                return (void) printf("%s: menu-force\n", label);
+        case TIMEOUT_MENU_HIDDEN:
+                return (void) printf("%s: menu-hidden\n", label);
+        default:
+                return (void) printf("%s: %u s\n", label, t);
+        }
+}
+
 static void print_status(Config *config, char16_t *loaded_image_path) {
         size_t x_max, y_max;
         uint32_t screen_width = 0, screen_height = 0;
@@ -480,31 +497,8 @@ static void print_status(Config *config, char16_t *loaded_image_path) {
         if (!ps_continue())
                 return;
 
-        switch (config->timeout_sec_config) {
-        case TIMEOUT_UNSET:
-                break;
-        case TIMEOUT_MENU_FORCE:
-                printf("      timeout (config): menu-force\n");
-                break;
-        case TIMEOUT_MENU_HIDDEN:
-                printf("      timeout (config): menu-hidden\n");
-                break;
-        default:
-                printf("      timeout (config): %u s\n", config->timeout_sec_config);
-        }
-
-        switch (config->timeout_sec_efivar) {
-        case TIMEOUT_UNSET:
-                break;
-        case TIMEOUT_MENU_FORCE:
-                printf("     timeout (EFI var): menu-force\n");
-                break;
-        case TIMEOUT_MENU_HIDDEN:
-                printf("     timeout (EFI var): menu-hidden\n");
-                break;
-        default:
-                printf("     timeout (EFI var): %u s\n", config->timeout_sec_efivar);
-        }
+        print_timeout_status("      timeout (config)", config->timeout_sec_config);
+        print_timeout_status("     timeout (EFI var)", config->timeout_sec_efivar);
 
         if (config->entry_default_config)
                 printf("      default (config): %ls\n", config->entry_default_config);
@@ -562,7 +556,7 @@ static void print_status(Config *config, char16_t *loaded_image_path) {
                 return;
 
         for (size_t i = 0; i < config->n_entries; i++) {
-                ConfigEntry *entry = config->entries[i];
+                BootEntry *entry = config->entries[i];
                 EFI_DEVICE_PATH *dp = NULL;
                 _cleanup_free_ char16_t *dp_str = NULL;
 
@@ -571,7 +565,7 @@ static void print_status(Config *config, char16_t *loaded_image_path) {
                                     EFI_SUCCESS)
                         (void) device_path_to_str(dp, &dp_str);
 
-                printf("  config entry: %zu/%zu\n", i + 1, config->n_entries);
+                printf("    boot entry: %zu/%zu\n", i + 1, config->n_entries);
                 printf("            id: %ls\n", entry->id);
                 if (entry->title)
                         printf("         title: %ls\n", entry->title);
@@ -607,37 +601,42 @@ static void print_status(Config *config, char16_t *loaded_image_path) {
         }
 }
 
-static EFI_STATUS reboot_into_firmware(void) {
+static EFI_STATUS set_reboot_into_firmware(void) {
         uint64_t osind = 0;
         EFI_STATUS err;
 
-        if (!FLAGS_SET(get_os_indications_supported(), EFI_OS_INDICATIONS_BOOT_TO_FW_UI))
-                return log_error_status(EFI_UNSUPPORTED, "Reboot to firmware interface not supported.");
-
         (void) efivar_get_uint64_le(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"OsIndications", &osind);
         osind |= EFI_OS_INDICATIONS_BOOT_TO_FW_UI;
 
         err = efivar_set_uint64_le(MAKE_GUID_PTR(EFI_GLOBAL_VARIABLE), u"OsIndications", osind, EFI_VARIABLE_NON_VOLATILE);
         if (err != EFI_SUCCESS)
-                return log_error_status(err, "Error setting OsIndications: %m");
-
-        RT->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
-        assert_not_reached();
+                log_error_status(err, "Error setting OsIndications: %m");
+        return err;
 }
 
-static EFI_STATUS poweroff_system(void) {
+_noreturn_ static EFI_STATUS poweroff_system(void) {
         RT->ResetSystem(EfiResetShutdown, EFI_SUCCESS, 0, NULL);
         assert_not_reached();
 }
 
-static EFI_STATUS reboot_system(void) {
+_noreturn_ static EFI_STATUS reboot_system(void) {
         RT->ResetSystem(EfiResetCold, EFI_SUCCESS, 0, NULL);
         assert_not_reached();
 }
 
+static EFI_STATUS reboot_into_firmware(void) {
+        EFI_STATUS err;
+
+        err = set_reboot_into_firmware();
+        if (err != EFI_SUCCESS)
+                return err;
+
+        return reboot_system();
+}
+
 static bool menu_run(
                 Config *config,
-                ConfigEntry **chosen_entry,
+                BootEntry **chosen_entry,
                 char16_t *loaded_image_path) {
 
         assert(config);
@@ -654,10 +653,18 @@ static bool menu_run(
         _cleanup_free_ char16_t *clearline = NULL, *separator = NULL, *status = NULL;
         uint32_t timeout_efivar_saved = config->timeout_sec_efivar;
         uint32_t timeout_remain = config->timeout_sec == TIMEOUT_MENU_FORCE ? 0 : config->timeout_sec;
-        bool exit = false, run = true, firmware_setup = false;
         int64_t console_mode_initial = ST->ConOut->Mode->Mode, console_mode_efivar_saved = config->console_mode_efivar;
         size_t default_efivar_saved = config->idx_default_efivar;
 
+        enum {
+                ACTION_CONTINUE,        /* Continue with loop over user input */
+                ACTION_FIRMWARE_SETUP,  /* Ask for confirmation and reboot into firmware setup */
+                ACTION_POWEROFF,        /* Power off the machine */
+                ACTION_REBOOT,          /* Reboot the machine */
+                ACTION_RUN,             /* Execute a boot entry */
+                ACTION_QUIT,            /* Return to the firmware */
+        } action = ACTION_CONTINUE;
+
         graphics_mode(false);
         ST->ConIn->Reset(ST->ConIn, false);
         ST->ConOut->EnableCursor(ST->ConOut, false);
@@ -673,7 +680,7 @@ static bool menu_run(
         }
 
         size_t line_width = 0, entry_padding = 3;
-        while (!exit) {
+        while (IN_SET(action, ACTION_CONTINUE, ACTION_FIRMWARE_SETUP)) {
                 uint64_t key;
 
                 if (new_mode) {
@@ -820,7 +827,7 @@ static bool menu_run(
                         assert(timeout_remain > 0);
                         timeout_remain--;
                         if (timeout_remain == 0) {
-                                exit = true;
+                                action = ACTION_RUN;
                                 break;
                         }
 
@@ -828,7 +835,7 @@ static bool menu_run(
                         continue;
                 }
                 if (err != EFI_SUCCESS) {
-                        exit = true;
+                        action = ACTION_RUN;
                         break;
                 }
 
@@ -839,10 +846,13 @@ static bool menu_run(
 
                 idx_highlight_prev = idx_highlight;
 
-                if (firmware_setup) {
-                        firmware_setup = false;
-                        if (IN_SET(key, KEYPRESS(0, 0, '\r'), KEYPRESS(0, 0, '\n')))
-                                (void) reboot_into_firmware();
+                if (action == ACTION_FIRMWARE_SETUP) {
+                        if (IN_SET(key, KEYPRESS(0, 0, '\r'), KEYPRESS(0, 0, '\n')) &&
+                            set_reboot_into_firmware() == EFI_SUCCESS)
+                                break;
+
+                        /* Any key other than newline or a failed attempt cancel the request. */
+                        action = ACTION_CONTINUE;
                         continue;
                 }
 
@@ -895,7 +905,7 @@ static bool menu_run(
                 case KEYPRESS(0, SCAN_F3, 0): /* EZpad Mini 4s firmware sends malformed events */
                 case KEYPRESS(0, SCAN_F3, '\r'): /* Teclast X98+ II firmware sends malformed events */
                 case KEYPRESS(0, SCAN_RIGHT, 0):
-                        exit = true;
+                        action = ACTION_RUN;
                         break;
 
                 case KEYPRESS(0, SCAN_F1, 0):
@@ -909,8 +919,7 @@ static bool menu_run(
                         break;
 
                 case KEYPRESS(0, 0, 'Q'):
-                        exit = true;
-                        run = false;
+                        action = ACTION_QUIT;
                         break;
 
                 case KEYPRESS(0, 0, 'd'):
@@ -931,12 +940,12 @@ static bool menu_run(
 
                 case KEYPRESS(0, 0, '-'):
                 case KEYPRESS(0, 0, 'T'):
-                        status = update_timeout_efivar(&config->timeout_sec_efivar, false);
+                        status = update_timeout_efivar(config, false);
                         break;
 
                 case KEYPRESS(0, 0, '+'):
                 case KEYPRESS(0, 0, 't'):
-                        status = update_timeout_efivar(&config->timeout_sec_efivar, true);
+                        status = update_timeout_efivar(config, true);
                         break;
 
                 case KEYPRESS(0, 0, 'e'):
@@ -964,7 +973,8 @@ static bool menu_run(
                          * Since we cannot paint the last character of the edit line, we simply start
                          * at x-offset 1 for symmetry. */
                         print_at(1, y_status, COLOR_EDIT, clearline + 2);
-                        exit = line_edit(&config->entries[idx_highlight]->options, x_max - 2, y_status);
+                        if (line_edit(&config->entries[idx_highlight]->options, x_max - 2, y_status))
+                                action = ACTION_RUN;
                         print_at(1, y_status, COLOR_NORMAL, clearline + 2);
 
                         /* The options string was now edited, hence we have to pass it to the invoked
@@ -1030,19 +1040,20 @@ static bool menu_run(
                 case KEYPRESS(0, SCAN_DELETE, 0): /* Same as F2. */
                 case KEYPRESS(0, SCAN_ESC, 0):    /* HP. */
                         if (FLAGS_SET(get_os_indications_supported(), EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
-                                firmware_setup = true;
+                                action = ACTION_FIRMWARE_SETUP;
                                 /* Let's make sure the user really wants to do this. */
                                 status = xstrdup16(u"Press Enter to reboot into firmware interface.");
                         } else
                                 status = xstrdup16(u"Reboot into firmware interface not supported.");
                         break;
 
-                case KEYPRESS(0, 0, 'O'): /* Only uppercase, so that it can't be hit so easily fat-fingered, but still works safely over serial */
-                        (void) poweroff_system();
+                case KEYPRESS(0, 0, 'O'): /* Only uppercase, so that it can't be hit so easily fat-fingered,
+                                           * but still works safely over serial. */
+                        action = ACTION_POWEROFF;
                         break;
 
                 case KEYPRESS(0, 0, 'B'): /* ditto */
-                        (void) reboot_system();
+                        action = ACTION_REBOOT;
                         break;
 
                 default:
@@ -1068,8 +1079,6 @@ static bool menu_run(
                         highlight = true;
         }
 
-        *chosen_entry = config->entries[idx_highlight];
-
         /* Update EFI vars after we left the menu to reduce NVRAM writes. */
 
         if (default_efivar_saved != config->idx_default_efivar)
@@ -1100,11 +1109,25 @@ static bool menu_run(
                 }
         }
 
+        switch (action) {
+        case ACTION_CONTINUE:
+                assert_not_reached();
+        case ACTION_POWEROFF:
+                poweroff_system();
+        case ACTION_REBOOT:
+        case ACTION_FIRMWARE_SETUP:
+                reboot_system();
+        case ACTION_RUN:
+        case ACTION_QUIT:
+                break;
+        }
+
+        *chosen_entry = config->entries[idx_highlight];
         clear_screen(COLOR_NORMAL);
-        return run;
+        return action == ACTION_RUN;
 }
 
-static void config_add_entry(Config *config, ConfigEntry *entry) {
+static void config_add_entry(Config *config, BootEntry *entry) {
         assert(config);
         assert(entry);
 
@@ -1120,9 +1143,9 @@ static void config_add_entry(Config *config, ConfigEntry *entry) {
         config->entries[config->n_entries++] = entry;
 }
 
-static void config_entry_free(ConfigEntry *entry) {
+static BootEntry* boot_entry_free(BootEntry *entry) {
         if (!entry)
-                return;
+                return NULL;
 
         free(entry->id);
         free(entry->title_show);
@@ -1137,13 +1160,12 @@ static void config_entry_free(ConfigEntry *entry) {
         free(entry->path);
         free(entry->current_name);
         free(entry->next_name);
-        free(entry);
-}
 
-static void config_entry_freep(ConfigEntry **entry) {
-        config_entry_free(*entry);
+        return mfree(entry);
 }
 
+DEFINE_TRIVIAL_CLEANUP_FUNC(BootEntry *, boot_entry_free);
+
 static char *line_get_key_value(
                 char *content,
                 const char *sep,
@@ -1227,7 +1249,7 @@ static void config_defaults_load_from_file(Config *config, char *content) {
         assert(config);
         assert(content);
 
-        while ((line = line_get_key_value(content, " \t", &pos, &key, &value))) {
+        while ((line = line_get_key_value(content, " \t", &pos, &key, &value)))
                 if (streq8(key, "timeout")) {
                         if (streq8( value, "menu-force"))
                                 config->timeout_sec_config = TIMEOUT_MENU_FORCE;
@@ -1243,69 +1265,52 @@ static void config_defaults_load_from_file(Config *config, char *content) {
                                 config->timeout_sec_config = u;
                         }
                         config->timeout_sec = config->timeout_sec_config;
-                        continue;
-                }
 
-                if (streq8(key, "default")) {
+                } else if (streq8(key, "default")) {
                         if (value[0] == '@' && !strcaseeq8(value, "@saved")) {
                                 log_error("Unsupported special entry identifier, ignoring: %s", value);
                                 continue;
                         }
                         free(config->entry_default_config);
                         config->entry_default_config = xstr8_to_16(value);
-                        continue;
-                }
 
-                if (streq8(key, "editor")) {
+                } else if (streq8(key, "editor")) {
                         err = parse_boolean(value, &config->editor);
                         if (err != EFI_SUCCESS)
                                 log_error("Error parsing 'editor' config option, ignoring: %s", value);
-                        continue;
-                }
 
-                if (streq8(key, "auto-entries")) {
+                } else if (streq8(key, "auto-entries")) {
                         err = parse_boolean(value, &config->auto_entries);
                         if (err != EFI_SUCCESS)
                                 log_error("Error parsing 'auto-entries' config option, ignoring: %s", value);
-                        continue;
-                }
 
-                if (streq8(key, "auto-firmware")) {
+                } else if (streq8(key, "auto-firmware")) {
                         err = parse_boolean(value, &config->auto_firmware);
                         if (err != EFI_SUCCESS)
                                 log_error("Error parsing 'auto-firmware' config option, ignoring: %s", value);
-                        continue;
-                }
 
-                if (streq8(key, "auto-poweroff")) {
+                } else if (streq8(key, "auto-poweroff")) {
                         err = parse_boolean(value, &config->auto_poweroff);
                         if (err != EFI_SUCCESS)
                                 log_error("Error parsing 'auto-poweroff' config option, ignoring: %s", value);
-                        continue;
-                }
 
-                if (streq8(key, "auto-reboot")) {
+                } else if (streq8(key, "auto-reboot")) {
                         err = parse_boolean(value, &config->auto_reboot);
                         if (err != EFI_SUCCESS)
                                 log_error("Error parsing 'auto-reboot' config option, ignoring: %s", value);
-                        continue;
-                }
 
-                if (streq8(key, "beep")) {
+                } else if (streq8(key, "beep")) {
                         err = parse_boolean(value, &config->beep);
                         if (err != EFI_SUCCESS)
                                 log_error("Error parsing 'beep' config option, ignoring: %s", value);
-                        continue;
-                }
 
-                if (streq8(key, "reboot-for-bitlocker")) {
+                } else if (streq8(key, "reboot-for-bitlocker")) {
                         err = parse_boolean(value, &config->reboot_for_bitlocker);
                         if (err != EFI_SUCCESS)
                                 log_error("Error parsing 'reboot-for-bitlocker' config option, ignoring: %s",
                                           value);
-                }
 
-                if (streq8(key, "secure-boot-enroll")) {
+                } else if (streq8(key, "secure-boot-enroll")) {
                         if (streq8(value, "manual"))
                                 config->secure_boot_enroll = ENROLL_MANUAL;
                         else if (streq8(value, "force"))
@@ -1317,10 +1322,8 @@ static void config_defaults_load_from_file(Config *config, char *content) {
                         else
                                 log_error("Error parsing 'secure-boot-enroll' config option, ignoring: %s",
                                           value);
-                        continue;
-                }
 
-                if (streq8(key, "console-mode")) {
+                } else if (streq8(key, "console-mode")) {
                         if (streq8(value, "auto"))
                                 config->console_mode = CONSOLE_MODE_AUTO;
                         else if (streq8(value, "max"))
@@ -1336,13 +1339,11 @@ static void config_defaults_load_from_file(Config *config, char *content) {
                                 }
                                 config->console_mode = u;
                         }
-                        continue;
                 }
-        }
 }
 
-static void config_entry_parse_tries(
-                ConfigEntry *entry,
+static void boot_entry_parse_tries(
+                BootEntry *entry,
                 const char16_t *path,
                 const char16_t *file,
                 const char16_t *suffix) {
@@ -1405,7 +1406,7 @@ static void config_entry_parse_tries(
                         suffix);
 }
 
-static EFI_STATUS config_entry_bump_counters(ConfigEntry *entry) {
+static EFI_STATUS boot_entry_bump_counters(BootEntry *entry) {
         _cleanup_free_ char16_t* old_path = NULL, *new_path = NULL;
         _cleanup_(file_closep) EFI_FILE *handle = NULL;
         _cleanup_free_ EFI_FILE_INFO *file_info = NULL;
@@ -1461,7 +1462,7 @@ static EFI_STATUS config_entry_bump_counters(ConfigEntry *entry) {
         return EFI_SUCCESS;
 }
 
-static void config_entry_add_type1(
+static void boot_entry_add_type1(
                 Config *config,
                 EFI_HANDLE *device,
                 EFI_FILE *root_dir,
@@ -1470,7 +1471,7 @@ static void config_entry_add_type1(
                 char *content,
                 const char16_t *loaded_image_path) {
 
-        _cleanup_(config_entry_freep) ConfigEntry *entry = NULL;
+        _cleanup_(boot_entry_freep) BootEntry *entry = NULL;
         char *line;
         size_t pos = 0, n_initrd = 0;
         char *key, *value;
@@ -1483,46 +1484,36 @@ static void config_entry_add_type1(
         assert(file);
         assert(content);
 
-        entry = xnew(ConfigEntry, 1);
-        *entry = (ConfigEntry) {
+        entry = xnew(BootEntry, 1);
+        *entry = (BootEntry) {
                 .tries_done = -1,
                 .tries_left = -1,
         };
 
-        while ((line = line_get_key_value(content, " \t", &pos, &key, &value))) {
+        while ((line = line_get_key_value(content, " \t", &pos, &key, &value)))
                 if (streq8(key, "title")) {
                         free(entry->title);
                         entry->title = xstr8_to_16(value);
-                        continue;
-                }
 
-                if (streq8(key, "sort-key")) {
+                } else if (streq8(key, "sort-key")) {
                         free(entry->sort_key);
                         entry->sort_key = xstr8_to_16(value);
-                        continue;
-                }
 
-                if (streq8(key, "version")) {
+                } else if (streq8(key, "version")) {
                         free(entry->version);
                         entry->version = xstr8_to_16(value);
-                        continue;
-                }
 
-                if (streq8(key, "machine-id")) {
+                } else if (streq8(key, "machine-id")) {
                         free(entry->machine_id);
                         entry->machine_id = xstr8_to_16(value);
-                        continue;
-                }
 
-                if (streq8(key, "linux")) {
+                } else if (streq8(key, "linux")) {
                         free(entry->loader);
                         entry->type = LOADER_LINUX;
                         entry->loader = xstr8_to_path(value);
                         entry->key = 'l';
-                        continue;
-                }
 
-                if (streq8(key, "efi")) {
+                } else if (streq8(key, "efi")) {
                         entry->type = LOADER_EFI;
                         free(entry->loader);
                         entry->loader = xstr8_to_path(value);
@@ -1532,35 +1523,27 @@ static void config_entry_add_type1(
                                 entry->type = LOADER_UNDEFINED;
                                 break;
                         }
-                        continue;
-                }
 
-                if (streq8(key, "architecture")) {
+                } else if (streq8(key, "architecture")) {
                         /* do not add an entry for an EFI image of architecture not matching with that of the image */
                         if (!streq8(value, EFI_MACHINE_TYPE_NAME)) {
                                 entry->type = LOADER_UNDEFINED;
                                 break;
                         }
-                        continue;
-                }
 
-                if (streq8(key, "devicetree")) {
+                } else if (streq8(key, "devicetree")) {
                         free(entry->devicetree);
                         entry->devicetree = xstr8_to_path(value);
-                        continue;
-                }
 
-                if (streq8(key, "initrd")) {
+                } else if (streq8(key, "initrd")) {
                         entry->initrd = xrealloc(
                                 entry->initrd,
                                 n_initrd == 0 ? 0 : (n_initrd + 1) * sizeof(uint16_t *),
                                 (n_initrd + 2) * sizeof(uint16_t *));
                         entry->initrd[n_initrd++] = xstr8_to_path(value);
                         entry->initrd[n_initrd] = NULL;
-                        continue;
-                }
 
-                if (streq8(key, "options")) {
+                } else if (streq8(key, "options")) {
                         _cleanup_free_ char16_t *new = NULL;
 
                         new = xstr8_to_16(value);
@@ -1570,10 +1553,7 @@ static void config_entry_add_type1(
                                 entry->options = s;
                         } else
                                 entry->options = TAKE_PTR(new);
-
-                        continue;
                 }
-        }
 
         if (entry->type == LOADER_UNDEFINED)
                 return;
@@ -1590,7 +1570,7 @@ static void config_entry_add_type1(
 
         config_add_entry(config, entry);
 
-        config_entry_parse_tries(entry, path, file, u".conf");
+        boot_entry_parse_tries(entry, path, file, u".conf");
         TAKE_PTR(entry);
 }
 
@@ -1692,7 +1672,7 @@ static void config_load_defaults(Config *config, EFI_FILE *root_dir) {
                 (void) efivar_get(MAKE_GUID_PTR(LOADER), u"LoaderEntryLastBooted", &config->entry_saved);
 }
 
-static void config_load_entries(
+static void config_load_type1_entries(
                 Config *config,
                 EFI_HANDLE *device,
                 EFI_FILE *root_dir,
@@ -1732,11 +1712,11 @@ static void config_load_entries(
 
                 err = file_read(entries_dir, f->FileName, 0, 0, &content, NULL);
                 if (err == EFI_SUCCESS)
-                        config_entry_add_type1(config, device, root_dir, u"\\loader\\entries", f->FileName, content, loaded_image_path);
+                        boot_entry_add_type1(config, device, root_dir, u"\\loader\\entries", f->FileName, content, loaded_image_path);
         }
 }
 
-static int config_entry_compare(const ConfigEntry *a, const ConfigEntry *b) {
+static int boot_entry_compare(const BootEntry *a, const BootEntry *b) {
         int r;
 
         assert(a);
@@ -1790,7 +1770,7 @@ static int config_entry_compare(const ConfigEntry *a, const ConfigEntry *b) {
         return CMP(a->tries_done, b->tries_done);
 }
 
-static size_t config_entry_find(Config *config, const char16_t *pattern) {
+static size_t config_find_entry(Config *config, const char16_t *pattern) {
         assert(config);
 
         /* We expect pattern and entry IDs to be already case folded. */
@@ -1805,18 +1785,18 @@ static size_t config_entry_find(Config *config, const char16_t *pattern) {
         return IDX_INVALID;
 }
 
-static void config_default_entry_select(Config *config) {
+static void config_select_default_entry(Config *config) {
         size_t i;
 
         assert(config);
 
-        i = config_entry_find(config, config->entry_oneshot);
+        i = config_find_entry(config, config->entry_oneshot);
         if (i != IDX_INVALID) {
                 config->idx_default = i;
                 return;
         }
 
-        i = config_entry_find(config, config->use_saved_entry_efivar ? config->entry_saved : config->entry_default_efivar);
+        i = config_find_entry(config, config->use_saved_entry_efivar ? config->entry_saved : config->entry_default_efivar);
         if (i != IDX_INVALID) {
                 config->idx_default = i;
                 config->idx_default_efivar = i;
@@ -1825,21 +1805,20 @@ static void config_default_entry_select(Config *config) {
 
         if (config->use_saved_entry)
                 /* No need to do the same thing twice. */
-                i = config->use_saved_entry_efivar ? IDX_INVALID : config_entry_find(config, config->entry_saved);
+                i = config->use_saved_entry_efivar ? IDX_INVALID : config_find_entry(config, config->entry_saved);
         else
-                i = config_entry_find(config, config->entry_default_config);
+                i = config_find_entry(config, config->entry_default_config);
         if (i != IDX_INVALID) {
                 config->idx_default = i;
                 return;
         }
 
         /* select the first suitable entry */
-        for (i = 0; i < config->n_entries; i++) {
-                if (config->entries[i]->type == LOADER_AUTO || config->entries[i]->call)
-                        continue;
-                config->idx_default = i;
-                return;
-        }
+        for (i = 0; i < config->n_entries; i++)
+                if (config->entries[i]->type != LOADER_AUTO && !config->entries[i]->call) {
+                        config->idx_default = i;
+                        return;
+                }
 
         /* If no configured entry to select from was found, enable the menu. */
         config->idx_default = 0;
@@ -1847,7 +1826,7 @@ static void config_default_entry_select(Config *config) {
                 config->timeout_sec = 10;
 }
 
-static bool entries_unique(ConfigEntry **entries, bool *unique, size_t n_entries) {
+static bool entries_unique(BootEntry **entries, bool *unique, size_t n_entries) {
         bool is_unique = true;
 
         assert(entries);
@@ -1864,8 +1843,8 @@ static bool entries_unique(ConfigEntry **entries, bool *unique, size_t n_entries
         return is_unique;
 }
 
-/* generate a unique title, avoiding non-distinguishable menu entries */
-static void config_title_generate(Config *config) {
+/* generate unique titles, avoiding non-distinguishable menu entries */
+static void generate_boot_entry_titles(Config *config) {
         assert(config);
 
         bool unique[config->n_entries];
@@ -1947,7 +1926,7 @@ static bool is_sd_boot(EFI_FILE *root_dir, const char16_t *loader_path) {
         return memcmp(content, SD_MAGIC, sizeof(SD_MAGIC)) == 0;
 }
 
-static ConfigEntry *config_entry_add_loader_auto(
+static BootEntry* config_add_entry_loader_auto(
                 Config *config,
                 EFI_HANDLE *device,
                 EFI_FILE *root_dir,
@@ -1986,8 +1965,8 @@ static ConfigEntry *config_entry_add_loader_auto(
         if (err != EFI_SUCCESS)
                 return NULL;
 
-        ConfigEntry *entry = xnew(ConfigEntry, 1);
-        *entry = (ConfigEntry) {
+        BootEntry *entry = xnew(BootEntry, 1);
+        *entry = (BootEntry) {
                 .id = xstrdup16(id),
                 .type = LOADER_AUTO,
                 .title = xstrdup16(title),
@@ -2002,7 +1981,7 @@ static ConfigEntry *config_entry_add_loader_auto(
         return entry;
 }
 
-static void config_entry_add_osx(Config *config) {
+static void config_add_entry_osx(Config *config) {
         EFI_STATUS err;
         size_t n_handles = 0;
         _cleanup_free_ EFI_HANDLE *handles = NULL;
@@ -2023,7 +2002,7 @@ static void config_entry_add_osx(Config *config) {
                 if (open_volume(handles[i], &root) != EFI_SUCCESS)
                         continue;
 
-                if (config_entry_add_loader_auto(
+                if (config_add_entry_loader_auto(
                                 config,
                                 handles[i],
                                 root,
@@ -2119,7 +2098,7 @@ static EFI_STATUS boot_windows_bitlocker(void) {
 }
 #endif
 
-static void config_entry_add_windows(Config *config, EFI_HANDLE *device, EFI_FILE *root_dir) {
+static void config_add_entry_windows(Config *config, EFI_HANDLE *device, EFI_FILE *root_dir) {
 #if defined(__i386__) || defined(__x86_64__) || defined(__arm__) || defined(__aarch64__)
         _cleanup_free_ char *bcd = NULL;
         char16_t *title = NULL;
@@ -2138,16 +2117,16 @@ static void config_entry_add_windows(Config *config, EFI_HANDLE *device, EFI_FIL
         if (err == EFI_SUCCESS)
                 title = get_bcd_title((uint8_t *) bcd, len);
 
-        ConfigEntry *e = config_entry_add_loader_auto(config, device, root_dir, NULL,
-                                                      u"auto-windows", 'w', title ?: u"Windows Boot Manager",
-                                                      u"\\EFI\\Microsoft\\Boot\\bootmgfw.efi");
+        BootEntry *e = config_add_entry_loader_auto(config, device, root_dir, NULL,
+                                                    u"auto-windows", 'w', title ?: u"Windows Boot Manager",
+                                                    u"\\EFI\\Microsoft\\Boot\\bootmgfw.efi");
 
         if (config->reboot_for_bitlocker)
                 e->call = boot_windows_bitlocker;
 #endif
 }
 
-static void config_entry_add_unified(
+static void config_load_type2_entries(
                 Config *config,
                 EFI_HANDLE *device,
                 EFI_FILE *root_dir) {
@@ -2210,55 +2189,39 @@ static void config_entry_add_unified(
                         continue;
 
                 /* read properties from the embedded os-release file */
-                while ((line = line_get_key_value(content, "=", &pos, &key, &value))) {
+                while ((line = line_get_key_value(content, "=", &pos, &key, &value)))
                         if (streq8(key, "PRETTY_NAME")) {
                                 free(os_pretty_name);
                                 os_pretty_name = xstr8_to_16(value);
-                                continue;
-                        }
 
-                        if (streq8(key, "IMAGE_ID")) {
+                        } else if (streq8(key, "IMAGE_ID")) {
                                 free(os_image_id);
                                 os_image_id = xstr8_to_16(value);
-                                continue;
-                        }
 
-                        if (streq8(key, "NAME")) {
+                        } else if (streq8(key, "NAME")) {
                                 free(os_name);
                                 os_name = xstr8_to_16(value);
-                                continue;
-                        }
 
-                        if (streq8(key, "ID")) {
+                        } else if (streq8(key, "ID")) {
                                 free(os_id);
                                 os_id = xstr8_to_16(value);
-                                continue;
-                        }
 
-                        if (streq8(key, "IMAGE_VERSION")) {
+                        } else if (streq8(key, "IMAGE_VERSION")) {
                                 free(os_image_version);
                                 os_image_version = xstr8_to_16(value);
-                                continue;
-                        }
 
-                        if (streq8(key, "VERSION")) {
+                        } else if (streq8(key, "VERSION")) {
                                 free(os_version);
                                 os_version = xstr8_to_16(value);
-                                continue;
-                        }
 
-                        if (streq8(key, "VERSION_ID")) {
+                        } else if (streq8(key, "VERSION_ID")) {
                                 free(os_version_id);
                                 os_version_id = xstr8_to_16(value);
-                                continue;
-                        }
 
-                        if (streq8(key, "BUILD_ID")) {
+                        } else if (streq8(key, "BUILD_ID")) {
                                 free(os_build_id);
                                 os_build_id = xstr8_to_16(value);
-                                continue;
                         }
-                }
 
                 if (!bootspec_pick_name_version_sort_key(
                                     os_pretty_name,
@@ -2274,8 +2237,8 @@ static void config_entry_add_unified(
                                     &good_sort_key))
                         continue;
 
-                ConfigEntry *entry = xnew(ConfigEntry, 1);
-                *entry = (ConfigEntry) {
+                BootEntry *entry = xnew(BootEntry, 1);
+                *entry = (BootEntry) {
                         .id = xstrdup16(f->FileName),
                         .type = LOADER_UNIFIED_LINUX,
                         .title = xstrdup16(good_name),
@@ -2290,7 +2253,7 @@ static void config_entry_add_unified(
 
                 strtolower16(entry->id);
                 config_add_entry(config, entry);
-                config_entry_parse_tries(entry, u"\\EFI\\Linux", f->FileName, u".efi");
+                boot_entry_parse_tries(entry, u"\\EFI\\Linux", f->FileName, u".efi");
 
                 if (szs[SECTION_CMDLINE] == 0)
                         continue;
@@ -2323,13 +2286,13 @@ static void config_load_xbootldr(
         if (err != EFI_SUCCESS)
                 return;
 
-        config_entry_add_unified(config, new_device, root_dir);
-        config_load_entries(config, new_device, root_dir, NULL);
+        config_load_type2_entries(config, new_device, root_dir);
+        config_load_type1_entries(config, new_device, root_dir, NULL);
 }
 
 static EFI_STATUS initrd_prepare(
                 EFI_FILE *root,
-                const ConfigEntry *entry,
+                const BootEntry *entry,
                 char16_t **ret_options,
                 void **ret_initrd,
                 size_t *ret_initrd_size) {
@@ -2405,7 +2368,7 @@ static EFI_STATUS initrd_prepare(
 
 static EFI_STATUS image_start(
                 EFI_HANDLE parent_image,
-                const ConfigEntry *entry) {
+                const BootEntry *entry) {
 
         _cleanup_(devicetree_cleanup) struct devicetree_state dtstate = {};
         _cleanup_(unload_imagep) EFI_HANDLE image = NULL;
@@ -2439,7 +2402,8 @@ static EFI_STATUS image_start(
                 return log_error_status(err, "Error loading %ls: %m", entry->loader);
 
         /* DTBs are loaded by the kernel before ExitBootServices, and they can be used to map and assign
-         * arbitrary memory ranges, so skip it when secure boot is enabled as the DTB here is unverified. */
+         * arbitrary memory ranges, so skip them when secure boot is enabled as the DTB here is unverified.
+         */
         if (entry->devicetree && !secure_boot_enabled()) {
                 err = devicetree_install(&dtstate, image_root, entry->devicetree);
                 if (err != EFI_SUCCESS)
@@ -2456,8 +2420,8 @@ static EFI_STATUS image_start(
         if (err != EFI_SUCCESS)
                 return log_error_status(err, "Error getting LoadedImageProtocol handle: %m");
 
-        /* If we had to append an initrd= entry to the command line, we have to pass it, and measure
-         * it. Otherwise, only pass/measure it if it is not implicit anyway (i.e. embedded into the UKI or
+        /* If we had to append an initrd= entry to the command line, we have to pass it, and measure it.
+         * Otherwise, only pass/measure it if it is not implicit anyway (i.e. embedded into the UKI or
          * so). */
         char16_t *options = options_initrd ?: entry->options_implied ? NULL : entry->options;
         if (options) {
@@ -2500,7 +2464,7 @@ static EFI_STATUS image_start(
 static void config_free(Config *config) {
         assert(config);
         for (size_t i = 0; i < config->n_entries; i++)
-                config_entry_free(config->entries[i]);
+                boot_entry_free(config->entries[i]);
         free(config->entries);
         free(config->entry_default_config);
         free(config->entry_default_efivar);
@@ -2529,7 +2493,7 @@ static void config_write_entries_to_variable(Config *config) {
         (void) efivar_set_raw(MAKE_GUID_PTR(LOADER), u"LoaderEntries", buffer, sz, 0);
 }
 
-static void save_selected_entry(const Config *config, const ConfigEntry *entry) {
+static void save_selected_entry(const Config *config, const BootEntry *entry) {
         assert(config);
         assert(entry);
         assert(entry->loader || !entry->call);
@@ -2569,7 +2533,7 @@ static EFI_STATUS secure_boot_discover_keys(Config *config, EFI_FILE *root_dir)
         for (;;) {
                 _cleanup_free_ EFI_FILE_INFO *dirent = NULL;
                 size_t dirent_size = 0;
-                ConfigEntry *entry = NULL;
+                BootEntry *entry = NULL;
 
                 err = readdir(keys_basedir, &dirent, &dirent_size);
                 if (err != EFI_SUCCESS || !dirent)
@@ -2581,8 +2545,8 @@ static EFI_STATUS secure_boot_discover_keys(Config *config, EFI_FILE *root_dir)
                 if (!FLAGS_SET(dirent->Attribute, EFI_FILE_DIRECTORY))
                         continue;
 
-                entry = xnew(ConfigEntry, 1);
-                *entry = (ConfigEntry) {
+                entry = xnew(BootEntry, 1);
+                *entry = (BootEntry) {
                         .id = xasprintf("secure-boot-keys-%ls", dirent->FileName),
                         .title = xasprintf("Enroll Secure Boot keys: %ls", dirent->FileName),
                         .path = xasprintf("\\loader\\keys\\%ls", dirent->FileName),
@@ -2594,8 +2558,8 @@ static EFI_STATUS secure_boot_discover_keys(Config *config, EFI_FILE *root_dir)
 
                 if (IN_SET(config->secure_boot_enroll, ENROLL_IF_SAFE, ENROLL_FORCE) &&
                     strcaseeq16(dirent->FileName, u"auto"))
-                        /* if we auto enroll successfully this call does not return, if it fails we still
-                         * want to add other potential entries to the menu */
+                        /* If we auto enroll successfully this call does not return.
+                         * If it fails we still want to add other potential entries to the menu. */
                         secure_boot_enroll_at(root_dir, entry->path, config->secure_boot_enroll == ENROLL_FORCE);
         }
 
@@ -2659,29 +2623,29 @@ static void config_load_all_entries(
 
         config_load_defaults(config, root_dir);
 
-        /* scan /EFI/Linux/ directory */
-        config_entry_add_unified(config, loaded_image->DeviceHandle, root_dir);
+        /* Scan /EFI/Linux/ directory */
+        config_load_type2_entries(config, loaded_image->DeviceHandle, root_dir);
 
-        /* scan /loader/entries/\*.conf files */
-        config_load_entries(config, loaded_image->DeviceHandle, root_dir, loaded_image_path);
+        /* Scan /loader/entries/\*.conf files */
+        config_load_type1_entries(config, loaded_image->DeviceHandle, root_dir, loaded_image_path);
 
         /* Similar, but on any XBOOTLDR partition */
         config_load_xbootldr(config, loaded_image->DeviceHandle);
 
-        /* sort entries after version number */
-        sort_pointer_array((void **) config->entries, config->n_entries, (compare_pointer_func_t) config_entry_compare);
+        /* Sort entries after version number */
+        sort_pointer_array((void **) config->entries, config->n_entries, (compare_pointer_func_t) boot_entry_compare);
 
-        /* if we find some well-known loaders, add them to the end of the list */
-        config_entry_add_osx(config);
-        config_entry_add_windows(config, loaded_image->DeviceHandle, root_dir);
-        config_entry_add_loader_auto(config, loaded_image->DeviceHandle, root_dir, NULL,
+        /* If we find some well-known loaders, add them to the end of the list */
+        config_add_entry_osx(config);
+        config_add_entry_windows(config, loaded_image->DeviceHandle, root_dir);
+        config_add_entry_loader_auto(config, loaded_image->DeviceHandle, root_dir, NULL,
                                      u"auto-efi-shell", 's', u"EFI Shell", u"\\shell" EFI_MACHINE_TYPE_NAME ".efi");
-        config_entry_add_loader_auto(config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
+        config_add_entry_loader_auto(config, loaded_image->DeviceHandle, root_dir, loaded_image_path,
                                      u"auto-efi-default", '\0', u"EFI Default Loader", NULL);
 
         if (config->auto_firmware && FLAGS_SET(get_os_indications_supported(), EFI_OS_INDICATIONS_BOOT_TO_FW_UI)) {
-                ConfigEntry *entry = xnew(ConfigEntry, 1);
-                *entry = (ConfigEntry) {
+                BootEntry *entry = xnew(BootEntry, 1);
+                *entry = (BootEntry) {
                         .id = xstrdup16(u"auto-reboot-to-firmware-setup"),
                         .title = xstrdup16(u"Reboot Into Firmware Interface"),
                         .call = reboot_into_firmware,
@@ -2692,8 +2656,8 @@ static void config_load_all_entries(
         }
 
         if (config->auto_poweroff) {
-                ConfigEntry *entry = xnew(ConfigEntry, 1);
-                *entry = (ConfigEntry) {
+                BootEntry *entry = xnew(BootEntry, 1);
+                *entry = (BootEntry) {
                         .id = xstrdup16(u"auto-poweroff"),
                         .title = xstrdup16(u"Power Off The System"),
                         .call = poweroff_system,
@@ -2704,8 +2668,8 @@ static void config_load_all_entries(
         }
 
         if (config->auto_reboot) {
-                ConfigEntry *entry = xnew(ConfigEntry, 1);
-                *entry = (ConfigEntry) {
+                BootEntry *entry = xnew(BootEntry, 1);
+                *entry = (BootEntry) {
                         .id = xstrdup16(u"auto-reboot"),
                         .title = xstrdup16(u"Reboot The System"),
                         .call = reboot_system,
@@ -2715,10 +2679,10 @@ static void config_load_all_entries(
                 config_add_entry(config, entry);
         }
 
-        /* find if secure boot signing keys exist and autoload them if necessary
-        otherwise creates menu entries so that the user can load them manually
-        if the secure-boot-enroll variable is set to no (the default), we do not
-        even search for keys on the ESP */
+        /* Find secure boot signing keys and autoload them if configured.
+         * Otherwise, create menu entries so that the user can load them manually.
+         * If the secure-boot-enroll variable is set to no (the default), we do not
+         * even search for keys on the ESP */
         if (config->secure_boot_enroll != ENROLL_OFF)
                 secure_boot_discover_keys(config, root_dir);
 
@@ -2727,10 +2691,10 @@ static void config_load_all_entries(
 
         config_write_entries_to_variable(config);
 
-        config_title_generate(config);
+        generate_boot_entry_titles(config);
 
-        /* select entry by configured pattern or EFI LoaderDefaultEntry= variable */
-        config_default_entry_select(config);
+        /* Select entry by configured pattern or EFI LoaderDefaultEntry= variable */
+        config_select_default_entry(config);
 }
 
 static EFI_STATUS discover_root_dir(EFI_LOADED_IMAGE_PROTOCOL *loaded_image, EFI_FILE **ret_dir) {
@@ -2785,7 +2749,7 @@ static EFI_STATUS run(EFI_HANDLE image) {
                 /* Block up to 100ms to give firmware time to get input working. */
                 err = console_key_read(&key, 100 * 1000);
                 if (err == EFI_SUCCESS) {
-                        /* find matching key in config entries */
+                        /* find matching key in boot entries */
                         size_t idx = entry_lookup_key(&config, config.idx_default, KEYCHAR(key));
                         if (idx != IDX_INVALID)
                                 config.idx_default = idx;
@@ -2795,7 +2759,7 @@ static EFI_STATUS run(EFI_HANDLE image) {
         }
 
         for (;;) {
-                ConfigEntry *entry;
+                BootEntry *entry;
 
                 entry = config.entries[config.idx_default];
                 if (menu) {
@@ -2819,7 +2783,7 @@ static EFI_STATUS run(EFI_HANDLE image) {
                         continue;
                 }
 
-                (void) config_entry_bump_counters(entry);
+                (void) boot_entry_bump_counters(entry);
                 save_selected_entry(&config, entry);
 
                 /* Optionally, read a random seed off the ESP and pass it to the OS */
index 22200bd939360907190af3c33c5fb2f499b5e5b0..216fc341c18ec65f1d430a53fd5ed064f869b57b 100644 (file)
@@ -154,18 +154,14 @@ int lsm_bpf_setup(Manager *m) {
         return 0;
 }
 
-int lsm_bpf_unit_restrict_filesystems(Unit *u, const Set *filesystems, bool allow_list) {
+int lsm_bpf_restrict_filesystems(const Set *filesystems, uint64_t cgroup_id, int outer_map_fd, bool allow_list) {
         uint32_t dummy_value = 1, zero = 0;
         const char *fs;
         const statfs_f_type_t *magic;
         int r;
 
         assert(filesystems);
-        assert(u);
-
-        if (!u->manager->restrict_fs)
-                return log_unit_error_errno(u, SYNTHETIC_ERRNO(EINVAL),
-                                            "bpf-lsm: BPF LSM object is not installed, has setup failed?");
+        assert(outer_map_fd >= 0);
 
         int inner_map_fd = compat_bpf_map_create(
                         BPF_MAP_TYPE_HASH,
@@ -175,39 +171,35 @@ int lsm_bpf_unit_restrict_filesystems(Unit *u, const Set *filesystems, bool allo
                         128U, /* Should be enough for all filesystem types */
                         NULL);
         if (inner_map_fd < 0)
-                return log_unit_error_errno(u, errno, "bpf-lsm: Failed to create inner BPF map: %m");
-
-        int outer_map_fd = sym_bpf_map__fd(u->manager->restrict_fs->maps.cgroup_hash);
-        if (outer_map_fd < 0)
-                return log_unit_error_errno(u, errno, "bpf-lsm: Failed to get BPF map fd: %m");
+                return log_error_errno(errno, "bpf-lsm: Failed to create inner BPF map: %m");
 
-        if (sym_bpf_map_update_elem(outer_map_fd, &u->cgroup_id, &inner_map_fd, BPF_ANY) != 0)
-                return log_unit_error_errno(u, errno, "bpf-lsm: Error populating BPF map: %m");
+        if (sym_bpf_map_update_elem(outer_map_fd, &cgroup_id, &inner_map_fd, BPF_ANY) != 0)
+                return log_error_errno(errno, "bpf-lsm: Error populating BPF map: %m");
 
         uint32_t allow = allow_list;
 
         /* Use key 0 to store whether this is an allow list or a deny list */
         if (sym_bpf_map_update_elem(inner_map_fd, &zero, &allow, BPF_ANY) != 0)
-                return log_unit_error_errno(u, errno, "bpf-lsm: Error initializing map: %m");
+                return log_error_errno(errno, "bpf-lsm: Error initializing map: %m");
 
         SET_FOREACH(fs, filesystems) {
                 r = fs_type_from_string(fs, &magic);
                 if (r < 0) {
-                        log_unit_warning(u, "bpf-lsm: Invalid filesystem name '%s', ignoring.", fs);
+                        log_warning("bpf-lsm: Invalid filesystem name '%s', ignoring.", fs);
                         continue;
                 }
 
-                log_unit_debug(u, "bpf-lsm: Restricting filesystem access to '%s'", fs);
+                log_debug("bpf-lsm: Restricting filesystem access to '%s'", fs);
 
                 for (int i = 0; i < FILESYSTEM_MAGIC_MAX; i++) {
                         if (magic[i] == 0)
                                 break;
 
                         if (sym_bpf_map_update_elem(inner_map_fd, &magic[i], &dummy_value, BPF_ANY) != 0) {
-                                r = log_unit_error_errno(u, errno, "bpf-lsm: Failed to update BPF map: %m");
+                                r = log_error_errno(errno, "bpf-lsm: Failed to update BPF map: %m");
 
-                                if (sym_bpf_map_delete_elem(outer_map_fd, &u->cgroup_id) != 0)
-                                        log_unit_debug_errno(u, errno, "bpf-lsm: Failed to delete cgroup entry from BPF map: %m");
+                                if (sym_bpf_map_delete_elem(outer_map_fd, &cgroup_id) != 0)
+                                        log_debug_errno(errno, "bpf-lsm: Failed to delete cgroup entry from BPF map: %m");
 
                                 return r;
                         }
@@ -263,8 +255,8 @@ int lsm_bpf_setup(Manager *m) {
         return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "bpf-lsm: Failed to set up LSM BPF: %m");
 }
 
-int lsm_bpf_unit_restrict_filesystems(Unit *u, const Set *filesystems, const bool allow_list) {
-        return log_unit_debug_errno(u, SYNTHETIC_ERRNO(EOPNOTSUPP), "bpf-lsm: Failed to restrict filesystems using LSM BPF: %m");
+int lsm_bpf_restrict_filesystems(const Set *filesystems, uint64_t cgroup_id, int outer_map_fd, const bool allow_list) {
+        return log_debug_errno(SYNTHETIC_ERRNO(EOPNOTSUPP), "bpf-lsm: Failed to restrict filesystems using LSM BPF: %m");
 }
 
 int lsm_bpf_cleanup(const Unit *u) {
index dff581279d7fdef94a692d4ed03a903a17c7e737..a6eda193fe0cbc22894a9589bcea7f9e35d36eca 100644 (file)
@@ -16,7 +16,7 @@ typedef struct restrict_fs_bpf restrict_fs_bpf;
 
 bool lsm_bpf_supported(bool initialize);
 int lsm_bpf_setup(Manager *m);
-int lsm_bpf_unit_restrict_filesystems(Unit *u, const Set *filesystems, bool allow_list);
+int lsm_bpf_restrict_filesystems(const Set *filesystems, uint64_t cgroup_id, int outer_map_fd, bool allow_list);
 int lsm_bpf_cleanup(const Unit *u);
 int lsm_bpf_map_restrict_fs_fd(Unit *u);
 void lsm_bpf_destroy(struct restrict_fs_bpf *prog);
index 47bab04f4210681ec8be87614046cfd06ca28620..e217eab7eed09a1b9c18f114789b443318deaac9 100644 (file)
@@ -143,7 +143,14 @@ static void cgroup_compat_warn(void) {
 void cgroup_context_init(CGroupContext *c) {
         assert(c);
 
-        /* Initialize everything to the kernel defaults. */
+        /* Initialize everything to the kernel defaults. When initializing a bool member to 'true', make
+         * sure to serialize in execute-serialize.c using serialize_bool() instead of
+         * serialize_bool_elide(), as sd-executor will initialize here to 'true', but serialize_bool_elide()
+         * skips serialization if the value is 'false' (as that's the common default), so if the value at
+         * runtime is zero it would be lost after deserialization. Same when initializing uint64_t and other
+         * values, update/add a conditional serialization check. This is to minimize the amount of
+         * serialized data that is sent to the sd-executor, so that there is less work to do on the default
+         * cases. */
 
         *c = (CGroupContext) {
                 .cpu_weight = CGROUP_WEIGHT_INVALID,
@@ -724,6 +731,23 @@ int cgroup_context_add_device_allow(CGroupContext *c, const char *dev, const cha
         return 0;
 }
 
+int cgroup_context_add_or_update_device_allow(CGroupContext *c, const char *dev, const char *mode) {
+        assert(c);
+        assert(dev);
+        assert(isempty(mode) || in_charset(mode, "rwm"));
+
+        LIST_FOREACH(device_allow, b, c->device_allow)
+                if (path_equal(b->path, dev)) {
+                        b->r = isempty(mode) || strchr(mode, 'r');
+                        b->w = isempty(mode) || strchr(mode, 'w');
+                        b->m = isempty(mode) || strchr(mode, 'm');
+
+                        return 0;
+                }
+
+        return cgroup_context_add_device_allow(c, dev, mode);
+}
+
 int cgroup_context_add_bpf_foreign_program(CGroupContext *c, uint32_t attach_type, const char *bpffs_path) {
         CGroupBPFForeignProgram *p;
         _cleanup_free_ char *d = NULL;
index 072c92f0117980f9306a146c7324a83571e03aa9..80d353fac6af3096a5cd56ff78d8f25d185c1df5 100644 (file)
@@ -279,6 +279,7 @@ static inline bool cgroup_context_want_memory_pressure(const CGroupContext *c) {
 }
 
 int cgroup_context_add_device_allow(CGroupContext *c, const char *dev, const char *mode);
+int cgroup_context_add_or_update_device_allow(CGroupContext *c, const char *dev, const char *mode);
 int cgroup_context_add_bpf_foreign_program(CGroupContext *c, uint32_t attach_type, const char *path);
 
 void unit_modify_nft_set(Unit *u, bool add);
index 71714e94731176d511451c242ed39662b535de80..bc741dc47f567a07909db943d8b3c6cc6f47710f 100644 (file)
@@ -510,13 +510,21 @@ static int manager_varlink_init_system(Manager *m) {
         if (!MANAGER_IS_TEST_RUN(m)) {
                 (void) mkdir_p_label("/run/systemd/userdb", 0755);
 
-                r = varlink_server_listen_address(s, "/run/systemd/userdb/io.systemd.DynamicUser", 0666);
-                if (r < 0)
-                        return log_error_errno(r, "Failed to bind to varlink socket: %m");
+                FOREACH_STRING(address, "/run/systemd/userdb/io.systemd.DynamicUser", VARLINK_ADDR_PATH_MANAGED_OOM_SYSTEM) {
+                        if (MANAGER_IS_RELOADING(m)) {
+                                /* If manager is reloading, we skip listening on existing addresses, since
+                                 * the fd should be acquired later through deserialization. */
+                                if (access(address, F_OK) >= 0)
+                                        continue;
+                                if (errno != ENOENT)
+                                        return log_error_errno(errno,
+                                                               "Failed to check if varlink socket '%s' exists: %m", address);
+                        }
 
-                r = varlink_server_listen_address(s, VARLINK_ADDR_PATH_MANAGED_OOM_SYSTEM, 0666);
-                if (r < 0)
-                        return log_error_errno(r, "Failed to bind to varlink socket: %m");
+                        r = varlink_server_listen_address(s, address, 0666);
+                        if (r < 0)
+                                return log_error_errno(r, "Failed to bind to varlink socket '%s': %m", address);
+                }
         }
 
         r = varlink_server_attach_event(s, m->event, SD_EVENT_PRIORITY_NORMAL);
index d38e8a6aeb4142542ac5c9749f89514815b675a4..820b43ee1fe6b594930676fd08be4705aba56a31 100644 (file)
@@ -1820,31 +1820,9 @@ int bus_cgroup_set_property(
                                 return sd_bus_error_set(error, SD_BUS_ERROR_INVALID_ARGS, "DeviceAllow= requires combination of rwm flags");
 
                         if (!UNIT_WRITE_FLAGS_NOOP(flags)) {
-                                CGroupDeviceAllow *a = NULL;
-
-                                LIST_FOREACH(device_allow, b, c->device_allow)
-                                        if (path_equal(b->path, path)) {
-                                                a = b;
-                                                break;
-                                        }
-
-                                if (!a) {
-                                        a = new0(CGroupDeviceAllow, 1);
-                                        if (!a)
-                                                return -ENOMEM;
-
-                                        a->path = strdup(path);
-                                        if (!a->path) {
-                                                free(a);
-                                                return -ENOMEM;
-                                        }
-
-                                        LIST_PREPEND(device_allow, c->device_allow, a);
-                                }
-
-                                a->r = strchr(rwm, 'r');
-                                a->w = strchr(rwm, 'w');
-                                a->m = strchr(rwm, 'm');
+                                r = cgroup_context_add_or_update_device_allow(c, path, rwm);
+                                if (r < 0)
+                                        return r;
                         }
 
                         n++;
index e99a6694f6f6f34ca65798614fb03b9677d0c18d..dc349afecfac0d429d9fd25a870c27d208213bfa 100644 (file)
@@ -26,9 +26,9 @@
 /* Takes a value generated randomly or by hashing and turns it into a UID in the right range */
 #define UID_CLAMP_INTO_RANGE(rnd) (((uid_t) (rnd) % (DYNAMIC_UID_MAX - DYNAMIC_UID_MIN + 1)) + DYNAMIC_UID_MIN)
 
-DEFINE_PRIVATE_TRIVIAL_REF_FUNC(DynamicUser, dynamic_user);
+DEFINE_TRIVIAL_REF_FUNC(DynamicUser, dynamic_user);
 
-static DynamicUser* dynamic_user_free(DynamicUser *d) {
+DynamicUser* dynamic_user_free(DynamicUser *d) {
         if (!d)
                 return NULL;
 
@@ -43,13 +43,15 @@ static int dynamic_user_add(Manager *m, const char *name, int storage_socket[sta
         DynamicUser *d;
         int r;
 
-        assert(m);
+        assert(m || ret);
         assert(name);
         assert(storage_socket);
 
-        r = hashmap_ensure_allocated(&m->dynamic_users, &string_hash_ops);
-        if (r < 0)
-                return r;
+        if (m) { /* Might be called in sd-executor with no manager object */
+                r = hashmap_ensure_allocated(&m->dynamic_users, &string_hash_ops);
+                if (r < 0)
+                        return r;
+        }
 
         d = malloc0(offsetof(DynamicUser, name) + strlen(name) + 1);
         if (!d)
@@ -60,10 +62,12 @@ static int dynamic_user_add(Manager *m, const char *name, int storage_socket[sta
         d->storage_socket[0] = storage_socket[0];
         d->storage_socket[1] = storage_socket[1];
 
-        r = hashmap_put(m->dynamic_users, d->name, d);
-        if (r < 0) {
-                free(d);
-                return r;
+        if (m) { /* Might be called in sd-executor with no manager object */
+                r = hashmap_put(m->dynamic_users, d->name, d);
+                if (r < 0) {
+                        free(d);
+                        return r;
+                }
         }
 
         d->manager = m;
@@ -603,37 +607,49 @@ static DynamicUser* dynamic_user_destroy(DynamicUser *d) {
         return dynamic_user_free(d);
 }
 
-int dynamic_user_serialize(Manager *m, FILE *f, FDSet *fds) {
-        DynamicUser *d;
+int dynamic_user_serialize_one(DynamicUser *d, const char *key, FILE *f, FDSet *fds) {
+        int copy0, copy1;
 
-        assert(m);
+        assert(key);
         assert(f);
         assert(fds);
 
-        /* Dump the dynamic user database into the manager serialization, to deal with daemon reloads. */
+        if (!d)
+                return 0;
 
-        HASHMAP_FOREACH(d, m->dynamic_users) {
-                int copy0, copy1;
+        if (d->storage_socket[0] < 0 || d->storage_socket[1] < 0)
+                return 0;
 
-                copy0 = fdset_put_dup(fds, d->storage_socket[0]);
-                if (copy0 < 0)
-                        return log_error_errno(copy0, "Failed to add dynamic user storage fd to serialization: %m");
+        copy0 = fdset_put_dup(fds, d->storage_socket[0]);
+        if (copy0 < 0)
+                return log_error_errno(copy0, "Failed to add dynamic user storage fd to serialization: %m");
 
-                copy1 = fdset_put_dup(fds, d->storage_socket[1]);
-                if (copy1 < 0)
-                        return log_error_errno(copy1, "Failed to add dynamic user storage fd to serialization: %m");
+        copy1 = fdset_put_dup(fds, d->storage_socket[1]);
+        if (copy1 < 0)
+                return log_error_errno(copy1, "Failed to add dynamic user storage fd to serialization: %m");
 
-                (void) serialize_item_format(f, "dynamic-user", "%s %i %i", d->name, copy0, copy1);
-        }
+        (void) serialize_item_format(f, key, "%s %i %i", d->name, copy0, copy1);
 
         return 0;
 }
 
-void dynamic_user_deserialize_one(Manager *m, const char *value, FDSet *fds) {
+int dynamic_user_serialize(Manager *m, FILE *f, FDSet *fds) {
+        DynamicUser *d;
+
+        assert(m);
+
+        /* Dump the dynamic user database into the manager serialization, to deal with daemon reloads. */
+
+        HASHMAP_FOREACH(d, m->dynamic_users)
+                (void) dynamic_user_serialize_one(d, "dynamic-user", f, fds);
+
+        return 0;
+}
+
+void dynamic_user_deserialize_one(Manager *m, const char *value, FDSet *fds, DynamicUser **ret) {
         _cleanup_free_ char *name = NULL, *s0 = NULL, *s1 = NULL;
         int r, fd0, fd1;
 
-        assert(m);
         assert(value);
         assert(fds);
 
@@ -655,7 +671,7 @@ void dynamic_user_deserialize_one(Manager *m, const char *value, FDSet *fds) {
                 return;
         }
 
-        r = dynamic_user_add(m, name, (int[]) { fd0, fd1 }, NULL);
+        r = dynamic_user_add(m, name, (int[]) { fd0, fd1 }, ret);
         if (r < 0) {
                 log_debug_errno(r, "Failed to add dynamic user: %m");
                 return;
@@ -663,6 +679,9 @@ void dynamic_user_deserialize_one(Manager *m, const char *value, FDSet *fds) {
 
         (void) fdset_remove(fds, fd0);
         (void) fdset_remove(fds, fd1);
+
+        if (ret) /* If the caller uses it directly, increment the refcount */
+                (*ret)->n_ref++;
 }
 
 void dynamic_user_vacuum(Manager *m, bool close_user) {
@@ -831,3 +850,12 @@ DynamicCreds* dynamic_creds_destroy(DynamicCreds *creds) {
 
         return mfree(creds);
 }
+
+void dynamic_creds_done(DynamicCreds *creds) {
+        if (!creds)
+                return;
+
+        if (creds->group != creds->user)
+                dynamic_user_free(creds->group);
+        creds->group = creds->user = dynamic_user_free(creds->user);
+}
index 6539d17571b2112afc2ca3e587a1caefdf4b3396..e86ee02796b1282f10f247db08ffa1952cf4ace6 100644 (file)
@@ -26,7 +26,9 @@ struct DynamicUser {
 };
 
 int dynamic_user_serialize(Manager *m, FILE *f, FDSet *fds);
-void dynamic_user_deserialize_one(Manager *m, const char *value, FDSet *fds);
+int dynamic_user_serialize_one(DynamicUser *d, const char *key, FILE *f, FDSet *fds);
+void dynamic_user_deserialize_one(Manager *m, const char *value, FDSet *fds, DynamicUser **ret);
+DynamicUser* dynamic_user_free(DynamicUser *d);
 void dynamic_user_vacuum(Manager *m, bool close_user);
 
 int dynamic_user_current(DynamicUser *d, uid_t *ret);
@@ -38,6 +40,9 @@ int dynamic_creds_realize(DynamicCreds *creds, char **suggested_paths, uid_t *ui
 
 DynamicCreds *dynamic_creds_unref(DynamicCreds *creds);
 DynamicCreds *dynamic_creds_destroy(DynamicCreds *creds);
+void dynamic_creds_done(DynamicCreds *creds);
 
 DEFINE_TRIVIAL_CLEANUP_FUNC(DynamicCreds*, dynamic_creds_unref);
 DEFINE_TRIVIAL_CLEANUP_FUNC(DynamicCreds*, dynamic_creds_destroy);
+
+DynamicUser *dynamic_user_ref(DynamicUser *user);
index 4d4dadca90de1c5e4bd6cc1bc172fac8993d0359..ff2d795c7d90f3b6527a257fa311ea0ee57d5429 100644 (file)
@@ -932,7 +932,8 @@ int exec_setup_credentials(
 
         r = safe_fork("(sd-mkdcreds)", FORK_DEATHSIG|FORK_WAIT|FORK_NEW_MOUNTNS, NULL);
         if (r < 0) {
-                _cleanup_free_ char *t = NULL, *u = NULL;
+                _cleanup_(rmdir_and_freep) char *u = NULL; /* remove the temporary workspace if we can */
+                _cleanup_free_ char *t = NULL;
 
                 /* If this is not a privilege or support issue then propagate the error */
                 if (!ERRNO_IS_NOT_SUPPORTED(r) && !ERRNO_IS_PRIVILEGE(r))
@@ -967,9 +968,6 @@ int exec_setup_credentials(
                                 false,   /* it's OK to fall back to a plain directory if we can't mount anything */
                                 uid,
                                 gid);
-
-                (void) rmdir(u); /* remove the workspace again if we can. */
-
                 if (r < 0)
                         return r;
 
diff --git a/src/core/exec-invoke.c b/src/core/exec-invoke.c
new file mode 100644 (file)
index 0000000..ea39e0a
--- /dev/null
@@ -0,0 +1,5082 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+
+#include <sys/eventfd.h>
+#include <sys/ioctl.h>
+#include <sys/mount.h>
+#include <sys/prctl.h>
+
+#if HAVE_PAM
+#include <security/pam_appl.h>
+#include <security/pam_misc.h>
+#endif
+
+#if HAVE_APPARMOR
+#include <sys/apparmor.h>
+#endif
+
+#include "sd-messages.h"
+
+#if HAVE_APPARMOR
+#include "apparmor-util.h"
+#endif
+#include "argv-util.h"
+#include "barrier.h"
+#include "bpf-dlopen.h"
+#include "bpf-lsm.h"
+#include "btrfs-util.h"
+#include "capability-util.h"
+#include "cgroup-setup.h"
+#include "chase.h"
+#include "chattr-util.h"
+#include "chown-recursive.h"
+#include "copy.h"
+#include "data-fd-util.h"
+#include "env-util.h"
+#include "escape.h"
+#include "exec-credential.h"
+#include "exec-invoke.h"
+#include "execute.h"
+#include "exit-status.h"
+#include "fd-util.h"
+#include "hexdecoct.h"
+#include "io-util.h"
+#include "missing_ioprio.h"
+#include "missing_prctl.h"
+#include "missing_securebits.h"
+#include "missing_syscall.h"
+#include "mkdir-label.h"
+#include "proc-cmdline.h"
+#include "process-util.h"
+#include "psi-util.h"
+#include "rlimit-util.h"
+#include "seccomp-util.h"
+#include "selinux-util.h"
+#include "signal-util.h"
+#include "smack-util.h"
+#include "socket-util.h"
+#include "string-table.h"
+#include "strv.h"
+#include "terminal-util.h"
+#include "utmp-wtmp.h"
+
+#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
+#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
+
+#define SNDBUF_SIZE (8*1024*1024)
+
+static int shift_fds(int fds[], size_t n_fds) {
+        if (n_fds <= 0)
+                return 0;
+
+        /* Modifies the fds array! (sorts it) */
+
+        assert(fds);
+
+        for (int start = 0;;) {
+                int restart_from = -1;
+
+                for (int i = start; i < (int) n_fds; i++) {
+                        int nfd;
+
+                        /* Already at right index? */
+                        if (fds[i] == i+3)
+                                continue;
+
+                        nfd = fcntl(fds[i], F_DUPFD, i + 3);
+                        if (nfd < 0)
+                                return -errno;
+
+                        safe_close(fds[i]);
+                        fds[i] = nfd;
+
+                        /* Hmm, the fd we wanted isn't free? Then
+                         * let's remember that and try again from here */
+                        if (nfd != i+3 && restart_from < 0)
+                                restart_from = i;
+                }
+
+                if (restart_from < 0)
+                        break;
+
+                start = restart_from;
+        }
+
+        return 0;
+}
+
+static int flags_fds(
+                const int fds[],
+                size_t n_socket_fds,
+                size_t n_fds,
+                bool nonblock) {
+
+        int r;
+
+        if (n_fds <= 0)
+                return 0;
+
+        assert(fds);
+
+        /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags.
+         * O_NONBLOCK only applies to socket activation though. */
+
+        for (size_t i = 0; i < n_fds; i++) {
+
+                if (i < n_socket_fds) {
+                        r = fd_nonblock(fds[i], nonblock);
+                        if (r < 0)
+                                return r;
+                }
+
+                /* We unconditionally drop FD_CLOEXEC from the fds,
+                 * since after all we want to pass these fds to our
+                 * children */
+
+                r = fd_cloexec(fds[i], false);
+                if (r < 0)
+                        return r;
+        }
+
+        return 0;
+}
+
+static bool is_terminal_input(ExecInput i) {
+        return IN_SET(i,
+                      EXEC_INPUT_TTY,
+                      EXEC_INPUT_TTY_FORCE,
+                      EXEC_INPUT_TTY_FAIL);
+}
+
+static bool is_terminal_output(ExecOutput o) {
+        return IN_SET(o,
+                      EXEC_OUTPUT_TTY,
+                      EXEC_OUTPUT_KMSG_AND_CONSOLE,
+                      EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
+}
+
+static bool is_kmsg_output(ExecOutput o) {
+        return IN_SET(o,
+                      EXEC_OUTPUT_KMSG,
+                      EXEC_OUTPUT_KMSG_AND_CONSOLE);
+}
+
+static bool exec_context_needs_term(const ExecContext *c) {
+        assert(c);
+
+        /* Return true if the execution context suggests we should set $TERM to something useful. */
+
+        if (is_terminal_input(c->std_input))
+                return true;
+
+        if (is_terminal_output(c->std_output))
+                return true;
+
+        if (is_terminal_output(c->std_error))
+                return true;
+
+        return !!c->tty_path;
+}
+
+static int open_null_as(int flags, int nfd) {
+        int fd;
+
+        assert(nfd >= 0);
+
+        fd = open("/dev/null", flags|O_NOCTTY);
+        if (fd < 0)
+                return -errno;
+
+        return move_fd(fd, nfd, false);
+}
+
+static int connect_journal_socket(
+                int fd,
+                const char *log_namespace,
+                uid_t uid,
+                gid_t gid) {
+
+        uid_t olduid = UID_INVALID;
+        gid_t oldgid = GID_INVALID;
+        const char *j;
+        int r;
+
+        j = log_namespace ?
+                strjoina("/run/systemd/journal.", log_namespace, "/stdout") :
+                "/run/systemd/journal/stdout";
+
+        if (gid_is_valid(gid)) {
+                oldgid = getgid();
+
+                if (setegid(gid) < 0)
+                        return -errno;
+        }
+
+        if (uid_is_valid(uid)) {
+                olduid = getuid();
+
+                if (seteuid(uid) < 0) {
+                        r = -errno;
+                        goto restore_gid;
+                }
+        }
+
+        r = connect_unix_path(fd, AT_FDCWD, j);
+
+        /* If we fail to restore the uid or gid, things will likely fail later on. This should only happen if
+           an LSM interferes. */
+
+        if (uid_is_valid(uid))
+                (void) seteuid(olduid);
+
+ restore_gid:
+        if (gid_is_valid(gid))
+                (void) setegid(oldgid);
+
+        return r;
+}
+
+static int connect_logger_as(
+                const ExecContext *context,
+                const ExecParameters *params,
+                ExecOutput output,
+                const char *ident,
+                int nfd,
+                uid_t uid,
+                gid_t gid) {
+
+        _cleanup_close_ int fd = -EBADF;
+        int r;
+
+        assert(context);
+        assert(params);
+        assert(output < _EXEC_OUTPUT_MAX);
+        assert(ident);
+        assert(nfd >= 0);
+
+        fd = socket(AF_UNIX, SOCK_STREAM, 0);
+        if (fd < 0)
+                return -errno;
+
+        r = connect_journal_socket(fd, context->log_namespace, uid, gid);
+        if (r < 0)
+                return r;
+
+        if (shutdown(fd, SHUT_RD) < 0)
+                return -errno;
+
+        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
+
+        if (dprintf(fd,
+                "%s\n"
+                "%s\n"
+                "%i\n"
+                "%i\n"
+                "%i\n"
+                "%i\n"
+                "%i\n",
+                context->syslog_identifier ?: ident,
+                params->flags & EXEC_PASS_LOG_UNIT ? params->unit_id : "",
+                context->syslog_priority,
+                !!context->syslog_level_prefix,
+                false,
+                is_kmsg_output(output),
+                is_terminal_output(output)) < 0)
+                return -errno;
+
+        return move_fd(TAKE_FD(fd), nfd, false);
+}
+
+static int open_terminal_as(const char *path, int flags, int nfd) {
+        int fd;
+
+        assert(path);
+        assert(nfd >= 0);
+
+        fd = open_terminal(path, flags | O_NOCTTY);
+        if (fd < 0)
+                return fd;
+
+        return move_fd(fd, nfd, false);
+}
+
+static int acquire_path(const char *path, int flags, mode_t mode) {
+        _cleanup_close_ int fd = -EBADF;
+        int r;
+
+        assert(path);
+
+        if (IN_SET(flags & O_ACCMODE, O_WRONLY, O_RDWR))
+                flags |= O_CREAT;
+
+        fd = open(path, flags|O_NOCTTY, mode);
+        if (fd >= 0)
+                return TAKE_FD(fd);
+
+        if (errno != ENXIO) /* ENXIO is returned when we try to open() an AF_UNIX file system socket on Linux */
+                return -errno;
+
+        /* So, it appears the specified path could be an AF_UNIX socket. Let's see if we can connect to it. */
+
+        fd = socket(AF_UNIX, SOCK_STREAM, 0);
+        if (fd < 0)
+                return -errno;
+
+        r = connect_unix_path(fd, AT_FDCWD, path);
+        if (IN_SET(r, -ENOTSOCK, -EINVAL))
+                /* Propagate initial error if we get ENOTSOCK or EINVAL, i.e. we have indication that this
+                 * wasn't an AF_UNIX socket after all */
+                return -ENXIO;
+        if (r < 0)
+                return r;
+
+        if ((flags & O_ACCMODE) == O_RDONLY)
+                r = shutdown(fd, SHUT_WR);
+        else if ((flags & O_ACCMODE) == O_WRONLY)
+                r = shutdown(fd, SHUT_RD);
+        else
+                r = 0;
+        if (r < 0)
+                return -errno;
+
+        return TAKE_FD(fd);
+}
+
+static int fixup_input(
+                const ExecContext *context,
+                int socket_fd,
+                bool apply_tty_stdin) {
+
+        ExecInput std_input;
+
+        assert(context);
+
+        std_input = context->std_input;
+
+        if (is_terminal_input(std_input) && !apply_tty_stdin)
+                return EXEC_INPUT_NULL;
+
+        if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
+                return EXEC_INPUT_NULL;
+
+        if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
+                return EXEC_INPUT_NULL;
+
+        return std_input;
+}
+
+static int fixup_output(ExecOutput output, int socket_fd) {
+
+        if (output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
+                return EXEC_OUTPUT_INHERIT;
+
+        return output;
+}
+
+static int setup_input(
+                const ExecContext *context,
+                const ExecParameters *params,
+                int socket_fd,
+                const int named_iofds[static 3]) {
+
+        ExecInput i;
+        int r;
+
+        assert(context);
+        assert(params);
+        assert(named_iofds);
+
+        if (params->stdin_fd >= 0) {
+                if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
+                        return -errno;
+
+                /* Try to make this the controlling tty, if it is a tty, and reset it */
+                if (isatty(STDIN_FILENO)) {
+                        unsigned rows = context->tty_rows, cols = context->tty_cols;
+
+                        (void) exec_context_tty_size(context, &rows, &cols);
+                        (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE);
+                        (void) reset_terminal_fd(STDIN_FILENO, true);
+                        (void) terminal_set_size_fd(STDIN_FILENO, NULL, rows, cols);
+                }
+
+                return STDIN_FILENO;
+        }
+
+        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
+
+        switch (i) {
+
+        case EXEC_INPUT_NULL:
+                return open_null_as(O_RDONLY, STDIN_FILENO);
+
+        case EXEC_INPUT_TTY:
+        case EXEC_INPUT_TTY_FORCE:
+        case EXEC_INPUT_TTY_FAIL: {
+                unsigned rows, cols;
+                int fd;
+
+                fd = acquire_terminal(exec_context_tty_path(context),
+                                      i == EXEC_INPUT_TTY_FAIL  ? ACQUIRE_TERMINAL_TRY :
+                                      i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
+                                                                  ACQUIRE_TERMINAL_WAIT,
+                                      USEC_INFINITY);
+                if (fd < 0)
+                        return fd;
+
+                r = exec_context_tty_size(context, &rows, &cols);
+                if (r < 0)
+                        return r;
+
+                r = terminal_set_size_fd(fd, exec_context_tty_path(context), rows, cols);
+                if (r < 0)
+                        return r;
+
+                return move_fd(fd, STDIN_FILENO, false);
+        }
+
+        case EXEC_INPUT_SOCKET:
+                assert(socket_fd >= 0);
+
+                return RET_NERRNO(dup2(socket_fd, STDIN_FILENO));
+
+        case EXEC_INPUT_NAMED_FD:
+                assert(named_iofds[STDIN_FILENO] >= 0);
+
+                (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
+                return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO));
+
+        case EXEC_INPUT_DATA: {
+                int fd;
+
+                fd = acquire_data_fd(context->stdin_data, context->stdin_data_size, 0);
+                if (fd < 0)
+                        return fd;
+
+                return move_fd(fd, STDIN_FILENO, false);
+        }
+
+        case EXEC_INPUT_FILE: {
+                bool rw;
+                int fd;
+
+                assert(context->stdio_file[STDIN_FILENO]);
+
+                rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
+                        (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));
+
+                fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
+                if (fd < 0)
+                        return fd;
+
+                return move_fd(fd, STDIN_FILENO, false);
+        }
+
+        default:
+                assert_not_reached();
+        }
+}
+
+static bool can_inherit_stderr_from_stdout(
+                const ExecContext *context,
+                ExecOutput o,
+                ExecOutput e) {
+
+        assert(context);
+
+        /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
+         * stderr fd */
+
+        if (e == EXEC_OUTPUT_INHERIT)
+                return true;
+        if (e != o)
+                return false;
+
+        if (e == EXEC_OUTPUT_NAMED_FD)
+                return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]);
+
+        if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE))
+                return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);
+
+        return true;
+}
+
+static int setup_output(
+                const ExecContext *context,
+                const ExecParameters *params,
+                int fileno,
+                int socket_fd,
+                const int named_iofds[static 3],
+                const char *ident,
+                uid_t uid,
+                gid_t gid,
+                dev_t *journal_stream_dev,
+                ino_t *journal_stream_ino) {
+
+        ExecOutput o;
+        ExecInput i;
+        int r;
+
+        assert(context);
+        assert(params);
+        assert(ident);
+        assert(journal_stream_dev);
+        assert(journal_stream_ino);
+
+        if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
+
+                if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
+                        return -errno;
+
+                return STDOUT_FILENO;
+        }
+
+        if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
+                if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
+                        return -errno;
+
+                return STDERR_FILENO;
+        }
+
+        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
+        o = fixup_output(context->std_output, socket_fd);
+
+        if (fileno == STDERR_FILENO) {
+                ExecOutput e;
+                e = fixup_output(context->std_error, socket_fd);
+
+                /* This expects the input and output are already set up */
+
+                /* Don't change the stderr file descriptor if we inherit all
+                 * the way and are not on a tty */
+                if (e == EXEC_OUTPUT_INHERIT &&
+                    o == EXEC_OUTPUT_INHERIT &&
+                    i == EXEC_INPUT_NULL &&
+                    !is_terminal_input(context->std_input) &&
+                    getppid() != 1)
+                        return fileno;
+
+                /* Duplicate from stdout if possible */
+                if (can_inherit_stderr_from_stdout(context, o, e))
+                        return RET_NERRNO(dup2(STDOUT_FILENO, fileno));
+
+                o = e;
+
+        } else if (o == EXEC_OUTPUT_INHERIT) {
+                /* If input got downgraded, inherit the original value */
+                if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
+                        return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
+
+                /* If the input is connected to anything that's not a /dev/null or a data fd, inherit that... */
+                if (!IN_SET(i, EXEC_INPUT_NULL, EXEC_INPUT_DATA))
+                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
+
+                /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
+                if (getppid() != 1)
+                        return fileno;
+
+                /* We need to open /dev/null here anew, to get the right access mode. */
+                return open_null_as(O_WRONLY, fileno);
+        }
+
+        switch (o) {
+
+        case EXEC_OUTPUT_NULL:
+                return open_null_as(O_WRONLY, fileno);
+
+        case EXEC_OUTPUT_TTY:
+                if (is_terminal_input(i))
+                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
+
+                /* We don't reset the terminal if this is just about output */
+                return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
+
+        case EXEC_OUTPUT_KMSG:
+        case EXEC_OUTPUT_KMSG_AND_CONSOLE:
+        case EXEC_OUTPUT_JOURNAL:
+        case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
+                r = connect_logger_as(context, params, o, ident, fileno, uid, gid);
+                if (r < 0) {
+                        log_exec_warning_errno(context,
+                                               params,
+                                               r,
+                                               "Failed to connect %s to the journal socket, ignoring: %m",
+                                               fileno == STDOUT_FILENO ? "stdout" : "stderr");
+                        r = open_null_as(O_WRONLY, fileno);
+                } else {
+                        struct stat st;
+
+                        /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
+                         * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
+                         * services to detect whether they are connected to the journal or not.
+                         *
+                         * If both stdout and stderr are connected to a stream then let's make sure to store the data
+                         * about STDERR as that's usually the best way to do logging. */
+
+                        if (fstat(fileno, &st) >= 0 &&
+                            (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
+                                *journal_stream_dev = st.st_dev;
+                                *journal_stream_ino = st.st_ino;
+                        }
+                }
+                return r;
+
+        case EXEC_OUTPUT_SOCKET:
+                assert(socket_fd >= 0);
+
+                return RET_NERRNO(dup2(socket_fd, fileno));
+
+        case EXEC_OUTPUT_NAMED_FD:
+                assert(named_iofds[fileno] >= 0);
+
+                (void) fd_nonblock(named_iofds[fileno], false);
+                return RET_NERRNO(dup2(named_iofds[fileno], fileno));
+
+        case EXEC_OUTPUT_FILE:
+        case EXEC_OUTPUT_FILE_APPEND:
+        case EXEC_OUTPUT_FILE_TRUNCATE: {
+                bool rw;
+                int fd, flags;
+
+                assert(context->stdio_file[fileno]);
+
+                rw = context->std_input == EXEC_INPUT_FILE &&
+                        streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]);
+
+                if (rw)
+                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
+
+                flags = O_WRONLY;
+                if (o == EXEC_OUTPUT_FILE_APPEND)
+                        flags |= O_APPEND;
+                else if (o == EXEC_OUTPUT_FILE_TRUNCATE)
+                        flags |= O_TRUNC;
+
+                fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
+                if (fd < 0)
+                        return fd;
+
+                return move_fd(fd, fileno, 0);
+        }
+
+        default:
+                assert_not_reached();
+        }
+}
+
+static int chown_terminal(int fd, uid_t uid) {
+        int r;
+
+        assert(fd >= 0);
+
+        /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
+        if (isatty(fd) < 1) {
+                if (IN_SET(errno, EINVAL, ENOTTY))
+                        return 0; /* not a tty */
+
+                return -errno;
+        }
+
+        /* This might fail. What matters are the results. */
+        r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID);
+        if (r < 0)
+                return r;
+
+        return 1;
+}
+
+static int setup_confirm_stdio(
+                const ExecContext *context,
+                const char *vc,
+                int *ret_saved_stdin,
+                int *ret_saved_stdout) {
+
+        _cleanup_close_ int fd = -EBADF, saved_stdin = -EBADF, saved_stdout = -EBADF;
+        unsigned rows, cols;
+        int r;
+
+        assert(ret_saved_stdin);
+        assert(ret_saved_stdout);
+
+        saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
+        if (saved_stdin < 0)
+                return -errno;
+
+        saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
+        if (saved_stdout < 0)
+                return -errno;
+
+        fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
+        if (fd < 0)
+                return fd;
+
+        r = chown_terminal(fd, getuid());
+        if (r < 0)
+                return r;
+
+        r = reset_terminal_fd(fd, true);
+        if (r < 0)
+                return r;
+
+        r = exec_context_tty_size(context, &rows, &cols);
+        if (r < 0)
+                return r;
+
+        r = terminal_set_size_fd(fd, vc, rows, cols);
+        if (r < 0)
+                return r;
+
+        r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */
+        TAKE_FD(fd);
+        if (r < 0)
+                return r;
+
+        *ret_saved_stdin = TAKE_FD(saved_stdin);
+        *ret_saved_stdout = TAKE_FD(saved_stdout);
+        return 0;
+}
+
+static void write_confirm_error_fd(int err, int fd, const char *unit_id) {
+        assert(err < 0);
+        assert(unit_id);
+
+        if (err == -ETIMEDOUT)
+                dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", unit_id);
+        else {
+                errno = -err;
+                dprintf(fd, "Couldn't ask confirmation for %s: %m, assuming positive response.\n", unit_id);
+        }
+}
+
+static void write_confirm_error(int err, const char *vc, const char *unit_id) {
+        _cleanup_close_ int fd = -EBADF;
+
+        assert(vc);
+
+        fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
+        if (fd < 0)
+                return;
+
+        write_confirm_error_fd(err, fd, unit_id);
+}
+
+static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
+        int r = 0;
+
+        assert(saved_stdin);
+        assert(saved_stdout);
+
+        release_terminal();
+
+        if (*saved_stdin >= 0)
+                if (dup2(*saved_stdin, STDIN_FILENO) < 0)
+                        r = -errno;
+
+        if (*saved_stdout >= 0)
+                if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
+                        r = -errno;
+
+        *saved_stdin = safe_close(*saved_stdin);
+        *saved_stdout = safe_close(*saved_stdout);
+
+        return r;
+}
+
+enum {
+        CONFIRM_PRETEND_FAILURE = -1,
+        CONFIRM_PRETEND_SUCCESS =  0,
+        CONFIRM_EXECUTE = 1,
+};
+
+static bool confirm_spawn_disabled(void) {
+        return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
+}
+
+static int ask_for_confirmation(const ExecContext *context, const ExecParameters *params, const char *cmdline) {
+        int saved_stdout = -1, saved_stdin = -1, r;
+        _cleanup_free_ char *e = NULL;
+        char c;
+
+        assert(context);
+        assert(params);
+
+        /* For any internal errors, assume a positive response. */
+        r = setup_confirm_stdio(context, params->confirm_spawn, &saved_stdin, &saved_stdout);
+        if (r < 0) {
+                write_confirm_error(r, params->confirm_spawn, params->unit_id);
+                return CONFIRM_EXECUTE;
+        }
+
+        /* confirm_spawn might have been disabled while we were sleeping. */
+        if (!params->confirm_spawn || confirm_spawn_disabled()) {
+                r = 1;
+                goto restore_stdio;
+        }
+
+        e = ellipsize(cmdline, 60, 100);
+        if (!e) {
+                log_oom();
+                r = CONFIRM_EXECUTE;
+                goto restore_stdio;
+        }
+
+        for (;;) {
+                r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e);
+                if (r < 0) {
+                        write_confirm_error_fd(r, STDOUT_FILENO, params->unit_id);
+                        r = CONFIRM_EXECUTE;
+                        goto restore_stdio;
+                }
+
+                switch (c) {
+                case 'c':
+                        printf("Resuming normal execution.\n");
+                        manager_disable_confirm_spawn();
+                        r = 1;
+                        break;
+                case 'D':
+                        printf("  Unit: %s\n",
+                               params->unit_id);
+                        exec_context_dump(context, stdout, "  ");
+                        exec_params_dump(params, stdout, "  ");
+                        continue; /* ask again */
+                case 'f':
+                        printf("Failing execution.\n");
+                        r = CONFIRM_PRETEND_FAILURE;
+                        break;
+                case 'h':
+                        printf("  c - continue, proceed without asking anymore\n"
+                               "  D - dump, show the state of the unit\n"
+                               "  f - fail, don't execute the command and pretend it failed\n"
+                               "  h - help\n"
+                               "  i - info, show a short summary of the unit\n"
+                               "  j - jobs, show jobs that are in progress\n"
+                               "  s - skip, don't execute the command and pretend it succeeded\n"
+                               "  y - yes, execute the command\n");
+                        continue; /* ask again */
+                case 'i':
+                        printf("  Unit:        %s\n"
+                               "  Command:     %s\n",
+                               params->unit_id, cmdline);
+                        continue; /* ask again */
+                case 'j':
+                        if (sigqueue(getppid(),
+                                     SIGRTMIN+18,
+                                     (const union sigval) { .sival_int = MANAGER_SIGNAL_COMMAND_DUMP_JOBS }) < 0)
+                                return -errno;
+
+                        continue; /* ask again */
+                case 'n':
+                        /* 'n' was removed in favor of 'f'. */
+                        printf("Didn't understand 'n', did you mean 'f'?\n");
+                        continue; /* ask again */
+                case 's':
+                        printf("Skipping execution.\n");
+                        r = CONFIRM_PRETEND_SUCCESS;
+                        break;
+                case 'y':
+                        r = CONFIRM_EXECUTE;
+                        break;
+                default:
+                        assert_not_reached();
+                }
+                break;
+        }
+
+restore_stdio:
+        restore_confirm_stdio(&saved_stdin, &saved_stdout);
+        return r;
+}
+
+static int get_fixed_user(
+                const char *username,
+                const char **ret_user,
+                uid_t *ret_uid,
+                gid_t *ret_gid,
+                const char **ret_home,
+                const char **ret_shell) {
+
+        int r;
+
+        assert(username);
+        assert(ret_user);
+
+        /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
+         * (i.e. are "/" or "/bin/nologin"). */
+
+        r = get_user_creds(&username, ret_uid, ret_gid, ret_home, ret_shell, USER_CREDS_CLEAN);
+        if (r < 0)
+                return r;
+
+        *ret_user = username;
+        return 0;
+}
+
+static int get_fixed_group(
+                const char *groupname,
+                const char **ret_group,
+                gid_t *ret_gid) {
+
+        int r;
+
+        assert(groupname);
+        assert(ret_group);
+
+        r = get_group_creds(&groupname, ret_gid, /* flags = */ 0);
+        if (r < 0)
+                return r;
+
+        *ret_group = groupname;
+        return 0;
+}
+
+static int get_supplementary_groups(const ExecContext *c, const char *user,
+                                    const char *group, gid_t gid,
+                                    gid_t **supplementary_gids, int *ngids) {
+        int r, k = 0;
+        int ngroups_max;
+        bool keep_groups = false;
+        gid_t *groups = NULL;
+        _cleanup_free_ gid_t *l_gids = NULL;
+
+        assert(c);
+
+        /*
+         * If user is given, then lookup GID and supplementary groups list.
+         * We avoid NSS lookups for gid=0. Also we have to initialize groups
+         * here and as early as possible so we keep the list of supplementary
+         * groups of the caller.
+         */
+        if (user && gid_is_valid(gid) && gid != 0) {
+                /* First step, initialize groups from /etc/groups */
+                if (initgroups(user, gid) < 0)
+                        return -errno;
+
+                keep_groups = true;
+        }
+
+        if (strv_isempty(c->supplementary_groups))
+                return 0;
+
+        /*
+         * If SupplementaryGroups= was passed then NGROUPS_MAX has to
+         * be positive, otherwise fail.
+         */
+        errno = 0;
+        ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
+        if (ngroups_max <= 0)
+                return errno_or_else(EOPNOTSUPP);
+
+        l_gids = new(gid_t, ngroups_max);
+        if (!l_gids)
+                return -ENOMEM;
+
+        if (keep_groups) {
+                /*
+                 * Lookup the list of groups that the user belongs to, we
+                 * avoid NSS lookups here too for gid=0.
+                 */
+                k = ngroups_max;
+                if (getgrouplist(user, gid, l_gids, &k) < 0)
+                        return -EINVAL;
+        } else
+                k = 0;
+
+        STRV_FOREACH(i, c->supplementary_groups) {
+                const char *g;
+
+                if (k >= ngroups_max)
+                        return -E2BIG;
+
+                g = *i;
+                r = get_group_creds(&g, l_gids+k, 0);
+                if (r < 0)
+                        return r;
+
+                k++;
+        }
+
+        /*
+         * Sets ngids to zero to drop all supplementary groups, happens
+         * when we are under root and SupplementaryGroups= is empty.
+         */
+        if (k == 0) {
+                *ngids = 0;
+                return 0;
+        }
+
+        /* Otherwise get the final list of supplementary groups */
+        groups = memdup(l_gids, sizeof(gid_t) * k);
+        if (!groups)
+                return -ENOMEM;
+
+        *supplementary_gids = groups;
+        *ngids = k;
+
+        groups = NULL;
+
+        return 0;
+}
+
+static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
+        int r;
+
+        /* Handle SupplementaryGroups= if it is not empty */
+        if (ngids > 0) {
+                r = maybe_setgroups(ngids, supplementary_gids);
+                if (r < 0)
+                        return r;
+        }
+
+        if (gid_is_valid(gid)) {
+                /* Then set our gids */
+                if (setresgid(gid, gid, gid) < 0)
+                        return -errno;
+        }
+
+        return 0;
+}
+
+static int set_securebits(unsigned bits, unsigned mask) {
+        unsigned applied;
+        int current;
+
+        current = prctl(PR_GET_SECUREBITS);
+        if (current < 0)
+                return -errno;
+
+        /* Clear all securebits defined in mask and set bits */
+        applied = ((unsigned) current & ~mask) | bits;
+        if ((unsigned) current == applied)
+                return 0;
+
+        if (prctl(PR_SET_SECUREBITS, applied) < 0)
+                return -errno;
+
+        return 1;
+}
+
+static int enforce_user(
+                const ExecContext *context,
+                uid_t uid,
+                uint64_t capability_ambient_set) {
+        assert(context);
+        int r;
+
+        if (!uid_is_valid(uid))
+                return 0;
+
+        /* Sets (but doesn't look up) the UIS and makes sure we keep the capabilities while doing so. For
+         * setting secure bits the capability CAP_SETPCAP is required, so we also need keep-caps in this
+         * case. */
+
+        if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {
+
+                /* First step: If we need to keep capabilities but drop privileges we need to make sure we
+                 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
+                r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
+                if (r < 0)
+                        return r;
+        }
+
+        /* Second step: actually set the uids */
+        if (setresuid(uid, uid, uid) < 0)
+                return -errno;
+
+        /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
+         * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
+         * outside of this call. */
+        return 0;
+}
+
+#if HAVE_PAM
+
+static int null_conv(
+                int num_msg,
+                const struct pam_message **msg,
+                struct pam_response **resp,
+                void *appdata_ptr) {
+
+        /* We don't support conversations */
+
+        return PAM_CONV_ERR;
+}
+
+#endif
+
+static int setup_pam(
+                const char *name,
+                const char *user,
+                uid_t uid,
+                gid_t gid,
+                const char *tty,
+                char ***env, /* updated on success */
+                const int fds[], size_t n_fds) {
+
+#if HAVE_PAM
+
+        static const struct pam_conv conv = {
+                .conv = null_conv,
+                .appdata_ptr = NULL
+        };
+
+        _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
+        _cleanup_strv_free_ char **e = NULL;
+        pam_handle_t *handle = NULL;
+        sigset_t old_ss;
+        int pam_code = PAM_SUCCESS, r;
+        bool close_session = false;
+        pid_t pam_pid = 0, parent_pid;
+        int flags = 0;
+
+        assert(name);
+        assert(user);
+        assert(env);
+
+        /* We set up PAM in the parent process, then fork. The child
+         * will then stay around until killed via PR_GET_PDEATHSIG or
+         * systemd via the cgroup logic. It will then remove the PAM
+         * session again. The parent process will exec() the actual
+         * daemon. We do things this way to ensure that the main PID
+         * of the daemon is the one we initially fork()ed. */
+
+        r = barrier_create(&barrier);
+        if (r < 0)
+                goto fail;
+
+        if (log_get_max_level() < LOG_DEBUG)
+                flags |= PAM_SILENT;
+
+        pam_code = pam_start(name, user, &conv, &handle);
+        if (pam_code != PAM_SUCCESS) {
+                handle = NULL;
+                goto fail;
+        }
+
+        if (!tty) {
+                _cleanup_free_ char *q = NULL;
+
+                /* Hmm, so no TTY was explicitly passed, but an fd passed to us directly might be a TTY. Let's figure
+                 * out if that's the case, and read the TTY off it. */
+
+                if (getttyname_malloc(STDIN_FILENO, &q) >= 0)
+                        tty = strjoina("/dev/", q);
+        }
+
+        if (tty) {
+                pam_code = pam_set_item(handle, PAM_TTY, tty);
+                if (pam_code != PAM_SUCCESS)
+                        goto fail;
+        }
+
+        STRV_FOREACH(nv, *env) {
+                pam_code = pam_putenv(handle, *nv);
+                if (pam_code != PAM_SUCCESS)
+                        goto fail;
+        }
+
+        pam_code = pam_acct_mgmt(handle, flags);
+        if (pam_code != PAM_SUCCESS)
+                goto fail;
+
+        pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | flags);
+        if (pam_code != PAM_SUCCESS)
+                log_debug("pam_setcred() failed, ignoring: %s", pam_strerror(handle, pam_code));
+
+        pam_code = pam_open_session(handle, flags);
+        if (pam_code != PAM_SUCCESS)
+                goto fail;
+
+        close_session = true;
+
+        e = pam_getenvlist(handle);
+        if (!e) {
+                pam_code = PAM_BUF_ERR;
+                goto fail;
+        }
+
+        /* Block SIGTERM, so that we know that it won't get lost in the child */
+
+        assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM, -1) >= 0);
+
+        parent_pid = getpid_cached();
+
+        r = safe_fork("(sd-pam)", 0, &pam_pid);
+        if (r < 0)
+                goto fail;
+        if (r == 0) {
+                int sig, ret = EXIT_PAM;
+
+                /* The child's job is to reset the PAM session on termination */
+                barrier_set_role(&barrier, BARRIER_CHILD);
+
+                /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
+                 * those fds are open here that have been opened by PAM. */
+                (void) close_many(fds, n_fds);
+
+                /* Drop privileges - we don't need any to pam_close_session and this will make
+                 * PR_SET_PDEATHSIG work in most cases.  If this fails, ignore the error - but expect sd-pam
+                 * threads to fail to exit normally */
+
+                r = maybe_setgroups(0, NULL);
+                if (r < 0)
+                        log_warning_errno(r, "Failed to setgroups() in sd-pam: %m");
+                if (setresgid(gid, gid, gid) < 0)
+                        log_warning_errno(errno, "Failed to setresgid() in sd-pam: %m");
+                if (setresuid(uid, uid, uid) < 0)
+                        log_warning_errno(errno, "Failed to setresuid() in sd-pam: %m");
+
+                (void) ignore_signals(SIGPIPE);
+
+                /* Wait until our parent died. This will only work if the above setresuid() succeeds,
+                 * otherwise the kernel will not allow unprivileged parents kill their privileged children
+                 * this way. We rely on the control groups kill logic to do the rest for us. */
+                if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
+                        goto child_finish;
+
+                /* Tell the parent that our setup is done. This is especially important regarding dropping
+                 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
+                 *
+                 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
+                (void) barrier_place(&barrier);
+
+                /* Check if our parent process might already have died? */
+                if (getppid() == parent_pid) {
+                        sigset_t ss;
+
+                        assert_se(sigemptyset(&ss) >= 0);
+                        assert_se(sigaddset(&ss, SIGTERM) >= 0);
+
+                        for (;;) {
+                                if (sigwait(&ss, &sig) < 0) {
+                                        if (errno == EINTR)
+                                                continue;
+
+                                        goto child_finish;
+                                }
+
+                                assert(sig == SIGTERM);
+                                break;
+                        }
+                }
+
+                pam_code = pam_setcred(handle, PAM_DELETE_CRED | flags);
+                if (pam_code != PAM_SUCCESS)
+                        goto child_finish;
+
+                /* If our parent died we'll end the session */
+                if (getppid() != parent_pid) {
+                        pam_code = pam_close_session(handle, flags);
+                        if (pam_code != PAM_SUCCESS)
+                                goto child_finish;
+                }
+
+                ret = 0;
+
+        child_finish:
+                /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
+                 * know about this. See pam_end(3) */
+                (void) pam_end(handle, pam_code | flags | PAM_DATA_SILENT);
+                _exit(ret);
+        }
+
+        barrier_set_role(&barrier, BARRIER_PARENT);
+
+        /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
+         * here. */
+        handle = NULL;
+
+        /* Unblock SIGTERM again in the parent */
+        assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
+
+        /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want
+         * this fd around. */
+        closelog();
+
+        /* Synchronously wait for the child to initialize. We don't care for errors as we cannot
+         * recover. However, warn loudly if it happens. */
+        if (!barrier_place_and_sync(&barrier))
+                log_error("PAM initialization failed");
+
+        return strv_free_and_replace(*env, e);
+
+fail:
+        if (pam_code != PAM_SUCCESS) {
+                log_error("PAM failed: %s", pam_strerror(handle, pam_code));
+                r = -EPERM;  /* PAM errors do not map to errno */
+        } else
+                log_error_errno(r, "PAM failed: %m");
+
+        if (handle) {
+                if (close_session)
+                        pam_code = pam_close_session(handle, flags);
+
+                (void) pam_end(handle, pam_code | flags);
+        }
+
+        closelog();
+        return r;
+#else
+        return 0;
+#endif
+}
+
+static void rename_process_from_path(const char *path) {
+        _cleanup_free_ char *buf = NULL;
+        const char *p;
+
+        assert(path);
+
+        /* This resulting string must fit in 10 chars (i.e. the length of "/sbin/init") to look pretty in
+         * /bin/ps */
+
+        if (path_extract_filename(path, &buf) < 0) {
+                rename_process("(...)");
+                return;
+        }
+
+        size_t l = strlen(buf);
+        if (l > 8) {
+                /* The end of the process name is usually more interesting, since the first bit might just be
+                 * "systemd-" */
+                p = buf + l - 8;
+                l = 8;
+        } else
+                p = buf;
+
+        char process_name[11];
+        process_name[0] = '(';
+        memcpy(process_name+1, p, l);
+        process_name[1+l] = ')';
+        process_name[1+l+1] = 0;
+
+        rename_process(process_name);
+}
+
+static bool context_has_address_families(const ExecContext *c) {
+        assert(c);
+
+        return c->address_families_allow_list ||
+                !set_isempty(c->address_families);
+}
+
+static bool context_has_syscall_filters(const ExecContext *c) {
+        assert(c);
+
+        return c->syscall_allow_list ||
+                !hashmap_isempty(c->syscall_filter);
+}
+
+static bool context_has_syscall_logs(const ExecContext *c) {
+        assert(c);
+
+        return c->syscall_log_allow_list ||
+                !hashmap_isempty(c->syscall_log);
+}
+
+static bool context_has_no_new_privileges(const ExecContext *c) {
+        assert(c);
+
+        if (c->no_new_privileges)
+                return true;
+
+        if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
+                return false;
+
+        /* We need NNP if we have any form of seccomp and are unprivileged */
+        return c->lock_personality ||
+                c->memory_deny_write_execute ||
+                c->private_devices ||
+                c->protect_clock ||
+                c->protect_hostname ||
+                c->protect_kernel_tunables ||
+                c->protect_kernel_modules ||
+                c->protect_kernel_logs ||
+                context_has_address_families(c) ||
+                exec_context_restrict_namespaces_set(c) ||
+                c->restrict_realtime ||
+                c->restrict_suid_sgid ||
+                !set_isempty(c->syscall_archs) ||
+                context_has_syscall_filters(c) ||
+                context_has_syscall_logs(c);
+}
+
+#if HAVE_SECCOMP
+
+static bool skip_seccomp_unavailable(const ExecContext *c, const ExecParameters *p, const char* msg) {
+
+        if (is_seccomp_available())
+                return false;
+
+        log_exec_debug(c, p, "SECCOMP features not detected in the kernel, skipping %s", msg);
+        return true;
+}
+
+static int apply_syscall_filter(const ExecContext *c, const ExecParameters *p, bool needs_ambient_hack) {
+        uint32_t negative_action, default_action, action;
+        int r;
+
+        assert(c);
+        assert(p);
+
+        if (!context_has_syscall_filters(c))
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "SystemCallFilter="))
+                return 0;
+
+        negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno);
+
+        if (c->syscall_allow_list) {
+                default_action = negative_action;
+                action = SCMP_ACT_ALLOW;
+        } else {
+                default_action = SCMP_ACT_ALLOW;
+                action = negative_action;
+        }
+
+        if (needs_ambient_hack) {
+                r = seccomp_filter_set_add(c->syscall_filter, c->syscall_allow_list, syscall_filter_sets + SYSCALL_FILTER_SET_SETUID);
+                if (r < 0)
+                        return r;
+        }
+
+        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
+}
+
+static int apply_syscall_log(const ExecContext *c, const ExecParameters *p) {
+#ifdef SCMP_ACT_LOG
+        uint32_t default_action, action;
+#endif
+
+        assert(c);
+        assert(p);
+
+        if (!context_has_syscall_logs(c))
+                return 0;
+
+#ifdef SCMP_ACT_LOG
+        if (skip_seccomp_unavailable(c, p, "SystemCallLog="))
+                return 0;
+
+        if (c->syscall_log_allow_list) {
+                /* Log nothing but the ones listed */
+                default_action = SCMP_ACT_ALLOW;
+                action = SCMP_ACT_LOG;
+        } else {
+                /* Log everything but the ones listed */
+                default_action = SCMP_ACT_LOG;
+                action = SCMP_ACT_ALLOW;
+        }
+
+        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
+#else
+        /* old libseccomp */
+        log_exec_debug(c, p, "SECCOMP feature SCMP_ACT_LOG not available, skipping SystemCallLog=");
+        return 0;
+#endif
+}
+
+static int apply_syscall_archs(const ExecContext *c, const ExecParameters *p) {
+        assert(c);
+        assert(p);
+
+        if (set_isempty(c->syscall_archs))
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "SystemCallArchitectures="))
+                return 0;
+
+        return seccomp_restrict_archs(c->syscall_archs);
+}
+
+static int apply_address_families(const ExecContext *c, const ExecParameters *p) {
+        assert(c);
+        assert(p);
+
+        if (!context_has_address_families(c))
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "RestrictAddressFamilies="))
+                return 0;
+
+        return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
+}
+
+static int apply_memory_deny_write_execute(const ExecContext *c, const ExecParameters *p) {
+        int r;
+
+        assert(c);
+        assert(p);
+
+        if (!c->memory_deny_write_execute)
+                return 0;
+
+        /* use prctl() if kernel supports it (6.3) */
+        r = prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
+        if (r == 0) {
+                log_exec_debug(c, p, "Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
+                return 0;
+        }
+        if (r < 0 && errno != EINVAL)
+                return log_exec_debug_errno(c,
+                                            p,
+                                            errno,
+                                            "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
+        /* else use seccomp */
+        log_exec_debug(c, p, "Kernel doesn't support PR_SET_MDWE: falling back to seccomp");
+
+        if (skip_seccomp_unavailable(c, p, "MemoryDenyWriteExecute="))
+                return 0;
+
+        return seccomp_memory_deny_write_execute();
+}
+
+static int apply_restrict_realtime(const ExecContext *c, const ExecParameters *p) {
+        assert(c);
+        assert(p);
+
+        if (!c->restrict_realtime)
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "RestrictRealtime="))
+                return 0;
+
+        return seccomp_restrict_realtime();
+}
+
+static int apply_restrict_suid_sgid(const ExecContext *c, const ExecParameters *p) {
+        assert(c);
+        assert(p);
+
+        if (!c->restrict_suid_sgid)
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "RestrictSUIDSGID="))
+                return 0;
+
+        return seccomp_restrict_suid_sgid();
+}
+
+static int apply_protect_sysctl(const ExecContext *c, const ExecParameters *p) {
+        assert(c);
+        assert(p);
+
+        /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
+         * let's protect even those systems where this is left on in the kernel. */
+
+        if (!c->protect_kernel_tunables)
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "ProtectKernelTunables="))
+                return 0;
+
+        return seccomp_protect_sysctl();
+}
+
+static int apply_protect_kernel_modules(const ExecContext *c, const ExecParameters *p) {
+        assert(c);
+        assert(p);
+
+        /* Turn off module syscalls on ProtectKernelModules=yes */
+
+        if (!c->protect_kernel_modules)
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "ProtectKernelModules="))
+                return 0;
+
+        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
+}
+
+static int apply_protect_kernel_logs(const ExecContext *c, const ExecParameters *p) {
+        assert(c);
+        assert(p);
+
+        if (!c->protect_kernel_logs)
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "ProtectKernelLogs="))
+                return 0;
+
+        return seccomp_protect_syslog();
+}
+
+static int apply_protect_clock(const ExecContext *c, const ExecParameters *p) {
+        assert(c);
+        assert(p);
+
+        if (!c->protect_clock)
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "ProtectClock="))
+                return 0;
+
+        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
+}
+
+static int apply_private_devices(const ExecContext *c, const ExecParameters *p) {
+        assert(c);
+        assert(p);
+
+        /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
+
+        if (!c->private_devices)
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "PrivateDevices="))
+                return 0;
+
+        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
+}
+
+static int apply_restrict_namespaces(const ExecContext *c, const ExecParameters *p) {
+        assert(c);
+        assert(p);
+
+        if (!exec_context_restrict_namespaces_set(c))
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "RestrictNamespaces="))
+                return 0;
+
+        return seccomp_restrict_namespaces(c->restrict_namespaces);
+}
+
+static int apply_lock_personality(const ExecContext *c, const ExecParameters *p) {
+        unsigned long personality;
+        int r;
+
+        assert(c);
+        assert(p);
+
+        if (!c->lock_personality)
+                return 0;
+
+        if (skip_seccomp_unavailable(c, p, "LockPersonality="))
+                return 0;
+
+        personality = c->personality;
+
+        /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
+        if (personality == PERSONALITY_INVALID) {
+
+                r = opinionated_personality(&personality);
+                if (r < 0)
+                        return r;
+        }
+
+        return seccomp_lock_personality(personality);
+}
+
+#endif
+
+#if HAVE_LIBBPF
+static int apply_restrict_filesystems(const ExecContext *c, const ExecParameters *p) {
+        int r;
+
+        assert(c);
+        assert(p);
+
+        if (!exec_context_restrict_filesystems_set(c))
+                return 0;
+
+        if (p->bpf_outer_map_fd < 0) {
+                /* LSM BPF is unsupported or lsm_bpf_setup failed */
+                log_exec_debug(c, p, "LSM BPF not supported, skipping RestrictFileSystems=");
+                return 0;
+        }
+
+        /* We are in a new binary, so dl-open again */
+        r = dlopen_bpf();
+        if (r < 0)
+                return r;
+
+        return lsm_bpf_restrict_filesystems(c->restrict_filesystems, p->cgroup_id, p->bpf_outer_map_fd, c->restrict_filesystems_allow_list);
+}
+#endif
+
+static int apply_protect_hostname(const ExecContext *c, const ExecParameters *p, int *ret_exit_status) {
+        assert(c);
+        assert(p);
+
+        if (!c->protect_hostname)
+                return 0;
+
+        if (ns_type_supported(NAMESPACE_UTS)) {
+                if (unshare(CLONE_NEWUTS) < 0) {
+                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
+                                *ret_exit_status = EXIT_NAMESPACE;
+                                return log_exec_error_errno(c,
+                                                            p,
+                                                            errno,
+                                                            "Failed to set up UTS namespacing: %m");
+                        }
+
+                        log_exec_warning(c,
+                                         p,
+                                         "ProtectHostname=yes is configured, but UTS namespace setup is "
+                                         "prohibited (container manager?), ignoring namespace setup.");
+                }
+        } else
+                log_exec_warning(c,
+                                 p,
+                                 "ProtectHostname=yes is configured, but the kernel does not "
+                                 "support UTS namespaces, ignoring namespace setup.");
+
+#if HAVE_SECCOMP
+        int r;
+
+        if (skip_seccomp_unavailable(c, p, "ProtectHostname="))
+                return 0;
+
+        r = seccomp_protect_hostname();
+        if (r < 0) {
+                *ret_exit_status = EXIT_SECCOMP;
+                return log_exec_error_errno(c, p, r, "Failed to apply hostname restrictions: %m");
+        }
+#endif
+
+        return 0;
+}
+
+static void do_idle_pipe_dance(int idle_pipe[static 4]) {
+        assert(idle_pipe);
+
+        idle_pipe[1] = safe_close(idle_pipe[1]);
+        idle_pipe[2] = safe_close(idle_pipe[2]);
+
+        if (idle_pipe[0] >= 0) {
+                int r;
+
+                r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
+
+                if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
+                        ssize_t n;
+
+                        /* Signal systemd that we are bored and want to continue. */
+                        n = write(idle_pipe[3], "x", 1);
+                        if (n > 0)
+                                /* Wait for systemd to react to the signal above. */
+                                (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
+                }
+
+                idle_pipe[0] = safe_close(idle_pipe[0]);
+
+        }
+
+        idle_pipe[3] = safe_close(idle_pipe[3]);
+}
+
+static const char *exec_directory_env_name_to_string(ExecDirectoryType t);
+
+/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
+ * the service payload in. */
+static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
+        [EXEC_DIRECTORY_RUNTIME] = "RUNTIME_DIRECTORY",
+        [EXEC_DIRECTORY_STATE] = "STATE_DIRECTORY",
+        [EXEC_DIRECTORY_CACHE] = "CACHE_DIRECTORY",
+        [EXEC_DIRECTORY_LOGS] = "LOGS_DIRECTORY",
+        [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
+};
+
+DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
+
+static int build_environment(
+                const ExecContext *c,
+                const ExecParameters *p,
+                const CGroupContext *cgroup_context,
+                size_t n_fds,
+                char **fdnames,
+                const char *home,
+                const char *username,
+                const char *shell,
+                dev_t journal_stream_dev,
+                ino_t journal_stream_ino,
+                const char *memory_pressure_path,
+                char ***ret) {
+
+        _cleanup_strv_free_ char **our_env = NULL;
+        size_t n_env = 0;
+        char *x;
+        int r;
+
+        assert(c);
+        assert(p);
+        assert(ret);
+
+#define N_ENV_VARS 19
+        our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
+        if (!our_env)
+                return -ENOMEM;
+
+        if (n_fds > 0) {
+                _cleanup_free_ char *joined = NULL;
+
+                if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0)
+                        return -ENOMEM;
+                our_env[n_env++] = x;
+
+                if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0)
+                        return -ENOMEM;
+                our_env[n_env++] = x;
+
+                joined = strv_join(fdnames, ":");
+                if (!joined)
+                        return -ENOMEM;
+
+                x = strjoin("LISTEN_FDNAMES=", joined);
+                if (!x)
+                        return -ENOMEM;
+                our_env[n_env++] = x;
+        }
+
+        if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
+                if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0)
+                        return -ENOMEM;
+                our_env[n_env++] = x;
+
+                if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
+                        return -ENOMEM;
+                our_env[n_env++] = x;
+        }
+
+        /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking
+         * Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and
+         * PID 1 by disabling use of PID1' NSS interface for looking up dynamic users. */
+        if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) {
+                x = strdup("SYSTEMD_NSS_DYNAMIC_BYPASS=1");
+                if (!x)
+                        return -ENOMEM;
+                our_env[n_env++] = x;
+        }
+
+        /* We query "root" if this is a system unit and User= is not specified. $USER is always set. $HOME
+         * could cause problem for e.g. getty, since login doesn't override $HOME, and $LOGNAME and $SHELL don't
+         * really make much sense since we're not logged in. Hence we conditionalize the three based on
+         * SetLoginEnvironment= switch. */
+        if (!c->user && !c->dynamic_user && p->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
+                r = get_fixed_user("root", &username, NULL, NULL, &home, &shell);
+                if (r < 0)
+                        return log_exec_debug_errno(c,
+                                                    p,
+                                                    r,
+                                                    "Failed to determine user credentials for root: %m");
+        }
+
+        bool set_user_login_env = c->set_login_environment >= 0 ? c->set_login_environment : (c->user || c->dynamic_user);
+
+        if (username) {
+                x = strjoin("USER=", username);
+                if (!x)
+                        return -ENOMEM;
+                our_env[n_env++] = x;
+
+                if (set_user_login_env) {
+                        x = strjoin("LOGNAME=", username);
+                        if (!x)
+                                return -ENOMEM;
+                        our_env[n_env++] = x;
+                }
+        }
+
+        if (home && set_user_login_env) {
+                x = strjoin("HOME=", home);
+                if (!x)
+                        return -ENOMEM;
+
+                path_simplify(x + 5);
+                our_env[n_env++] = x;
+        }
+
+        if (shell && set_user_login_env) {
+                x = strjoin("SHELL=", shell);
+                if (!x)
+                        return -ENOMEM;
+
+                path_simplify(x + 6);
+                our_env[n_env++] = x;
+        }
+
+        if (!sd_id128_is_null(p->invocation_id)) {
+                assert(p->invocation_id_string);
+
+                x = strjoin("INVOCATION_ID=", p->invocation_id_string);
+                if (!x)
+                        return -ENOMEM;
+
+                our_env[n_env++] = x;
+        }
+
+        if (exec_context_needs_term(c)) {
+                _cleanup_free_ char *cmdline = NULL;
+                const char *tty_path, *term = NULL;
+
+                tty_path = exec_context_tty_path(c);
+
+                /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try
+                 * to inherit the $TERM set for PID 1. This is useful for containers so that the $TERM the
+                 * container manager passes to PID 1 ends up all the way in the console login shown. */
+
+                if (path_equal_ptr(tty_path, "/dev/console") && getppid() == 1)
+                        term = getenv("TERM");
+                else if (tty_path && in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
+                        _cleanup_free_ char *key = NULL;
+
+                        key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
+                        if (!key)
+                                return -ENOMEM;
+
+                        r = proc_cmdline_get_key(key, 0, &cmdline);
+                        if (r < 0)
+                                log_exec_debug_errno(c,
+                                                     p,
+                                                     r,
+                                                     "Failed to read %s from kernel cmdline, ignoring: %m",
+                                                     key);
+                        else if (r > 0)
+                                term = cmdline;
+                }
+
+                if (!term)
+                        term = default_term_for_tty(tty_path);
+
+                x = strjoin("TERM=", term);
+                if (!x)
+                        return -ENOMEM;
+                our_env[n_env++] = x;
+        }
+
+        if (journal_stream_dev != 0 && journal_stream_ino != 0) {
+                if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
+                        return -ENOMEM;
+
+                our_env[n_env++] = x;
+        }
+
+        if (c->log_namespace) {
+                x = strjoin("LOG_NAMESPACE=", c->log_namespace);
+                if (!x)
+                        return -ENOMEM;
+
+                our_env[n_env++] = x;
+        }
+
+        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
+                _cleanup_free_ char *joined = NULL;
+                const char *n;
+
+                if (!p->prefix[t])
+                        continue;
+
+                if (c->directories[t].n_items == 0)
+                        continue;
+
+                n = exec_directory_env_name_to_string(t);
+                if (!n)
+                        continue;
+
+                for (size_t i = 0; i < c->directories[t].n_items; i++) {
+                        _cleanup_free_ char *prefixed = NULL;
+
+                        prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
+                        if (!prefixed)
+                                return -ENOMEM;
+
+                        if (!strextend_with_separator(&joined, ":", prefixed))
+                                return -ENOMEM;
+                }
+
+                x = strjoin(n, "=", joined);
+                if (!x)
+                        return -ENOMEM;
+
+                our_env[n_env++] = x;
+        }
+
+        _cleanup_free_ char *creds_dir = NULL;
+        r = exec_context_get_credential_directory(c, p, p->unit_id, &creds_dir);
+        if (r < 0)
+                return r;
+        if (r > 0) {
+                x = strjoin("CREDENTIALS_DIRECTORY=", creds_dir);
+                if (!x)
+                        return -ENOMEM;
+
+                our_env[n_env++] = x;
+        }
+
+        if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
+                return -ENOMEM;
+
+        our_env[n_env++] = x;
+
+        if (memory_pressure_path) {
+                x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
+                if (!x)
+                        return -ENOMEM;
+
+                our_env[n_env++] = x;
+
+                if (cgroup_context && !path_equal(memory_pressure_path, "/dev/null")) {
+                        _cleanup_free_ char *b = NULL, *e = NULL;
+
+                        if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
+                                     MEMORY_PRESSURE_DEFAULT_TYPE,
+                                     cgroup_context->memory_pressure_threshold_usec == USEC_INFINITY ? MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC :
+                                     CLAMP(cgroup_context->memory_pressure_threshold_usec, 1U, MEMORY_PRESSURE_DEFAULT_WINDOW_USEC),
+                                     MEMORY_PRESSURE_DEFAULT_WINDOW_USEC) < 0)
+                                return -ENOMEM;
+
+                        if (base64mem(b, strlen(b) + 1, &e) < 0)
+                                return -ENOMEM;
+
+                        x = strjoin("MEMORY_PRESSURE_WRITE=", e);
+                        if (!x)
+                                return -ENOMEM;
+
+                        our_env[n_env++] = x;
+                }
+        }
+
+        assert(n_env < N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
+#undef N_ENV_VARS
+
+        *ret = TAKE_PTR(our_env);
+
+        return 0;
+}
+
+static int build_pass_environment(const ExecContext *c, char ***ret) {
+        _cleanup_strv_free_ char **pass_env = NULL;
+        size_t n_env = 0;
+
+        STRV_FOREACH(i, c->pass_environment) {
+                _cleanup_free_ char *x = NULL;
+                char *v;
+
+                v = getenv(*i);
+                if (!v)
+                        continue;
+                x = strjoin(*i, "=", v);
+                if (!x)
+                        return -ENOMEM;
+
+                if (!GREEDY_REALLOC(pass_env, n_env + 2))
+                        return -ENOMEM;
+
+                pass_env[n_env++] = TAKE_PTR(x);
+                pass_env[n_env] = NULL;
+        }
+
+        *ret = TAKE_PTR(pass_env);
+
+        return 0;
+}
+
+static int setup_private_users(uid_t ouid, gid_t ogid, uid_t uid, gid_t gid) {
+        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
+        _cleanup_close_pair_ int errno_pipe[2] = PIPE_EBADF;
+        _cleanup_close_ int unshare_ready_fd = -EBADF;
+        _cleanup_(sigkill_waitp) pid_t pid = 0;
+        uint64_t c = 1;
+        ssize_t n;
+        int r;
+
+        /* Set up a user namespace and map the original UID/GID (IDs from before any user or group changes, i.e.
+         * the IDs from the user or system manager(s)) to itself, the selected UID/GID to itself, and everything else to
+         * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
+         * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
+         * which waits for the parent to create the new user namespace while staying in the original namespace. The
+         * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
+         * continues execution normally.
+         * For unprivileged users (i.e. without capabilities), the root to root mapping is excluded. As such, it
+         * does not need CAP_SETUID to write the single line mapping to itself. */
+
+        /* Can only set up multiple mappings with CAP_SETUID. */
+        if (have_effective_cap(CAP_SETUID) > 0 && uid != ouid && uid_is_valid(uid))
+                r = asprintf(&uid_map,
+                             UID_FMT " " UID_FMT " 1\n"     /* Map $OUID → $OUID */
+                             UID_FMT " " UID_FMT " 1\n",    /* Map $UID → $UID */
+                             ouid, ouid, uid, uid);
+        else
+                r = asprintf(&uid_map,
+                             UID_FMT " " UID_FMT " 1\n",    /* Map $OUID → $OUID */
+                             ouid, ouid);
+
+        if (r < 0)
+                return -ENOMEM;
+
+        /* Can only set up multiple mappings with CAP_SETGID. */
+        if (have_effective_cap(CAP_SETGID) > 0 && gid != ogid && gid_is_valid(gid))
+                r = asprintf(&gid_map,
+                             GID_FMT " " GID_FMT " 1\n"     /* Map $OGID → $OGID */
+                             GID_FMT " " GID_FMT " 1\n",    /* Map $GID → $GID */
+                             ogid, ogid, gid, gid);
+        else
+                r = asprintf(&gid_map,
+                             GID_FMT " " GID_FMT " 1\n",    /* Map $OGID -> $OGID */
+                             ogid, ogid);
+
+        if (r < 0)
+                return -ENOMEM;
+
+        /* Create a communication channel so that the parent can tell the child when it finished creating the user
+         * namespace. */
+        unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
+        if (unshare_ready_fd < 0)
+                return -errno;
+
+        /* Create a communication channel so that the child can tell the parent a proper error code in case it
+         * failed. */
+        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
+                return -errno;
+
+        r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &pid);
+        if (r < 0)
+                return r;
+        if (r == 0) {
+                _cleanup_close_ int fd = -EBADF;
+                const char *a;
+                pid_t ppid;
+
+                /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
+                 * here, after the parent opened its own user namespace. */
+
+                ppid = getppid();
+                errno_pipe[0] = safe_close(errno_pipe[0]);
+
+                /* Wait until the parent unshared the user namespace */
+                if (read(unshare_ready_fd, &c, sizeof(c)) < 0) {
+                        r = -errno;
+                        goto child_fail;
+                }
+
+                /* Disable the setgroups() system call in the child user namespace, for good. */
+                a = procfs_file_alloca(ppid, "setgroups");
+                fd = open(a, O_WRONLY|O_CLOEXEC);
+                if (fd < 0) {
+                        if (errno != ENOENT) {
+                                r = -errno;
+                                goto child_fail;
+                        }
+
+                        /* If the file is missing the kernel is too old, let's continue anyway. */
+                } else {
+                        if (write(fd, "deny\n", 5) < 0) {
+                                r = -errno;
+                                goto child_fail;
+                        }
+
+                        fd = safe_close(fd);
+                }
+
+                /* First write the GID map */
+                a = procfs_file_alloca(ppid, "gid_map");
+                fd = open(a, O_WRONLY|O_CLOEXEC);
+                if (fd < 0) {
+                        r = -errno;
+                        goto child_fail;
+                }
+                if (write(fd, gid_map, strlen(gid_map)) < 0) {
+                        r = -errno;
+                        goto child_fail;
+                }
+                fd = safe_close(fd);
+
+                /* The write the UID map */
+                a = procfs_file_alloca(ppid, "uid_map");
+                fd = open(a, O_WRONLY|O_CLOEXEC);
+                if (fd < 0) {
+                        r = -errno;
+                        goto child_fail;
+                }
+                if (write(fd, uid_map, strlen(uid_map)) < 0) {
+                        r = -errno;
+                        goto child_fail;
+                }
+
+                _exit(EXIT_SUCCESS);
+
+        child_fail:
+                (void) write(errno_pipe[1], &r, sizeof(r));
+                _exit(EXIT_FAILURE);
+        }
+
+        errno_pipe[1] = safe_close(errno_pipe[1]);
+
+        if (unshare(CLONE_NEWUSER) < 0)
+                return -errno;
+
+        /* Let the child know that the namespace is ready now */
+        if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
+                return -errno;
+
+        /* Try to read an error code from the child */
+        n = read(errno_pipe[0], &r, sizeof(r));
+        if (n < 0)
+                return -errno;
+        if (n == sizeof(r)) { /* an error code was sent to us */
+                if (r < 0)
+                        return r;
+                return -EIO;
+        }
+        if (n != 0) /* on success we should have read 0 bytes */
+                return -EIO;
+
+        r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
+        if (r < 0)
+                return r;
+        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
+                return -EIO;
+
+        return 0;
+}
+
+static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
+        _cleanup_free_ char *src_abs = NULL;
+        int r;
+
+        assert(source);
+
+        src_abs = path_join(root, source);
+        if (!src_abs)
+                return -ENOMEM;
+
+        STRV_FOREACH(dst, symlinks) {
+                _cleanup_free_ char *dst_abs = NULL;
+
+                dst_abs = path_join(root, *dst);
+                if (!dst_abs)
+                        return -ENOMEM;
+
+                r = mkdir_parents_label(dst_abs, 0755);
+                if (r < 0)
+                        return r;
+
+                r = symlink_idempotent(src_abs, dst_abs, true);
+                if (r < 0)
+                        return r;
+        }
+
+        return 0;
+}
+
+static int setup_exec_directory(
+                const ExecContext *context,
+                const ExecParameters *params,
+                uid_t uid,
+                gid_t gid,
+                ExecDirectoryType type,
+                bool needs_mount_namespace,
+                int *exit_status) {
+
+        static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
+                [EXEC_DIRECTORY_RUNTIME] = EXIT_RUNTIME_DIRECTORY,
+                [EXEC_DIRECTORY_STATE] = EXIT_STATE_DIRECTORY,
+                [EXEC_DIRECTORY_CACHE] = EXIT_CACHE_DIRECTORY,
+                [EXEC_DIRECTORY_LOGS] = EXIT_LOGS_DIRECTORY,
+                [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
+        };
+        int r;
+
+        assert(context);
+        assert(params);
+        assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
+        assert(exit_status);
+
+        if (!params->prefix[type])
+                return 0;
+
+        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
+                if (!uid_is_valid(uid))
+                        uid = 0;
+                if (!gid_is_valid(gid))
+                        gid = 0;
+        }
+
+        for (size_t i = 0; i < context->directories[type].n_items; i++) {
+                _cleanup_free_ char *p = NULL, *pp = NULL;
+
+                p = path_join(params->prefix[type], context->directories[type].items[i].path);
+                if (!p) {
+                        r = -ENOMEM;
+                        goto fail;
+                }
+
+                r = mkdir_parents_label(p, 0755);
+                if (r < 0)
+                        goto fail;
+
+                if (IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_LOGS) && params->runtime_scope == RUNTIME_SCOPE_USER) {
+
+                        /* If we are in user mode, and a configuration directory exists but a state directory
+                         * doesn't exist, then we likely are upgrading from an older systemd version that
+                         * didn't know the more recent addition to the xdg-basedir spec: the $XDG_STATE_HOME
+                         * directory. In older systemd versions EXEC_DIRECTORY_STATE was aliased to
+                         * EXEC_DIRECTORY_CONFIGURATION, with the advent of $XDG_STATE_HOME is is now
+                         * separated. If a service has both dirs configured but only the configuration dir
+                         * exists and the state dir does not, we assume we are looking at an update
+                         * situation. Hence, create a compatibility symlink, so that all expectations are
+                         * met.
+                         *
+                         * (We also do something similar with the log directory, which still doesn't exist in
+                         * the xdg basedir spec. We'll make it a subdir of the state dir.) */
+
+                        /* this assumes the state dir is always created before the configuration dir */
+                        assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
+                        assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
+
+                        r = laccess(p, F_OK);
+                        if (r == -ENOENT) {
+                                _cleanup_free_ char *q = NULL;
+
+                                /* OK, we know that the state dir does not exist. Let's see if the dir exists
+                                 * under the configuration hierarchy. */
+
+                                if (type == EXEC_DIRECTORY_STATE)
+                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], context->directories[type].items[i].path);
+                                else if (type == EXEC_DIRECTORY_LOGS)
+                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", context->directories[type].items[i].path);
+                                else
+                                        assert_not_reached();
+                                if (!q) {
+                                        r = -ENOMEM;
+                                        goto fail;
+                                }
+
+                                r = laccess(q, F_OK);
+                                if (r >= 0) {
+                                        /* It does exist! This hence looks like an update. Symlink the
+                                         * configuration directory into the state directory. */
+
+                                        r = symlink_idempotent(q, p, /* make_relative= */ true);
+                                        if (r < 0)
+                                                goto fail;
+
+                                        log_exec_notice(context, params, "Unit state directory %s missing but matching configuration directory %s exists, assuming update from systemd 253 or older, creating compatibility symlink.", p, q);
+                                        continue;
+                                } else if (r != -ENOENT)
+                                        log_exec_warning_errno(context, params, r, "Unable to detect whether unit configuration directory '%s' exists, assuming not: %m", q);
+
+                        } else if (r < 0)
+                                log_exec_warning_errno(context, params, r, "Unable to detect whether unit state directory '%s' is missing, assuming it is: %m", p);
+                }
+
+                if (exec_directory_is_private(context, type)) {
+                        /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
+                         * case we want to avoid leaving a directory around fully accessible that is owned by
+                         * a dynamic user whose UID is later on reused. To lock this down we use the same
+                         * trick used by container managers to prohibit host users to get access to files of
+                         * the same UID in containers: we place everything inside a directory that has an
+                         * access mode of 0700 and is owned root:root, so that it acts as security boundary
+                         * for unprivileged host code. We then use fs namespacing to make this directory
+                         * permeable for the service itself.
+                         *
+                         * Specifically: for a service which wants a special directory "foo/" we first create
+                         * a directory "private/" with access mode 0700 owned by root:root. Then we place
+                         * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
+                         * "private/foo". This way, privileged host users can access "foo/" as usual, but
+                         * unprivileged host users can't look into it. Inside of the namespace of the unit
+                         * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
+                         * "private/foo/" is mounted under the same name, thus disabling the access boundary
+                         * for the service and making sure it only gets access to the dirs it needs but no
+                         * others. Tricky? Yes, absolutely, but it works!
+                         *
+                         * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
+                         * to be owned by the service itself.
+                         *
+                         * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
+                         * for sharing files or sockets with other services. */
+
+                        pp = path_join(params->prefix[type], "private");
+                        if (!pp) {
+                                r = -ENOMEM;
+                                goto fail;
+                        }
+
+                        /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
+                        r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
+                        if (r < 0)
+                                goto fail;
+
+                        if (!path_extend(&pp, context->directories[type].items[i].path)) {
+                                r = -ENOMEM;
+                                goto fail;
+                        }
+
+                        /* Create all directories between the configured directory and this private root, and mark them 0755 */
+                        r = mkdir_parents_label(pp, 0755);
+                        if (r < 0)
+                                goto fail;
+
+                        if (is_dir(p, false) > 0 &&
+                            (laccess(pp, F_OK) == -ENOENT)) {
+
+                                /* Hmm, the private directory doesn't exist yet, but the normal one exists? If so, move
+                                 * it over. Most likely the service has been upgraded from one that didn't use
+                                 * DynamicUser=1, to one that does. */
+
+                                log_exec_info(context,
+                                              params,
+                                              "Found pre-existing public %s= directory %s, migrating to %s.\n"
+                                              "Apparently, service previously had DynamicUser= turned off, and has now turned it on.",
+                                              exec_directory_type_to_string(type), p, pp);
+
+                                r = RET_NERRNO(rename(p, pp));
+                                if (r < 0)
+                                        goto fail;
+                        } else {
+                                /* Otherwise, create the actual directory for the service */
+
+                                r = mkdir_label(pp, context->directories[type].mode);
+                                if (r < 0 && r != -EEXIST)
+                                        goto fail;
+                        }
+
+                        if (!context->directories[type].items[i].only_create) {
+                                /* And link it up from the original place.
+                                 * Notes
+                                 * 1) If a mount namespace is going to be used, then this symlink remains on
+                                 *    the host, and a new one for the child namespace will be created later.
+                                 * 2) It is not necessary to create this symlink when one of its parent
+                                 *    directories is specified and already created. E.g.
+                                 *        StateDirectory=foo foo/bar
+                                 *    In that case, the inode points to pp and p for "foo/bar" are the same:
+                                 *        pp = "/var/lib/private/foo/bar"
+                                 *        p = "/var/lib/foo/bar"
+                                 *    and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
+                                 *    we do not need to create the symlink, but we cannot create the symlink.
+                                 *    See issue #24783. */
+                                r = symlink_idempotent(pp, p, true);
+                                if (r < 0)
+                                        goto fail;
+                        }
+
+                } else {
+                        _cleanup_free_ char *target = NULL;
+
+                        if (type != EXEC_DIRECTORY_CONFIGURATION &&
+                            readlink_and_make_absolute(p, &target) >= 0) {
+                                _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
+
+                                /* This already exists and is a symlink? Interesting. Maybe it's one created
+                                 * by DynamicUser=1 (see above)?
+                                 *
+                                 * We do this for all directory types except for ConfigurationDirectory=,
+                                 * since they all support the private/ symlink logic at least in some
+                                 * configurations, see above. */
+
+                                r = chase(target, NULL, 0, &target_resolved, NULL);
+                                if (r < 0)
+                                        goto fail;
+
+                                q = path_join(params->prefix[type], "private", context->directories[type].items[i].path);
+                                if (!q) {
+                                        r = -ENOMEM;
+                                        goto fail;
+                                }
+
+                                /* /var/lib or friends may be symlinks. So, let's chase them also. */
+                                r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
+                                if (r < 0)
+                                        goto fail;
+
+                                if (path_equal(q_resolved, target_resolved)) {
+
+                                        /* Hmm, apparently DynamicUser= was once turned on for this service,
+                                         * but is no longer. Let's move the directory back up. */
+
+                                        log_exec_info(context,
+                                                      params,
+                                                      "Found pre-existing private %s= directory %s, migrating to %s.\n"
+                                                      "Apparently, service previously had DynamicUser= turned on, and has now turned it off.",
+                                                      exec_directory_type_to_string(type), q, p);
+
+                                        r = RET_NERRNO(unlink(p));
+                                        if (r < 0)
+                                                goto fail;
+
+                                        r = RET_NERRNO(rename(q, p));
+                                        if (r < 0)
+                                                goto fail;
+                                }
+                        }
+
+                        r = mkdir_label(p, context->directories[type].mode);
+                        if (r < 0) {
+                                if (r != -EEXIST)
+                                        goto fail;
+
+                                if (type == EXEC_DIRECTORY_CONFIGURATION) {
+                                        struct stat st;
+
+                                        /* Don't change the owner/access mode of the configuration directory,
+                                         * as in the common case it is not written to by a service, and shall
+                                         * not be writable. */
+
+                                        r = RET_NERRNO(stat(p, &st));
+                                        if (r < 0)
+                                                goto fail;
+
+                                        /* Still complain if the access mode doesn't match */
+                                        if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
+                                                log_exec_warning(context,
+                                                                 params,
+                                                                 "%s \'%s\' already exists but the mode is different. "
+                                                                 "(File system: %o %sMode: %o)",
+                                                                 exec_directory_type_to_string(type), context->directories[type].items[i].path,
+                                                                 st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
+
+                                        continue;
+                                }
+                        }
+                }
+
+                /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
+                 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
+                 * current UID/GID ownership.) */
+                r = chmod_and_chown(pp ?: p, context->directories[type].mode, UID_INVALID, GID_INVALID);
+                if (r < 0)
+                        goto fail;
+
+                /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
+                 * available to user code anyway */
+                if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
+                        continue;
+
+                /* Then, change the ownership of the whole tree, if necessary. When dynamic users are used we
+                 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
+                 * assignments to exist. */
+                r = path_chown_recursive(pp ?: p, uid, gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
+                if (r < 0)
+                        goto fail;
+        }
+
+        /* If we are not going to run in a namespace, set up the symlinks - otherwise
+         * they are set up later, to allow configuring empty var/run/etc. */
+        if (!needs_mount_namespace)
+                for (size_t i = 0; i < context->directories[type].n_items; i++) {
+                        r = create_many_symlinks(params->prefix[type],
+                                                 context->directories[type].items[i].path,
+                                                 context->directories[type].items[i].symlinks);
+                        if (r < 0)
+                                goto fail;
+                }
+
+        return 0;
+
+fail:
+        *exit_status = exit_status_table[type];
+        return r;
+}
+
+#if ENABLE_SMACK
+static int setup_smack(
+                const ExecParameters *params,
+                const ExecContext *context,
+                int executable_fd) {
+        int r;
+
+        assert(params);
+        assert(executable_fd >= 0);
+
+        if (context->smack_process_label) {
+                r = mac_smack_apply_pid(0, context->smack_process_label);
+                if (r < 0)
+                        return r;
+        } else if (params->fallback_smack_process_label) {
+                _cleanup_free_ char *exec_label = NULL;
+
+                r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
+                if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
+                        return r;
+
+                r = mac_smack_apply_pid(0, exec_label ?: params->fallback_smack_process_label);
+                if (r < 0)
+                        return r;
+        }
+
+        return 0;
+}
+#endif
+
+static int compile_bind_mounts(
+                const ExecContext *context,
+                const ExecParameters *params,
+                BindMount **ret_bind_mounts,
+                size_t *ret_n_bind_mounts,
+                char ***ret_empty_directories) {
+
+        _cleanup_strv_free_ char **empty_directories = NULL;
+        BindMount *bind_mounts = NULL;
+        size_t n, h = 0;
+        int r;
+
+        assert(context);
+        assert(params);
+        assert(ret_bind_mounts);
+        assert(ret_n_bind_mounts);
+        assert(ret_empty_directories);
+
+        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
+
+        n = context->n_bind_mounts;
+        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
+                if (!params->prefix[t])
+                        continue;
+
+                for (size_t i = 0; i < context->directories[t].n_items; i++)
+                        n += !context->directories[t].items[i].only_create;
+        }
+
+        if (n <= 0) {
+                *ret_bind_mounts = NULL;
+                *ret_n_bind_mounts = 0;
+                *ret_empty_directories = NULL;
+                return 0;
+        }
+
+        bind_mounts = new(BindMount, n);
+        if (!bind_mounts)
+                return -ENOMEM;
+
+        for (size_t i = 0; i < context->n_bind_mounts; i++) {
+                BindMount *item = context->bind_mounts + i;
+                _cleanup_free_ char *s = NULL, *d = NULL;
+
+                s = strdup(item->source);
+                if (!s)
+                        return -ENOMEM;
+
+                d = strdup(item->destination);
+                if (!d)
+                        return -ENOMEM;
+
+                bind_mounts[h++] = (BindMount) {
+                        .source = TAKE_PTR(s),
+                        .destination = TAKE_PTR(d),
+                        .read_only = item->read_only,
+                        .recursive = item->recursive,
+                        .ignore_enoent = item->ignore_enoent,
+                };
+        }
+
+        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
+                if (!params->prefix[t])
+                        continue;
+
+                if (context->directories[t].n_items == 0)
+                        continue;
+
+                if (exec_directory_is_private(context, t) &&
+                    !exec_context_with_rootfs(context)) {
+                        char *private_root;
+
+                        /* So this is for a dynamic user, and we need to make sure the process can access its own
+                         * directory. For that we overmount the usually inaccessible "private" subdirectory with a
+                         * tmpfs that makes it accessible and is empty except for the submounts we do this for. */
+
+                        private_root = path_join(params->prefix[t], "private");
+                        if (!private_root)
+                                return -ENOMEM;
+
+                        r = strv_consume(&empty_directories, private_root);
+                        if (r < 0)
+                                return r;
+                }
+
+                for (size_t i = 0; i < context->directories[t].n_items; i++) {
+                        _cleanup_free_ char *s = NULL, *d = NULL;
+
+                        /* When one of the parent directories is in the list, we cannot create the symlink
+                         * for the child directory. See also the comments in setup_exec_directory(). */
+                        if (context->directories[t].items[i].only_create)
+                                continue;
+
+                        if (exec_directory_is_private(context, t))
+                                s = path_join(params->prefix[t], "private", context->directories[t].items[i].path);
+                        else
+                                s = path_join(params->prefix[t], context->directories[t].items[i].path);
+                        if (!s)
+                                return -ENOMEM;
+
+                        if (exec_directory_is_private(context, t) &&
+                            exec_context_with_rootfs(context))
+                                /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
+                                 * directory is not created on the root directory. So, let's bind-mount the directory
+                                 * on the 'non-private' place. */
+                                d = path_join(params->prefix[t], context->directories[t].items[i].path);
+                        else
+                                d = strdup(s);
+                        if (!d)
+                                return -ENOMEM;
+
+                        bind_mounts[h++] = (BindMount) {
+                                .source = TAKE_PTR(s),
+                                .destination = TAKE_PTR(d),
+                                .read_only = false,
+                                .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
+                                .recursive = true,
+                                .ignore_enoent = false,
+                        };
+                }
+        }
+
+        assert(h == n);
+
+        *ret_bind_mounts = TAKE_PTR(bind_mounts);
+        *ret_n_bind_mounts = n;
+        *ret_empty_directories = TAKE_PTR(empty_directories);
+
+        return (int) n;
+}
+
+/* ret_symlinks will contain a list of pairs src:dest that describes
+ * the symlinks to create later on. For example, the symlinks needed
+ * to safely give private directories to DynamicUser=1 users. */
+static int compile_symlinks(
+                const ExecContext *context,
+                const ExecParameters *params,
+                bool setup_os_release_symlink,
+                char ***ret_symlinks) {
+
+        _cleanup_strv_free_ char **symlinks = NULL;
+        int r;
+
+        assert(context);
+        assert(params);
+        assert(ret_symlinks);
+
+        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
+                for (size_t i = 0; i < context->directories[dt].n_items; i++) {
+                        _cleanup_free_ char *private_path = NULL, *path = NULL;
+
+                        STRV_FOREACH(symlink, context->directories[dt].items[i].symlinks) {
+                                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
+
+                                src_abs = path_join(params->prefix[dt], context->directories[dt].items[i].path);
+                                dst_abs = path_join(params->prefix[dt], *symlink);
+                                if (!src_abs || !dst_abs)
+                                        return -ENOMEM;
+
+                                r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
+                                if (r < 0)
+                                        return r;
+                        }
+
+                        if (!exec_directory_is_private(context, dt) ||
+                            exec_context_with_rootfs(context) ||
+                            context->directories[dt].items[i].only_create)
+                                continue;
+
+                        private_path = path_join(params->prefix[dt], "private", context->directories[dt].items[i].path);
+                        if (!private_path)
+                                return -ENOMEM;
+
+                        path = path_join(params->prefix[dt], context->directories[dt].items[i].path);
+                        if (!path)
+                                return -ENOMEM;
+
+                        r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
+                        if (r < 0)
+                                return r;
+                }
+        }
+
+        /* We make the host's os-release available via a symlink, so that we can copy it atomically
+         * and readers will never get a half-written version. Note that, while the paths specified here are
+         * absolute, when they are processed in namespace.c they will be made relative automatically, i.e.:
+         * 'os-release -> .os-release-stage/os-release' is what will be created. */
+        if (setup_os_release_symlink) {
+                r = strv_extend(&symlinks, "/run/host/.os-release-stage/os-release");
+                if (r < 0)
+                        return r;
+
+                r = strv_extend(&symlinks, "/run/host/os-release");
+                if (r < 0)
+                        return r;
+        }
+
+        *ret_symlinks = TAKE_PTR(symlinks);
+
+        return 0;
+}
+
+static bool insist_on_sandboxing(
+                const ExecContext *context,
+                const char *root_dir,
+                const char *root_image,
+                const BindMount *bind_mounts,
+                size_t n_bind_mounts) {
+
+        assert(context);
+        assert(n_bind_mounts == 0 || bind_mounts);
+
+        /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that
+         * would alter the view on the file system beyond making things read-only or invisible, i.e. would
+         * rearrange stuff in a way we cannot ignore gracefully. */
+
+        if (context->n_temporary_filesystems > 0)
+                return true;
+
+        if (root_dir || root_image)
+                return true;
+
+        if (context->n_mount_images > 0)
+                return true;
+
+        if (context->dynamic_user)
+                return true;
+
+        if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
+                return true;
+
+        /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
+         * essential. */
+        for (size_t i = 0; i < n_bind_mounts; i++)
+                if (!path_equal(bind_mounts[i].source, bind_mounts[i].destination))
+                        return true;
+
+        if (context->log_namespace)
+                return true;
+
+        return false;
+}
+
+static int setup_ephemeral(const ExecContext *context, ExecRuntime *runtime) {
+        _cleanup_close_ int fd = -EBADF;
+        int r;
+
+        if (!runtime || !runtime->ephemeral_copy)
+                return 0;
+
+        r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
+
+        CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
+
+        fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
+        if (fd >= 0)
+                /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
+                return 0;
+
+        if (fd != -EAGAIN)
+                return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
+
+        log_debug("Making ephemeral snapshot of %s to %s",
+                  context->root_image ?: context->root_directory, runtime->ephemeral_copy);
+
+        if (context->root_image)
+                fd = copy_file(context->root_image, runtime->ephemeral_copy, O_EXCL, 0600,
+                               COPY_LOCK_BSD|COPY_REFLINK|COPY_CRTIME);
+        else
+                fd = btrfs_subvol_snapshot_at(AT_FDCWD, context->root_directory,
+                                              AT_FDCWD, runtime->ephemeral_copy,
+                                              BTRFS_SNAPSHOT_FALLBACK_COPY |
+                                              BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
+                                              BTRFS_SNAPSHOT_RECURSIVE |
+                                              BTRFS_SNAPSHOT_LOCK_BSD);
+        if (fd < 0)
+                return log_debug_errno(fd, "Failed to snapshot %s to %s: %m",
+                                       context->root_image ?: context->root_directory, runtime->ephemeral_copy);
+
+        if (context->root_image) {
+                /* A root image might be subject to lots of random writes so let's try to disable COW on it
+                 * which tends to not perform well in combination with lots of random writes.
+                 *
+                 * Note: btrfs actually isn't impressed by us setting the flag after making the reflink'ed
+                 * copy, but we at least want to make the intention clear.
+                 */
+                r = chattr_fd(fd, FS_NOCOW_FL, FS_NOCOW_FL, NULL);
+                if (r < 0)
+                        log_debug_errno(fd, "Failed to disable copy-on-write for %s, ignoring: %m", runtime->ephemeral_copy);
+        }
+
+        r = send_one_fd(runtime->ephemeral_storage_socket[1], fd, MSG_DONTWAIT);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to queue file descriptor on ephemeral storage socket: %m");
+
+        return 1;
+}
+
+static int verity_settings_prepare(
+                VeritySettings *verity,
+                const char *root_image,
+                const void *root_hash,
+                size_t root_hash_size,
+                const char *root_hash_path,
+                const void *root_hash_sig,
+                size_t root_hash_sig_size,
+                const char *root_hash_sig_path,
+                const char *verity_data_path) {
+
+        int r;
+
+        assert(verity);
+
+        if (root_hash) {
+                void *d;
+
+                d = memdup(root_hash, root_hash_size);
+                if (!d)
+                        return -ENOMEM;
+
+                free_and_replace(verity->root_hash, d);
+                verity->root_hash_size = root_hash_size;
+                verity->designator = PARTITION_ROOT;
+        }
+
+        if (root_hash_sig) {
+                void *d;
+
+                d = memdup(root_hash_sig, root_hash_sig_size);
+                if (!d)
+                        return -ENOMEM;
+
+                free_and_replace(verity->root_hash_sig, d);
+                verity->root_hash_sig_size = root_hash_sig_size;
+                verity->designator = PARTITION_ROOT;
+        }
+
+        if (verity_data_path) {
+                r = free_and_strdup(&verity->data_path, verity_data_path);
+                if (r < 0)
+                        return r;
+        }
+
+        r = verity_settings_load(
+                        verity,
+                        root_image,
+                        root_hash_path,
+                        root_hash_sig_path);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to load root hash: %m");
+
+        return 0;
+}
+
+static int apply_mount_namespace(
+                ExecCommandFlags command_flags,
+                const ExecContext *context,
+                const ExecParameters *params,
+                ExecRuntime *runtime,
+                const char *memory_pressure_path,
+                char **error_path) {
+
+        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
+        _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
+                        **read_write_paths_cleanup = NULL;
+        _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
+                        *extension_dir = NULL, *host_os_release_stage = NULL;
+        const char *root_dir = NULL, *root_image = NULL, *tmp_dir = NULL, *var_tmp_dir = NULL;
+        char **read_write_paths;
+        bool needs_sandboxing, setup_os_release_symlink;
+        BindMount *bind_mounts = NULL;
+        size_t n_bind_mounts = 0;
+        int r;
+
+        assert(context);
+
+        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
+
+        if (params->flags & EXEC_APPLY_CHROOT) {
+                r = setup_ephemeral(context, runtime);
+                if (r < 0)
+                        return r;
+
+                if (context->root_image)
+                        root_image = (runtime ? runtime->ephemeral_copy : NULL) ?: context->root_image;
+                else
+                        root_dir = (runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory;
+        }
+
+        r = compile_bind_mounts(context, params, &bind_mounts, &n_bind_mounts, &empty_directories);
+        if (r < 0)
+                return r;
+
+        /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
+         * service will need to write to it in order to start the notifications. */
+        if (context->protect_control_groups && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
+                read_write_paths_cleanup = strv_copy(context->read_write_paths);
+                if (!read_write_paths_cleanup)
+                        return -ENOMEM;
+
+                r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
+                if (r < 0)
+                        return r;
+
+                read_write_paths = read_write_paths_cleanup;
+        } else
+                read_write_paths = context->read_write_paths;
+
+        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command_flags & EXEC_COMMAND_FULLY_PRIVILEGED);
+        if (needs_sandboxing) {
+                /* The runtime struct only contains the parent of the private /tmp, which is non-accessible
+                 * to world users. Inside of it there's a /tmp that is sticky, and that's the one we want to
+                 * use here.  This does not apply when we are using /run/systemd/empty as fallback. */
+
+                if (context->private_tmp && runtime && runtime->shared) {
+                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
+                                tmp_dir = runtime->shared->tmp_dir;
+                        else if (runtime->shared->tmp_dir)
+                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
+
+                        if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
+                                var_tmp_dir = runtime->shared->var_tmp_dir;
+                        else if (runtime->shared->var_tmp_dir)
+                                var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
+                }
+        }
+
+        /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
+        setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && (root_dir || root_image);
+        r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
+        if (r < 0)
+                return r;
+
+        if (context->mount_propagation_flag == MS_SHARED)
+                log_exec_debug(context,
+                               params,
+                               "shared mount propagation hidden by other fs namespacing unit settings: ignoring");
+
+        if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
+                r = exec_context_get_credential_directory(context, params, params->unit_id, &creds_path);
+                if (r < 0)
+                        return r;
+        }
+
+        if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
+                propagate_dir = path_join("/run/systemd/propagate/", params->unit_id);
+                if (!propagate_dir)
+                        return -ENOMEM;
+
+                incoming_dir = strdup("/run/systemd/incoming");
+                if (!incoming_dir)
+                        return -ENOMEM;
+
+                extension_dir = strdup("/run/systemd/unit-extensions");
+                if (!extension_dir)
+                        return -ENOMEM;
+
+                /* If running under a different root filesystem, propagate the host's os-release. We make a
+                 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
+                if (setup_os_release_symlink) {
+                        host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
+                        if (!host_os_release_stage)
+                                return -ENOMEM;
+                }
+        } else {
+                assert(params->runtime_scope == RUNTIME_SCOPE_USER);
+
+                if (asprintf(&extension_dir, "/run/user/" UID_FMT "/systemd/unit-extensions", geteuid()) < 0)
+                        return -ENOMEM;
+
+                if (setup_os_release_symlink) {
+                        if (asprintf(&host_os_release_stage,
+                                     "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
+                                     geteuid()) < 0)
+                                return -ENOMEM;
+                }
+        }
+
+        if (root_image) {
+                r = verity_settings_prepare(
+                        &verity,
+                        root_image,
+                        context->root_hash, context->root_hash_size, context->root_hash_path,
+                        context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
+                        context->root_verity);
+                if (r < 0)
+                        return r;
+        }
+
+        NamespaceParameters parameters = {
+                .runtime_scope = params->runtime_scope,
+
+                .root_directory = root_dir,
+                .root_image = root_image,
+                .root_image_options = context->root_image_options,
+                .root_image_policy = context->root_image_policy ?: &image_policy_service,
+
+                .read_write_paths = read_write_paths,
+                .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
+                .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
+
+                .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
+                .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
+
+                .empty_directories = empty_directories,
+                .symlinks = symlinks,
+
+                .bind_mounts = bind_mounts,
+                .n_bind_mounts = n_bind_mounts,
+
+                .temporary_filesystems = context->temporary_filesystems,
+                .n_temporary_filesystems = context->n_temporary_filesystems,
+
+                .mount_images = context->mount_images,
+                .n_mount_images = context->n_mount_images,
+                .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
+
+                .tmp_dir = tmp_dir,
+                .var_tmp_dir = var_tmp_dir,
+
+                .creds_path = creds_path,
+                .log_namespace = context->log_namespace,
+                .mount_propagation_flag = context->mount_propagation_flag,
+
+                .verity = &verity,
+
+                .extension_images = context->extension_images,
+                .n_extension_images = context->n_extension_images,
+                .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
+                .extension_directories = context->extension_directories,
+
+                .propagate_dir = propagate_dir,
+                .incoming_dir = incoming_dir,
+                .extension_dir = extension_dir,
+                .notify_socket = root_dir || root_image ? params->notify_socket : NULL,
+                .host_os_release_stage = host_os_release_stage,
+
+                /* If DynamicUser=no and RootDirectory= is set then lets pass a relaxed sandbox info,
+                 * otherwise enforce it, don't ignore protected paths and fail if we are enable to apply the
+                 * sandbox inside the mount namespace. */
+                .ignore_protect_paths = !needs_sandboxing && !context->dynamic_user && root_dir,
+
+                .protect_control_groups = needs_sandboxing && context->protect_control_groups,
+                .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
+                .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
+                .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
+                .protect_hostname = needs_sandboxing && context->protect_hostname,
+
+                .private_dev = needs_sandboxing && context->private_devices,
+                .private_network = needs_sandboxing && exec_needs_network_namespace(context),
+                .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
+
+                .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
+
+                /* If NNP is on, we can turn on MS_NOSUID, since it won't have any effect anymore. */
+                .mount_nosuid = needs_sandboxing && context->no_new_privileges && !mac_selinux_use(),
+
+                .protect_home = needs_sandboxing && context->protect_home,
+                .protect_system = needs_sandboxing && context->protect_system,
+                .protect_proc = needs_sandboxing && context->protect_proc,
+                .proc_subset = needs_sandboxing && context->proc_subset,
+        };
+
+        r = setup_namespace(&parameters, error_path);
+        /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
+         * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
+         * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
+         * completely different execution environment. */
+        if (r == -ENOANO) {
+                if (insist_on_sandboxing(
+                                    context,
+                                    root_dir, root_image,
+                                    bind_mounts,
+                                    n_bind_mounts))
+                        return log_exec_debug_errno(context,
+                                                    params,
+                                                    SYNTHETIC_ERRNO(EOPNOTSUPP),
+                                                    "Failed to set up namespace, and refusing to continue since "
+                                                    "the selected namespacing options alter mount environment non-trivially.\n"
+                                                    "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
+                                                    n_bind_mounts,
+                                                    context->n_temporary_filesystems,
+                                                    yes_no(root_dir),
+                                                    yes_no(root_image),
+                                                    yes_no(context->dynamic_user));
+
+                log_exec_debug(context, params, "Failed to set up namespace, assuming containerized execution and ignoring.");
+                return 0;
+        }
+
+        return r;
+}
+
+static int apply_working_directory(
+                const ExecContext *context,
+                const ExecParameters *params,
+                ExecRuntime *runtime,
+                const char *home,
+                int *exit_status) {
+
+        const char *d, *wd;
+
+        assert(context);
+        assert(exit_status);
+
+        if (context->working_directory_home) {
+
+                if (!home) {
+                        *exit_status = EXIT_CHDIR;
+                        return -ENXIO;
+                }
+
+                wd = home;
+
+        } else
+                wd = empty_to_root(context->working_directory);
+
+        if (params->flags & EXEC_APPLY_CHROOT)
+                d = wd;
+        else
+                d = prefix_roota((runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory, wd);
+
+        if (chdir(d) < 0 && !context->working_directory_missing_ok) {
+                *exit_status = EXIT_CHDIR;
+                return -errno;
+        }
+
+        return 0;
+}
+
+static int apply_root_directory(
+                const ExecContext *context,
+                const ExecParameters *params,
+                ExecRuntime *runtime,
+                const bool needs_mount_ns,
+                int *exit_status) {
+
+        assert(context);
+        assert(exit_status);
+
+        if (params->flags & EXEC_APPLY_CHROOT)
+                if (!needs_mount_ns && context->root_directory)
+                        if (chroot((runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory) < 0) {
+                                *exit_status = EXIT_CHROOT;
+                                return -errno;
+                        }
+
+        return 0;
+}
+
+static int setup_keyring(
+                const ExecContext *context,
+                const ExecParameters *p,
+                uid_t uid, gid_t gid) {
+
+        key_serial_t keyring;
+        int r = 0;
+        uid_t saved_uid;
+        gid_t saved_gid;
+
+        assert(context);
+        assert(p);
+
+        /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that
+         * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond
+         * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be
+         * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in
+         * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where
+         * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */
+
+        if (context->keyring_mode == EXEC_KEYRING_INHERIT)
+                return 0;
+
+        /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up
+         * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel
+         * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user
+         * & group is just as nasty as acquiring a reference to the user keyring. */
+
+        saved_uid = getuid();
+        saved_gid = getgid();
+
+        if (gid_is_valid(gid) && gid != saved_gid) {
+                if (setregid(gid, -1) < 0)
+                        return log_exec_error_errno(context,
+                                                    p,
+                                                    errno,
+                                                    "Failed to change GID for user keyring: %m");
+        }
+
+        if (uid_is_valid(uid) && uid != saved_uid) {
+                if (setreuid(uid, -1) < 0) {
+                        r = log_exec_error_errno(context,
+                                                 p,
+                                                 errno,
+                                                 "Failed to change UID for user keyring: %m");
+                        goto out;
+                }
+        }
+
+        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
+        if (keyring == -1) {
+                if (errno == ENOSYS)
+                        log_exec_debug_errno(context,
+                                             p,
+                                             errno,
+                                             "Kernel keyring not supported, ignoring.");
+                else if (ERRNO_IS_PRIVILEGE(errno))
+                        log_exec_debug_errno(context,
+                                             p,
+                                             errno,
+                                             "Kernel keyring access prohibited, ignoring.");
+                else if (errno == EDQUOT)
+                        log_exec_debug_errno(context,
+                                             p,
+                                             errno,
+                                             "Out of kernel keyrings to allocate, ignoring.");
+                else
+                        r = log_exec_error_errno(context,
+                                                 p,
+                                                 errno,
+                                                 "Setting up kernel keyring failed: %m");
+
+                goto out;
+        }
+
+        /* When requested link the user keyring into the session keyring. */
+        if (context->keyring_mode == EXEC_KEYRING_SHARED) {
+
+                if (keyctl(KEYCTL_LINK,
+                           KEY_SPEC_USER_KEYRING,
+                           KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
+                        r = log_exec_error_errno(context,
+                                                 p,
+                                                 errno,
+                                                 "Failed to link user keyring into session keyring: %m");
+                        goto out;
+                }
+        }
+
+        /* Restore uid/gid back */
+        if (uid_is_valid(uid) && uid != saved_uid) {
+                if (setreuid(saved_uid, -1) < 0) {
+                        r = log_exec_error_errno(context,
+                                                 p,
+                                                 errno,
+                                                 "Failed to change UID back for user keyring: %m");
+                        goto out;
+                }
+        }
+
+        if (gid_is_valid(gid) && gid != saved_gid) {
+                if (setregid(saved_gid, -1) < 0)
+                        return log_exec_error_errno(context,
+                                                    p,
+                                                    errno,
+                                                    "Failed to change GID back for user keyring: %m");
+        }
+
+        /* Populate they keyring with the invocation ID by default, as original saved_uid. */
+        if (!sd_id128_is_null(p->invocation_id)) {
+                key_serial_t key;
+
+                key = add_key("user",
+                              "invocation_id",
+                              &p->invocation_id,
+                              sizeof(p->invocation_id),
+                              KEY_SPEC_SESSION_KEYRING);
+                if (key == -1)
+                        log_exec_debug_errno(context,
+                                             p,
+                                             errno,
+                                             "Failed to add invocation ID to keyring, ignoring: %m");
+                else {
+                        if (keyctl(KEYCTL_SETPERM, key,
+                                   KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
+                                   KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
+                                r = log_exec_error_errno(context,
+                                                         p,
+                                                         errno,
+                                                         "Failed to restrict invocation ID permission: %m");
+                }
+        }
+
+out:
+        /* Revert back uid & gid for the last time, and exit */
+        /* no extra logging, as only the first already reported error matters */
+        if (getuid() != saved_uid)
+                (void) setreuid(saved_uid, -1);
+
+        if (getgid() != saved_gid)
+                (void) setregid(saved_gid, -1);
+
+        return r;
+}
+
+static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
+        assert(array);
+        assert(n);
+        assert(pair);
+
+        if (pair[0] >= 0)
+                array[(*n)++] = pair[0];
+        if (pair[1] >= 0)
+                array[(*n)++] = pair[1];
+}
+
+static int close_remaining_fds(
+                const ExecParameters *params,
+                const ExecRuntime *runtime,
+                int socket_fd,
+                const int *fds, size_t n_fds) {
+
+        size_t n_dont_close = 0;
+        int dont_close[n_fds + 14];
+
+        assert(params);
+
+        if (params->stdin_fd >= 0)
+                dont_close[n_dont_close++] = params->stdin_fd;
+        if (params->stdout_fd >= 0)
+                dont_close[n_dont_close++] = params->stdout_fd;
+        if (params->stderr_fd >= 0)
+                dont_close[n_dont_close++] = params->stderr_fd;
+
+        if (socket_fd >= 0)
+                dont_close[n_dont_close++] = socket_fd;
+        if (n_fds > 0) {
+                memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
+                n_dont_close += n_fds;
+        }
+
+        if (runtime)
+                append_socket_pair(dont_close, &n_dont_close, runtime->ephemeral_storage_socket);
+
+        if (runtime && runtime->shared) {
+                append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
+                append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
+        }
+
+        if (runtime && runtime->dynamic_creds) {
+                if (runtime->dynamic_creds->user)
+                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
+                if (runtime->dynamic_creds->group)
+                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
+        }
+
+        if (params->user_lookup_fd >= 0)
+                dont_close[n_dont_close++] = params->user_lookup_fd;
+
+        return close_all_fds(dont_close, n_dont_close);
+}
+
+static int send_user_lookup(
+                const char *unit_id,
+                int user_lookup_fd,
+                uid_t uid,
+                gid_t gid) {
+
+        assert(unit_id);
+
+        /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
+         * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
+         * specified. */
+
+        if (user_lookup_fd < 0)
+                return 0;
+
+        if (!uid_is_valid(uid) && !gid_is_valid(gid))
+                return 0;
+
+        if (writev(user_lookup_fd,
+               (struct iovec[]) {
+                           IOVEC_MAKE(&uid, sizeof(uid)),
+                           IOVEC_MAKE(&gid, sizeof(gid)),
+                           IOVEC_MAKE_STRING(unit_id) }, 3) < 0)
+                return -errno;
+
+        return 0;
+}
+
+static int acquire_home(const ExecContext *c, uid_t uid, const char** home, char **buf) {
+        int r;
+
+        assert(c);
+        assert(home);
+        assert(buf);
+
+        /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */
+
+        if (*home)
+                return 0;
+
+        if (!c->working_directory_home)
+                return 0;
+
+        r = get_home_dir(buf);
+        if (r < 0)
+                return r;
+
+        *home = *buf;
+        return 1;
+}
+
+static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
+        _cleanup_strv_free_ char ** list = NULL;
+        int r;
+
+        assert(c);
+        assert(p);
+        assert(ret);
+
+        assert(c->dynamic_user);
+
+        /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for
+         * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special
+         * directories. */
+
+        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
+                if (t == EXEC_DIRECTORY_CONFIGURATION)
+                        continue;
+
+                if (!p->prefix[t])
+                        continue;
+
+                for (size_t i = 0; i < c->directories[t].n_items; i++) {
+                        char *e;
+
+                        if (exec_directory_is_private(c, t))
+                                e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
+                        else
+                                e = path_join(p->prefix[t], c->directories[t].items[i].path);
+                        if (!e)
+                                return -ENOMEM;
+
+                        r = strv_consume(&list, e);
+                        if (r < 0)
+                                return r;
+                }
+        }
+
+        *ret = TAKE_PTR(list);
+
+        return 0;
+}
+
+static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
+        _cleanup_(cpu_set_reset) CPUSet s = {};
+        int r;
+
+        assert(c);
+        assert(ret);
+
+        if (!c->numa_policy.nodes.set) {
+                log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
+                return 0;
+        }
+
+        r = numa_to_cpu_set(&c->numa_policy, &s);
+        if (r < 0)
+                return r;
+
+        cpu_set_reset(ret);
+
+        return cpu_set_add_all(ret, &s);
+}
+
+static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int fd, int *ret_fd) {
+        int r;
+
+        assert(fds);
+        assert(n_fds);
+        assert(*n_fds < fds_size);
+        assert(ret_fd);
+
+        if (fd < 0) {
+                *ret_fd = -EBADF;
+                return 0;
+        }
+
+        if (fd < 3 + (int) *n_fds) {
+                /* Let's move the fd up, so that it's outside of the fd range we will use to store
+                 * the fds we pass to the process (or which are closed only during execve). */
+
+                r = fcntl(fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
+                if (r < 0)
+                        return -errno;
+
+                close_and_replace(fd, r);
+        }
+
+        *ret_fd = fds[*n_fds] = fd;
+        (*n_fds) ++;
+        return 1;
+}
+
+static int connect_unix_harder(const ExecContext *c, const ExecParameters *p, const OpenFile *of, int ofd) {
+        union sockaddr_union addr = {
+                .un.sun_family = AF_UNIX,
+        };
+        socklen_t sa_len;
+        static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
+        int r;
+
+        assert(c);
+        assert(p);
+        assert(of);
+        assert(ofd >= 0);
+
+        r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
+        if (r < 0)
+                return log_exec_error_errno(c, p, r, "Failed to set sockaddr for %s: %m", of->path);
+
+        sa_len = r;
+
+        for (size_t i = 0; i < ELEMENTSOF(socket_types); i++) {
+                _cleanup_close_ int fd = -EBADF;
+
+                fd = socket(AF_UNIX, socket_types[i] | SOCK_CLOEXEC, 0);
+                if (fd < 0)
+                        return log_exec_error_errno(c,
+                                                    p,
+                                                    errno,
+                                                    "Failed to create socket for %s: %m",
+                                                    of->path);
+
+                r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
+                if (r == -EPROTOTYPE)
+                        continue;
+                if (r < 0)
+                        return log_exec_error_errno(c,
+                                                    p,
+                                                    r,
+                                                    "Failed to connect socket for %s: %m",
+                                                    of->path);
+
+                return TAKE_FD(fd);
+        }
+
+        return log_exec_error_errno(c,
+                                    p,
+                                    SYNTHETIC_ERRNO(EPROTOTYPE), "Failed to connect socket for \"%s\".",
+                                    of->path);
+}
+
+static int get_open_file_fd(const ExecContext *c, const ExecParameters *p, const OpenFile *of) {
+        struct stat st;
+        _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
+
+        assert(c);
+        assert(p);
+        assert(of);
+
+        ofd = open(of->path, O_PATH | O_CLOEXEC);
+        if (ofd < 0)
+                return log_exec_error_errno(c, p, errno, "Could not open \"%s\": %m", of->path);
+
+        if (fstat(ofd, &st) < 0)
+                return log_exec_error_errno(c, p, errno, "Failed to stat %s: %m", of->path);
+
+        if (S_ISSOCK(st.st_mode)) {
+                fd = connect_unix_harder(c, p, of, ofd);
+                if (fd < 0)
+                        return fd;
+
+                if (FLAGS_SET(of->flags, OPENFILE_READ_ONLY) && shutdown(fd, SHUT_WR) < 0)
+                        return log_exec_error_errno(c, p, errno, "Failed to shutdown send for socket %s: %m",
+                                                    of->path);
+
+                log_exec_debug(c, p, "socket %s opened (fd=%d)", of->path, fd);
+        } else {
+                int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
+                if (FLAGS_SET(of->flags, OPENFILE_APPEND))
+                        flags |= O_APPEND;
+                else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
+                        flags |= O_TRUNC;
+
+                fd = fd_reopen(ofd, flags | O_CLOEXEC);
+                if (fd < 0)
+                        return log_exec_error_errno(c, p, fd, "Failed to open file %s: %m", of->path);
+
+                log_exec_debug(c, p, "file %s opened (fd=%d)", of->path, fd);
+        }
+
+        return TAKE_FD(fd);
+}
+
+static int collect_open_file_fds(
+                const ExecContext *c,
+                const ExecParameters *p,
+                int **fds,
+                char ***fdnames,
+                size_t *n_fds) {
+        int r;
+
+        assert(c);
+        assert(p);
+        assert(fds);
+        assert(fdnames);
+        assert(n_fds);
+
+        LIST_FOREACH(open_files, of, p->open_files) {
+                _cleanup_close_ int fd = -EBADF;
+
+                fd = get_open_file_fd(c, p, of);
+                if (fd < 0) {
+                        if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
+                                log_exec_debug_errno(c, p, fd, "Failed to get OpenFile= file descriptor for %s, ignoring: %m", of->path);
+                                continue;
+                        }
+
+                        return fd;
+                }
+
+                if (!GREEDY_REALLOC(*fds, *n_fds + 1))
+                        return -ENOMEM;
+
+                r = strv_extend(fdnames, of->fdname);
+                if (r < 0)
+                        return r;
+
+                (*fds)[*n_fds] = TAKE_FD(fd);
+
+                (*n_fds)++;
+        }
+
+        return 0;
+}
+
+static void log_command_line(
+                const ExecContext *context,
+                const ExecParameters *params,
+                const char *msg,
+                const char *executable,
+                char **argv) {
+
+        assert(context);
+        assert(params);
+        assert(msg);
+        assert(executable);
+
+        if (!DEBUG_LOGGING)
+                return;
+
+        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
+
+        log_exec_struct(context, params, LOG_DEBUG,
+                        "EXECUTABLE=%s", executable,
+                        LOG_EXEC_MESSAGE(params, "%s: %s", msg, strnull(cmdline)),
+                        LOG_EXEC_INVOCATION_ID(params));
+}
+
+static bool exec_context_need_unprivileged_private_users(
+                const ExecContext *context,
+                const ExecParameters *params) {
+
+        assert(context);
+        assert(params);
+
+        /* These options require PrivateUsers= when used in user units, as we need to be in a user namespace
+         * to have permission to enable them when not running as root. If we have effective CAP_SYS_ADMIN
+         * (system manager) then we have privileges and don't need this. */
+        if (params->runtime_scope != RUNTIME_SCOPE_USER)
+                return false;
+
+        return context->private_users ||
+               context->private_tmp ||
+               context->private_devices ||
+               context->private_network ||
+               context->network_namespace_path ||
+               context->private_ipc ||
+               context->ipc_namespace_path ||
+               context->private_mounts > 0 ||
+               context->mount_apivfs ||
+               context->n_bind_mounts > 0 ||
+               context->n_temporary_filesystems > 0 ||
+               context->root_directory ||
+               !strv_isempty(context->extension_directories) ||
+               context->protect_system != PROTECT_SYSTEM_NO ||
+               context->protect_home != PROTECT_HOME_NO ||
+               context->protect_kernel_tunables ||
+               context->protect_kernel_modules ||
+               context->protect_kernel_logs ||
+               context->protect_control_groups ||
+               context->protect_clock ||
+               context->protect_hostname ||
+               !strv_isempty(context->read_write_paths) ||
+               !strv_isempty(context->read_only_paths) ||
+               !strv_isempty(context->inaccessible_paths) ||
+               !strv_isempty(context->exec_paths) ||
+               !strv_isempty(context->no_exec_paths);
+}
+
+static bool exec_context_shall_confirm_spawn(const ExecContext *context) {
+        assert(context);
+
+        if (confirm_spawn_disabled())
+                return false;
+
+        /* For some reasons units remaining in the same process group
+         * as PID 1 fail to acquire the console even if it's not used
+         * by any process. So skip the confirmation question for them. */
+        return !context->same_pgrp;
+}
+
+static int exec_context_named_iofds(
+                const ExecContext *c,
+                const ExecParameters *p,
+                int named_iofds[static 3]) {
+
+        size_t targets;
+        const char* stdio_fdname[3];
+        size_t n_fds;
+
+        assert(c);
+        assert(p);
+        assert(named_iofds);
+
+        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
+                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
+                  (c->std_error == EXEC_OUTPUT_NAMED_FD);
+
+        for (size_t i = 0; i < 3; i++)
+                stdio_fdname[i] = exec_context_fdname(c, i);
+
+        n_fds = p->n_storage_fds + p->n_socket_fds;
+
+        for (size_t i = 0; i < n_fds  && targets > 0; i++)
+                if (named_iofds[STDIN_FILENO] < 0 &&
+                    c->std_input == EXEC_INPUT_NAMED_FD &&
+                    stdio_fdname[STDIN_FILENO] &&
+                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
+
+                        named_iofds[STDIN_FILENO] = p->fds[i];
+                        targets--;
+
+                } else if (named_iofds[STDOUT_FILENO] < 0 &&
+                           c->std_output == EXEC_OUTPUT_NAMED_FD &&
+                           stdio_fdname[STDOUT_FILENO] &&
+                           streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
+
+                        named_iofds[STDOUT_FILENO] = p->fds[i];
+                        targets--;
+
+                } else if (named_iofds[STDERR_FILENO] < 0 &&
+                           c->std_error == EXEC_OUTPUT_NAMED_FD &&
+                           stdio_fdname[STDERR_FILENO] &&
+                           streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
+
+                        named_iofds[STDERR_FILENO] = p->fds[i];
+                        targets--;
+                }
+
+        return targets == 0 ? 0 : -ENOENT;
+}
+
+int exec_invoke(
+                const ExecCommand *command,
+                const ExecContext *context,
+                ExecParameters *params,
+                ExecRuntime *runtime,
+                const CGroupContext *cgroup_context,
+                int *exit_status) {
+
+        _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL, **replaced_argv = NULL;
+        int r, ngids = 0, exec_fd;
+        _cleanup_free_ gid_t *supplementary_gids = NULL;
+        const char *username = NULL, *groupname = NULL;
+        _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL;
+        const char *home = NULL, *shell = NULL;
+        char **final_argv = NULL;
+        dev_t journal_stream_dev = 0;
+        ino_t journal_stream_ino = 0;
+        bool userns_set_up = false;
+        bool needs_sandboxing,          /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
+                needs_setuid,           /* Do we need to do the actual setresuid()/setresgid() calls? */
+                needs_mount_namespace,  /* Do we need to set up a mount namespace for this kernel? */
+                needs_ambient_hack;     /* Do we need to apply the ambient capabilities hack? */
+#if HAVE_SELINUX
+        _cleanup_free_ char *mac_selinux_context_net = NULL;
+        bool use_selinux = false;
+#endif
+#if ENABLE_SMACK
+        bool use_smack = false;
+#endif
+#if HAVE_APPARMOR
+        bool use_apparmor = false;
+#endif
+        uid_t saved_uid = getuid();
+        gid_t saved_gid = getgid();
+        uid_t uid = UID_INVALID;
+        gid_t gid = GID_INVALID;
+        size_t n_fds, /* fds to pass to the child */
+               n_keep_fds; /* total number of fds not to close */
+        int secure_bits;
+        _cleanup_free_ gid_t *gids_after_pam = NULL;
+        int ngids_after_pam = 0;
+        _cleanup_free_ int *fds = NULL;
+        _cleanup_strv_free_ char **fdnames = NULL;
+
+        int socket_fd = -EBADF, named_iofds[3] = { -EBADF, -EBADF, -EBADF }, *params_fds = NULL;
+        size_t n_storage_fds = 0, n_socket_fds = 0;
+
+        assert(command);
+        assert(context);
+        assert(params);
+        assert(exit_status);
+
+        /* Explicitly test for CVE-2021-4034 inspired invocations */
+        assert(command->path);
+        assert(!strv_isempty(command->argv));
+
+        LOG_CONTEXT_PUSH_EXEC(context, params);
+
+        if (context->std_input == EXEC_INPUT_SOCKET ||
+            context->std_output == EXEC_OUTPUT_SOCKET ||
+            context->std_error == EXEC_OUTPUT_SOCKET) {
+
+                if (params->n_socket_fds > 1)
+                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
+
+                if (params->n_socket_fds == 0)
+                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
+
+                socket_fd = params->fds[0];
+        } else {
+                params_fds = params->fds;
+                n_socket_fds = params->n_socket_fds;
+                n_storage_fds = params->n_storage_fds;
+        }
+        n_fds = n_socket_fds + n_storage_fds;
+
+        r = exec_context_named_iofds(context, params, named_iofds);
+        if (r < 0)
+                return log_exec_error_errno(context, params, r, "Failed to load a named file descriptor: %m");
+
+        rename_process_from_path(command->path);
+
+        /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
+         * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
+         * both of which will be demoted to SIG_DFL. */
+        (void) default_signals(SIGNALS_CRASH_HANDLER,
+                               SIGNALS_IGNORE);
+
+        if (context->ignore_sigpipe)
+                (void) ignore_signals(SIGPIPE);
+
+        r = reset_signal_mask();
+        if (r < 0) {
+                *exit_status = EXIT_SIGNAL_MASK;
+                return log_exec_error_errno(context, params, r, "Failed to set process signal mask: %m");
+        }
+
+        if (params->idle_pipe)
+                do_idle_pipe_dance(params->idle_pipe);
+
+        /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
+         * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
+         * any fds open we don't really want open during the transition. In order to make logging work, we switch the
+         * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
+
+        log_forget_fds();
+        log_set_open_when_needed(true);
+        log_settle_target();
+        if (context->log_level_max >= 0)
+                log_set_max_level(context->log_level_max);
+
+        /* In case anything used libc syslog(), close this here, too */
+        closelog();
+
+        fds = newdup(int, params_fds, n_fds);
+        if (!fds) {
+                *exit_status = EXIT_MEMORY;
+                return log_oom();
+        }
+
+        fdnames = strv_copy((char**) params->fd_names);
+        if (!fdnames) {
+                *exit_status = EXIT_MEMORY;
+                return log_oom();
+        }
+
+        r = collect_open_file_fds(context, params, &fds, &fdnames, &n_fds);
+        if (r < 0) {
+                *exit_status = EXIT_FDS;
+                return log_exec_error_errno(context, params, r, "Failed to get OpenFile= file descriptors: %m");
+        }
+
+        int keep_fds[n_fds + 3];
+        memcpy_safe(keep_fds, fds, n_fds * sizeof(int));
+        n_keep_fds = n_fds;
+
+        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, params->exec_fd, &exec_fd);
+        if (r < 0) {
+                *exit_status = EXIT_FDS;
+                return log_exec_error_errno(context, params, r, "Failed to shift fd and set FD_CLOEXEC: %m");
+        }
+
+#if HAVE_LIBBPF
+        if (params->bpf_outer_map_fd >= 0) {
+                r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, params->bpf_outer_map_fd, (int *)&params->bpf_outer_map_fd);
+                if (r < 0) {
+                        *exit_status = EXIT_FDS;
+                        return log_exec_error_errno(context, params, r, "Failed to shift fd and set FD_CLOEXEC: %m");
+                }
+        }
+#endif
+
+        r = close_remaining_fds(params, runtime, socket_fd, keep_fds, n_keep_fds);
+        if (r < 0) {
+                *exit_status = EXIT_FDS;
+                return log_exec_error_errno(context, params, r, "Failed to close unwanted file descriptors: %m");
+        }
+
+        if (!context->same_pgrp &&
+            setsid() < 0) {
+                *exit_status = EXIT_SETSID;
+                return log_exec_error_errno(context, params, errno, "Failed to create new process session: %m");
+        }
+
+        exec_context_tty_reset(context, params);
+
+        if (params->shall_confirm_spawn && exec_context_shall_confirm_spawn(context)) {
+                _cleanup_free_ char *cmdline = NULL;
+
+                cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
+                if (!cmdline) {
+                        *exit_status = EXIT_MEMORY;
+                        return log_oom();
+                }
+
+                r = ask_for_confirmation(context, params, cmdline);
+                if (r != CONFIRM_EXECUTE) {
+                        if (r == CONFIRM_PRETEND_SUCCESS) {
+                                *exit_status = EXIT_SUCCESS;
+                                return 0;
+                        }
+
+                        *exit_status = EXIT_CONFIRM;
+                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ECANCELED),
+                                                    "Execution cancelled by the user");
+                }
+        }
+
+        /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
+         * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
+         * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
+         * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
+         * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
+        if (setenv("SYSTEMD_ACTIVATION_UNIT", params->unit_id, true) != 0 ||
+            setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
+                *exit_status = EXIT_MEMORY;
+                return log_exec_error_errno(context, params, errno, "Failed to update environment: %m");
+        }
+
+        if (context->dynamic_user && runtime && runtime->dynamic_creds) {
+                _cleanup_strv_free_ char **suggested_paths = NULL;
+
+                /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
+                 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
+                if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
+                        *exit_status = EXIT_USER;
+                        return log_exec_error_errno(context, params, errno, "Failed to update environment: %m");
+                }
+
+                r = compile_suggested_paths(context, params, &suggested_paths);
+                if (r < 0) {
+                        *exit_status = EXIT_MEMORY;
+                        return log_oom();
+                }
+
+                r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
+                if (r < 0) {
+                        *exit_status = EXIT_USER;
+                        if (r == -EILSEQ)
+                                return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
+                                                            "Failed to update dynamic user credentials: User or group with specified name already exists.");
+                        return log_exec_error_errno(context, params, r, "Failed to update dynamic user credentials: %m");
+                }
+
+                if (!uid_is_valid(uid)) {
+                        *exit_status = EXIT_USER;
+                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\"", uid);
+                }
+
+                if (!gid_is_valid(gid)) {
+                        *exit_status = EXIT_USER;
+                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\"", gid);
+                }
+
+                if (runtime->dynamic_creds->user)
+                        username = runtime->dynamic_creds->user->name;
+
+        } else {
+                if (context->user) {
+                        r = get_fixed_user(context->user, &username, &uid, &gid, &home, &shell);
+                        if (r < 0) {
+                                *exit_status = EXIT_USER;
+                                return log_exec_error_errno(context, params, r, "Failed to determine user credentials: %m");
+                        }
+                }
+
+                if (context->group) {
+                        r = get_fixed_group(context->group, &groupname, &gid);
+                        if (r < 0) {
+                                *exit_status = EXIT_GROUP;
+                                return log_exec_error_errno(context, params, r, "Failed to determine group credentials: %m");
+                        }
+                }
+        }
+
+        /* Initialize user supplementary groups and get SupplementaryGroups= ones */
+        r = get_supplementary_groups(context, username, groupname, gid,
+                                     &supplementary_gids, &ngids);
+        if (r < 0) {
+                *exit_status = EXIT_GROUP;
+                return log_exec_error_errno(context, params, r, "Failed to determine supplementary groups: %m");
+        }
+
+        r = send_user_lookup(params->unit_id, params->user_lookup_fd, uid, gid);
+        if (r < 0) {
+                *exit_status = EXIT_USER;
+                return log_exec_error_errno(context, params, r, "Failed to send user credentials to PID1: %m");
+        }
+
+        params->user_lookup_fd = safe_close(params->user_lookup_fd);
+
+        r = acquire_home(context, uid, &home, &home_buffer);
+        if (r < 0) {
+                *exit_status = EXIT_CHDIR;
+                return log_exec_error_errno(context, params, r, "Failed to determine $HOME for user: %m");
+        }
+
+        /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
+        if (socket_fd >= 0)
+                (void) fd_nonblock(socket_fd, false);
+
+        /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
+         * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
+        if (params->cgroup_path) {
+                _cleanup_free_ char *p = NULL;
+
+                r = exec_params_get_cgroup_path(params, cgroup_context, &p);
+                if (r < 0) {
+                        *exit_status = EXIT_CGROUP;
+                        return log_exec_error_errno(context, params, r, "Failed to acquire cgroup path: %m");
+                }
+
+                r = cg_attach_everywhere(params->cgroup_supported, p, 0, NULL, NULL);
+                if (r == -EUCLEAN) {
+                        *exit_status = EXIT_CGROUP;
+                        return log_exec_error_errno(context, params, r, "Failed to attach process to cgroup %s "
+                                                    "because the cgroup or one of its parents or "
+                                                    "siblings is in the threaded mode: %m", p);
+                }
+                if (r < 0) {
+                        *exit_status = EXIT_CGROUP;
+                        return log_exec_error_errno(context, params, r, "Failed to attach to cgroup %s: %m", p);
+                }
+        }
+
+        if (context->network_namespace_path && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
+                r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
+                if (r < 0) {
+                        *exit_status = EXIT_NETWORK;
+                        return log_exec_error_errno(context, params, r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
+                }
+        }
+
+        if (context->ipc_namespace_path && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
+                r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
+                if (r < 0) {
+                        *exit_status = EXIT_NAMESPACE;
+                        return log_exec_error_errno(context, params, r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
+                }
+        }
+
+        r = setup_input(context, params, socket_fd, named_iofds);
+        if (r < 0) {
+                *exit_status = EXIT_STDIN;
+                return log_exec_error_errno(context, params, r, "Failed to set up standard input: %m");
+        }
+
+        r = setup_output(context, params, STDOUT_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
+        if (r < 0) {
+                *exit_status = EXIT_STDOUT;
+                return log_exec_error_errno(context, params, r, "Failed to set up standard output: %m");
+        }
+
+        r = setup_output(context, params, STDERR_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
+        if (r < 0) {
+                *exit_status = EXIT_STDERR;
+                return log_exec_error_errno(context, params, r, "Failed to set up standard error output: %m");
+        }
+
+        if (context->oom_score_adjust_set) {
+                /* When we can't make this change due to EPERM, then let's silently skip over it. User
+                 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
+                r = set_oom_score_adjust(context->oom_score_adjust);
+                if (ERRNO_IS_NEG_PRIVILEGE(r))
+                        log_exec_debug_errno(context, params, r,
+                                             "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
+                else if (r < 0) {
+                        *exit_status = EXIT_OOM_ADJUST;
+                        return log_exec_error_errno(context, params, r, "Failed to adjust OOM setting: %m");
+                }
+        }
+
+        if (context->coredump_filter_set) {
+                r = set_coredump_filter(context->coredump_filter);
+                if (ERRNO_IS_NEG_PRIVILEGE(r))
+                        log_exec_debug_errno(context, params, r, "Failed to adjust coredump_filter, ignoring: %m");
+                else if (r < 0) {
+                        *exit_status = EXIT_LIMITS;
+                        return log_exec_error_errno(context, params, r, "Failed to adjust coredump_filter: %m");
+                }
+        }
+
+        if (context->nice_set) {
+                r = setpriority_closest(context->nice);
+                if (r < 0) {
+                        *exit_status = EXIT_NICE;
+                        return log_exec_error_errno(context, params, r, "Failed to set up process scheduling priority (nice level): %m");
+                }
+        }
+
+        if (context->cpu_sched_set) {
+                struct sched_param param = {
+                        .sched_priority = context->cpu_sched_priority,
+                };
+
+                r = sched_setscheduler(0,
+                                       context->cpu_sched_policy |
+                                       (context->cpu_sched_reset_on_fork ?
+                                        SCHED_RESET_ON_FORK : 0),
+                                       &param);
+                if (r < 0) {
+                        *exit_status = EXIT_SETSCHEDULER;
+                        return log_exec_error_errno(context, params, errno, "Failed to set up CPU scheduling: %m");
+                }
+        }
+
+        if (context->cpu_affinity_from_numa || context->cpu_set.set) {
+                _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
+                const CPUSet *cpu_set;
+
+                if (context->cpu_affinity_from_numa) {
+                        r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
+                        if (r < 0) {
+                                *exit_status = EXIT_CPUAFFINITY;
+                                return log_exec_error_errno(context, params, r, "Failed to derive CPU affinity mask from NUMA mask: %m");
+                        }
+
+                        cpu_set = &converted_cpu_set;
+                } else
+                        cpu_set = &context->cpu_set;
+
+                if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
+                        *exit_status = EXIT_CPUAFFINITY;
+                        return log_exec_error_errno(context, params, errno, "Failed to set up CPU affinity: %m");
+                }
+        }
+
+        if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
+                r = apply_numa_policy(&context->numa_policy);
+                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
+                        log_exec_debug_errno(context, params, r, "NUMA support not available, ignoring.");
+                else if (r < 0) {
+                        *exit_status = EXIT_NUMA_POLICY;
+                        return log_exec_error_errno(context, params, r, "Failed to set NUMA memory policy: %m");
+                }
+        }
+
+        if (context->ioprio_set)
+                if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
+                        *exit_status = EXIT_IOPRIO;
+                        return log_exec_error_errno(context, params, errno, "Failed to set up IO scheduling priority: %m");
+                }
+
+        if (context->timer_slack_nsec != NSEC_INFINITY)
+                if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
+                        *exit_status = EXIT_TIMERSLACK;
+                        return log_exec_error_errno(context, params, errno, "Failed to set up timer slack: %m");
+                }
+
+        if (context->personality != PERSONALITY_INVALID) {
+                r = safe_personality(context->personality);
+                if (r < 0) {
+                        *exit_status = EXIT_PERSONALITY;
+                        return log_exec_error_errno(context, params, r, "Failed to set up execution domain (personality): %m");
+                }
+        }
+
+        if (context->utmp_id) {
+                const char *line = context->tty_path ?
+                        (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
+                        NULL;
+                utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
+                                      line,
+                                      context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
+                                      context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
+                                      USER_PROCESS,
+                                      username);
+        }
+
+        if (uid_is_valid(uid)) {
+                r = chown_terminal(STDIN_FILENO, uid);
+                if (r < 0) {
+                        *exit_status = EXIT_STDIN;
+                        return log_exec_error_errno(context, params, r, "Failed to change ownership of terminal: %m");
+                }
+        }
+
+        if (params->cgroup_path) {
+                /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
+                 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
+                 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
+                 * touch a single hierarchy too. */
+
+                if (params->flags & EXEC_CGROUP_DELEGATE) {
+                        _cleanup_free_ char *p = NULL;
+
+                        r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid);
+                        if (r < 0) {
+                                *exit_status = EXIT_CGROUP;
+                                return log_exec_error_errno(context, params, r, "Failed to adjust control group access: %m");
+                        }
+
+                        r = exec_params_get_cgroup_path(params, cgroup_context, &p);
+                        if (r < 0) {
+                                *exit_status = EXIT_CGROUP;
+                                return log_exec_error_errno(context, params, r, "Failed to acquire cgroup path: %m");
+                        }
+                        if (r > 0) {
+                                r = cg_set_access_recursive(SYSTEMD_CGROUP_CONTROLLER, p, uid, gid);
+                                if (r < 0) {
+                                        *exit_status = EXIT_CGROUP;
+                                        return log_exec_error_errno(context, params, r, "Failed to adjust control subgroup access: %m");
+                                }
+                        }
+                }
+
+                if (cgroup_context && cg_unified() > 0 && is_pressure_supported() > 0) {
+                        if (cgroup_context_want_memory_pressure(cgroup_context)) {
+                                r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
+                                if (r < 0) {
+                                        *exit_status = EXIT_MEMORY;
+                                        return log_oom();
+                                }
+
+                                r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
+                                if (r < 0) {
+                                        log_exec_full_errno(context, params, r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
+                                                            "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
+                                        memory_pressure_path = mfree(memory_pressure_path);
+                                }
+                        } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_OFF) {
+                                memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
+                                if (!memory_pressure_path) {
+                                        *exit_status = EXIT_MEMORY;
+                                        return log_oom();
+                                }
+                        }
+                }
+        }
+
+        needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
+
+        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
+                r = setup_exec_directory(context, params, uid, gid, dt, needs_mount_namespace, exit_status);
+                if (r < 0)
+                        return log_exec_error_errno(context, params, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
+        }
+
+        if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
+                r = exec_setup_credentials(context, params, params->unit_id, uid, gid);
+                if (r < 0) {
+                        *exit_status = EXIT_CREDENTIALS;
+                        return log_exec_error_errno(context, params, r, "Failed to set up credentials: %m");
+                }
+        }
+
+        r = build_environment(
+                        context,
+                        params,
+                        cgroup_context,
+                        n_fds,
+                        fdnames,
+                        home,
+                        username,
+                        shell,
+                        journal_stream_dev,
+                        journal_stream_ino,
+                        memory_pressure_path,
+                        &our_env);
+        if (r < 0) {
+                *exit_status = EXIT_MEMORY;
+                return log_oom();
+        }
+
+        r = build_pass_environment(context, &pass_env);
+        if (r < 0) {
+                *exit_status = EXIT_MEMORY;
+                return log_oom();
+        }
+
+        /* The $PATH variable is set to the default path in params->environment. However, this is overridden
+         * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
+         * not specify PATH but the unit has ExecSearchPath. */
+        if (!strv_isempty(context->exec_search_path)) {
+                _cleanup_free_ char *joined = NULL;
+
+                joined = strv_join(context->exec_search_path, ":");
+                if (!joined) {
+                        *exit_status = EXIT_MEMORY;
+                        return log_oom();
+                }
+
+                r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
+                if (r < 0) {
+                        *exit_status = EXIT_MEMORY;
+                        return log_oom();
+                }
+        }
+
+        accum_env = strv_env_merge(params->environment,
+                                   our_env,
+                                   joined_exec_search_path,
+                                   pass_env,
+                                   context->environment,
+                                   params->files_env);
+        if (!accum_env) {
+                *exit_status = EXIT_MEMORY;
+                return log_oom();
+        }
+        accum_env = strv_env_clean(accum_env);
+
+        (void) umask(context->umask);
+
+        r = setup_keyring(context, params, uid, gid);
+        if (r < 0) {
+                *exit_status = EXIT_KEYRING;
+                return log_exec_error_errno(context, params, r, "Failed to set up kernel keyring: %m");
+        }
+
+        /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
+         * from it. */
+        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
+
+        /* We need the ambient capability hack, if the caller asked us to apply it and the command is marked
+         * for it, and the kernel doesn't actually support ambient caps. */
+        needs_ambient_hack = (params->flags & EXEC_APPLY_SANDBOXING) && (command->flags & EXEC_COMMAND_AMBIENT_MAGIC) && !ambient_capabilities_supported();
+
+        /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
+         * excepted from either whole sandboxing or just setresuid() itself, and the ambient hack is not
+         * desired. */
+        if (needs_ambient_hack)
+                needs_setuid = false;
+        else
+                needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
+
+        uint64_t capability_ambient_set = context->capability_ambient_set;
+
+        if (needs_sandboxing) {
+                /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
+                 * /sys being present. The actual MAC context application will happen later, as late as
+                 * possible, to avoid impacting our own code paths. */
+
+#if HAVE_SELINUX
+                use_selinux = mac_selinux_use();
+#endif
+#if ENABLE_SMACK
+                use_smack = mac_smack_use();
+#endif
+#if HAVE_APPARMOR
+                use_apparmor = mac_apparmor_use();
+#endif
+        }
+
+        if (needs_sandboxing) {
+                int which_failed;
+
+                /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
+                 * is set here. (See below.) */
+
+                r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
+                if (r < 0) {
+                        *exit_status = EXIT_LIMITS;
+                        return log_exec_error_errno(context, params, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
+                }
+        }
+
+        if (needs_setuid && context->pam_name && username) {
+                /* Let's call into PAM after we set up our own idea of resource limits to that pam_limits
+                 * wins here. (See above.) */
+
+                /* All fds passed in the fds array will be closed in the pam child process. */
+                r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds);
+                if (r < 0) {
+                        *exit_status = EXIT_PAM;
+                        return log_exec_error_errno(context, params, r, "Failed to set up PAM session: %m");
+                }
+
+                if (ambient_capabilities_supported()) {
+                        uint64_t ambient_after_pam;
+
+                        /* PAM modules might have set some ambient caps. Query them here and merge them into
+                         * the caps we want to set in the end, so that we don't end up unsetting them. */
+                        r = capability_get_ambient(&ambient_after_pam);
+                        if (r < 0) {
+                                *exit_status = EXIT_CAPABILITIES;
+                                return log_exec_error_errno(context, params, r, "Failed to query ambient caps: %m");
+                        }
+
+                        capability_ambient_set |= ambient_after_pam;
+                }
+
+                ngids_after_pam = getgroups_alloc(&gids_after_pam);
+                if (ngids_after_pam < 0) {
+                        *exit_status = EXIT_MEMORY;
+                        return log_exec_error_errno(context, params, ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
+                }
+        }
+
+        if (needs_sandboxing && exec_context_need_unprivileged_private_users(context, params)) {
+                /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
+                 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
+                 * set up the all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
+
+                r = setup_private_users(saved_uid, saved_gid, uid, gid);
+                /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
+                 * the actual requested operations fail (or silently continue). */
+                if (r < 0 && context->private_users) {
+                        *exit_status = EXIT_USER;
+                        return log_exec_error_errno(context, params, r, "Failed to set up user namespacing for unprivileged user: %m");
+                }
+                if (r < 0)
+                        log_exec_info_errno(context, params, r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
+                else
+                        userns_set_up = true;
+        }
+
+        if (exec_needs_network_namespace(context) && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
+
+                /* Try to enable network namespacing if network namespacing is available and we have
+                 * CAP_NET_ADMIN. We need CAP_NET_ADMIN to be able to configure the loopback device in the
+                 * new network namespace. And if we don't have that, then we could only create a network
+                 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
+                if (ns_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
+                        r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
+                        if (ERRNO_IS_NEG_PRIVILEGE(r))
+                                log_exec_notice_errno(context, params, r,
+                                                      "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
+                        else if (r < 0) {
+                                *exit_status = EXIT_NETWORK;
+                                return log_exec_error_errno(context, params, r, "Failed to set up network namespacing: %m");
+                        }
+                } else if (context->network_namespace_path) {
+                        *exit_status = EXIT_NETWORK;
+                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
+                                                    "NetworkNamespacePath= is not supported, refusing.");
+                } else
+                        log_exec_notice(context, params, "PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
+        }
+
+        if (exec_needs_ipc_namespace(context) && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
+
+                if (ns_type_supported(NAMESPACE_IPC)) {
+                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
+                        if (r == -EPERM)
+                                log_exec_warning_errno(context, params, r,
+                                                       "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
+                        else if (r < 0) {
+                                *exit_status = EXIT_NAMESPACE;
+                                return log_exec_error_errno(context, params, r, "Failed to set up IPC namespacing: %m");
+                        }
+                } else if (context->ipc_namespace_path) {
+                        *exit_status = EXIT_NAMESPACE;
+                        return log_exec_error_errno(context, params, SYNTHETIC_ERRNO(EOPNOTSUPP),
+                                                    "IPCNamespacePath= is not supported, refusing.");
+                } else
+                        log_exec_warning(context, params, "PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
+        }
+
+        if (needs_mount_namespace) {
+                _cleanup_free_ char *error_path = NULL;
+
+                r = apply_mount_namespace(command->flags, context, params, runtime, memory_pressure_path, &error_path);
+                if (r < 0) {
+                        *exit_status = EXIT_NAMESPACE;
+                        return log_exec_error_errno(context, params, r, "Failed to set up mount namespacing%s%s: %m",
+                                                    error_path ? ": " : "", strempty(error_path));
+                }
+        }
+
+        if (needs_sandboxing) {
+                r = apply_protect_hostname(context, params, exit_status);
+                if (r < 0)
+                        return r;
+        }
+
+        if (context->memory_ksm >= 0)
+                if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm) < 0) {
+                        if (ERRNO_IS_NOT_SUPPORTED(errno))
+                                log_exec_debug_errno(context,
+                                                     params,
+                                                     errno,
+                                                     "KSM support not available, ignoring.");
+                        else {
+                                *exit_status = EXIT_KSM;
+                                return log_exec_error_errno(context, params, errno, "Failed to set KSM: %m");
+                        }
+                }
+
+        /* Drop groups as early as possible.
+         * This needs to be done after PrivateDevices=y setup as device nodes should be owned by the host's root.
+         * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
+        if (needs_setuid) {
+                _cleanup_free_ gid_t *gids_to_enforce = NULL;
+                int ngids_to_enforce = 0;
+
+                ngids_to_enforce = merge_gid_lists(supplementary_gids,
+                                                   ngids,
+                                                   gids_after_pam,
+                                                   ngids_after_pam,
+                                                   &gids_to_enforce);
+                if (ngids_to_enforce < 0) {
+                        *exit_status = EXIT_MEMORY;
+                        return log_exec_error_errno(context, params,
+                                                    ngids_to_enforce,
+                                                    "Failed to merge group lists. Group membership might be incorrect: %m");
+                }
+
+                r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
+                if (r < 0) {
+                        *exit_status = EXIT_GROUP;
+                        return log_exec_error_errno(context, params, r, "Changing group credentials failed: %m");
+                }
+        }
+
+        /* If the user namespace was not set up above, try to do it now.
+         * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
+         * restricted by rules pertaining to combining user namespaces with other namespaces (e.g. in the
+         * case of mount namespaces being less privileged when the mount point list is copied from a
+         * different user namespace). */
+
+        if (needs_sandboxing && context->private_users && !userns_set_up) {
+                r = setup_private_users(saved_uid, saved_gid, uid, gid);
+                if (r < 0) {
+                        *exit_status = EXIT_USER;
+                        return log_exec_error_errno(context, params, r, "Failed to set up user namespacing: %m");
+                }
+        }
+
+        /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
+         * shall execute. */
+
+        _cleanup_free_ char *executable = NULL;
+        _cleanup_close_ int executable_fd = -EBADF;
+        r = find_executable_full(command->path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
+        if (r < 0) {
+                if (r != -ENOMEM && (command->flags & EXEC_COMMAND_IGNORE_FAILURE)) {
+                        log_exec_struct_errno(context, params, LOG_INFO, r,
+                                              "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
+                                              LOG_EXEC_INVOCATION_ID(params),
+                                              LOG_EXEC_MESSAGE(params,
+                                                               "Executable %s missing, skipping: %m",
+                                                               command->path),
+                                              "EXECUTABLE=%s", command->path);
+                        *exit_status = EXIT_SUCCESS;
+                        return 0;
+                }
+
+                *exit_status = EXIT_EXEC;
+                return log_exec_struct_errno(context, params, LOG_INFO, r,
+                                             "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
+                                             LOG_EXEC_INVOCATION_ID(params),
+                                             LOG_EXEC_MESSAGE(params,
+                                                              "Failed to locate executable %s: %m",
+                                                              command->path),
+                                             "EXECUTABLE=%s", command->path);
+        }
+
+        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, executable_fd, &executable_fd);
+        if (r < 0) {
+                *exit_status = EXIT_FDS;
+                return log_exec_error_errno(context, params, r, "Failed to shift fd and set FD_CLOEXEC: %m");
+        }
+
+#if HAVE_SELINUX
+        if (needs_sandboxing && use_selinux && params->selinux_context_net) {
+                int fd = -EBADF;
+
+                if (socket_fd >= 0)
+                        fd = socket_fd;
+                else if (params->n_socket_fds == 1)
+                        /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
+                         * use context from that fd to compute the label. */
+                        fd = params->fds[0];
+
+                if (fd >= 0) {
+                        r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
+                        if (r < 0) {
+                                if (!context->selinux_context_ignore) {
+                                        *exit_status = EXIT_SELINUX_CONTEXT;
+                                        return log_exec_error_errno(context,
+                                                                    params,
+                                                                    r,
+                                                                    "Failed to determine SELinux context: %m");
+                                }
+                                log_exec_debug_errno(context,
+                                                     params,
+                                                     r,
+                                                     "Failed to determine SELinux context, ignoring: %m");
+                        }
+                }
+        }
+#endif
+
+        /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that
+         * we are more aggressive this time, since we don't need socket_fd and the netns and ipcns fds any
+         * more. We do keep exec_fd however, if we have it, since we need to keep it open until the final
+         * execve(). */
+
+        r = close_all_fds(keep_fds, n_keep_fds);
+        if (r >= 0)
+                r = shift_fds(fds, n_fds);
+        if (r >= 0)
+                r = flags_fds(fds, n_socket_fds, n_fds, context->non_blocking);
+        if (r < 0) {
+                *exit_status = EXIT_FDS;
+                return log_exec_error_errno(context, params, r, "Failed to adjust passed file descriptors: %m");
+        }
+
+        /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
+         * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
+         * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
+         * came this far. */
+
+        secure_bits = context->secure_bits;
+
+        if (needs_sandboxing) {
+                uint64_t bset;
+
+                /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
+                 * (Note this is placed after the general resource limit initialization, see above, in order
+                 * to take precedence.) */
+                if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
+                        if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
+                                *exit_status = EXIT_LIMITS;
+                                return log_exec_error_errno(context, params, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
+                        }
+                }
+
+#if ENABLE_SMACK
+                /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
+                 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
+                if (use_smack && context->smack_process_label) {
+                        r = setup_smack(params, context, executable_fd);
+                        if (r < 0 && !context->smack_process_label_ignore) {
+                                *exit_status = EXIT_SMACK_PROCESS_LABEL;
+                                return log_exec_error_errno(context, params, r, "Failed to set SMACK process label: %m");
+                        }
+                }
+#endif
+
+                bset = context->capability_bounding_set;
+                /* If the ambient caps hack is enabled (which means the kernel can't do them, and the user asked for
+                 * our magic fallback), then let's add some extra caps, so that the service can drop privs of its own,
+                 * instead of us doing that */
+                if (needs_ambient_hack)
+                        bset |= (UINT64_C(1) << CAP_SETPCAP) |
+                                (UINT64_C(1) << CAP_SETUID) |
+                                (UINT64_C(1) << CAP_SETGID);
+
+                if (!cap_test_all(bset)) {
+                        r = capability_bounding_set_drop(bset, /* right_now= */ false);
+                        if (r < 0) {
+                                *exit_status = EXIT_CAPABILITIES;
+                                return log_exec_error_errno(context, params, r, "Failed to drop capabilities: %m");
+                        }
+                }
+
+                /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
+                 * keep-caps set.
+                 *
+                 * To be able to raise the ambient capabilities after setresuid() they have to be added to
+                 * the inherited set and keep caps has to be set (done in enforce_user()).  After setresuid()
+                 * the ambient capabilities can be raised as they are present in the permitted and
+                 * inhertiable set. However it is possible that someone wants to set ambient capabilities
+                 * without changing the user, so we also set the ambient capabilities here.
+                 *
+                 * The requested ambient capabilities are raised in the inheritable set if the second
+                 * argument is true. */
+                if (!needs_ambient_hack) {
+                        r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
+                        if (r < 0) {
+                                *exit_status = EXIT_CAPABILITIES;
+                                return log_exec_error_errno(context, params, r, "Failed to apply ambient capabilities (before UID change): %m");
+                        }
+                }
+        }
+
+        /* chroot to root directory first, before we lose the ability to chroot */
+        r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
+        if (r < 0)
+                return log_exec_error_errno(context, params, r, "Chrooting to the requested root directory failed: %m");
+
+        if (needs_setuid) {
+                if (uid_is_valid(uid)) {
+                        r = enforce_user(context, uid, capability_ambient_set);
+                        if (r < 0) {
+                                *exit_status = EXIT_USER;
+                                return log_exec_error_errno(context, params, r, "Failed to change UID to " UID_FMT ": %m", uid);
+                        }
+
+                        if (!needs_ambient_hack && capability_ambient_set != 0) {
+
+                                /* Raise the ambient capabilities after user change. */
+                                r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
+                                if (r < 0) {
+                                        *exit_status = EXIT_CAPABILITIES;
+                                        return log_exec_error_errno(context, params, r, "Failed to apply ambient capabilities (after UID change): %m");
+                                }
+                        }
+                }
+        }
+
+        /* Apply working directory here, because the working directory might be on NFS and only the user running
+         * this service might have the correct privilege to change to the working directory */
+        r = apply_working_directory(context, params, runtime, home, exit_status);
+        if (r < 0)
+                return log_exec_error_errno(context, params, r, "Changing to the requested working directory failed: %m");
+
+        if (needs_sandboxing) {
+                /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
+                 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
+                 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
+                 * are restricted. */
+
+#if HAVE_SELINUX
+                if (use_selinux) {
+                        char *exec_context = mac_selinux_context_net ?: context->selinux_context;
+
+                        if (exec_context) {
+                                r = setexeccon(exec_context);
+                                if (r < 0) {
+                                        if (!context->selinux_context_ignore) {
+                                                *exit_status = EXIT_SELINUX_CONTEXT;
+                                                return log_exec_error_errno(context, params, r, "Failed to change SELinux context to %s: %m", exec_context);
+                                        }
+                                        log_exec_debug_errno(context,
+                                                             params,
+                                                             r,
+                                                             "Failed to change SELinux context to %s, ignoring: %m",
+                                                             exec_context);
+                                }
+                        }
+                }
+#endif
+
+#if HAVE_APPARMOR
+                if (use_apparmor && context->apparmor_profile) {
+                        r = aa_change_onexec(context->apparmor_profile);
+                        if (r < 0 && !context->apparmor_profile_ignore) {
+                                *exit_status = EXIT_APPARMOR_PROFILE;
+                                return log_exec_error_errno(context,
+                                                            params,
+                                                            errno,
+                                                            "Failed to prepare AppArmor profile change to %s: %m",
+                                                            context->apparmor_profile);
+                        }
+                }
+#endif
+
+                /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
+                 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
+                 * requires CAP_SETPCAP. */
+                if (prctl(PR_GET_SECUREBITS) != secure_bits) {
+                        /* CAP_SETPCAP is required to set securebits. This capability is raised into the
+                         * effective set here.
+                         *
+                         * The effective set is overwritten during execve() with the following values:
+                         *
+                         * - ambient set (for non-root processes)
+                         *
+                         * - (inheritable | bounding) set for root processes)
+                         *
+                         * Hence there is no security impact to raise it in the effective set before execve
+                         */
+                        r = capability_gain_cap_setpcap(/* return_caps= */ NULL);
+                        if (r < 0) {
+                                *exit_status = EXIT_CAPABILITIES;
+                                return log_exec_error_errno(context, params, r, "Failed to gain CAP_SETPCAP for setting secure bits");
+                        }
+                        if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
+                                *exit_status = EXIT_SECUREBITS;
+                                return log_exec_error_errno(context, params, errno, "Failed to set process secure bits: %m");
+                        }
+                }
+
+                if (context_has_no_new_privileges(context))
+                        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
+                                *exit_status = EXIT_NO_NEW_PRIVILEGES;
+                                return log_exec_error_errno(context, params, errno, "Failed to disable new privileges: %m");
+                        }
+
+#if HAVE_SECCOMP
+                r = apply_address_families(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_ADDRESS_FAMILIES;
+                        return log_exec_error_errno(context, params, r, "Failed to restrict address families: %m");
+                }
+
+                r = apply_memory_deny_write_execute(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to disable writing to executable memory: %m");
+                }
+
+                r = apply_restrict_realtime(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to apply realtime restrictions: %m");
+                }
+
+                r = apply_restrict_suid_sgid(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to apply SUID/SGID restrictions: %m");
+                }
+
+                r = apply_restrict_namespaces(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to apply namespace restrictions: %m");
+                }
+
+                r = apply_protect_sysctl(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to apply sysctl restrictions: %m");
+                }
+
+                r = apply_protect_kernel_modules(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to apply module loading restrictions: %m");
+                }
+
+                r = apply_protect_kernel_logs(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to apply kernel log restrictions: %m");
+                }
+
+                r = apply_protect_clock(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to apply clock restrictions: %m");
+                }
+
+                r = apply_private_devices(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to set up private devices: %m");
+                }
+
+                r = apply_syscall_archs(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to apply syscall architecture restrictions: %m");
+                }
+
+                r = apply_lock_personality(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to lock personalities: %m");
+                }
+
+                r = apply_syscall_log(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to apply system call log filters: %m");
+                }
+
+                /* This really should remain the last step before the execve(), to make sure our own code is unaffected
+                 * by the filter as little as possible. */
+                r = apply_syscall_filter(context, params, needs_ambient_hack);
+                if (r < 0) {
+                        *exit_status = EXIT_SECCOMP;
+                        return log_exec_error_errno(context, params, r, "Failed to apply system call filters: %m");
+                }
+#endif
+
+#if HAVE_LIBBPF
+                r = apply_restrict_filesystems(context, params);
+                if (r < 0) {
+                        *exit_status = EXIT_BPF;
+                        return log_exec_error_errno(context, params, r, "Failed to restrict filesystems: %m");
+                }
+#endif
+
+        }
+
+        if (!strv_isempty(context->unset_environment)) {
+                char **ee = NULL;
+
+                ee = strv_env_delete(accum_env, 1, context->unset_environment);
+                if (!ee) {
+                        *exit_status = EXIT_MEMORY;
+                        return log_oom();
+                }
+
+                strv_free_and_replace(accum_env, ee);
+        }
+
+        if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
+                _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
+
+                r = replace_env_argv(command->argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
+                if (r < 0) {
+                        *exit_status = EXIT_MEMORY;
+                        return log_exec_error_errno(context,
+                                                    params,
+                                                    r,
+                                                    "Failed to replace environment variables: %m");
+                }
+                final_argv = replaced_argv;
+
+                if (!strv_isempty(unset_variables)) {
+                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
+                        log_exec_warning(context,
+                                         params,
+                                         "Referenced but unset environment variable evaluates to an empty string: %s",
+                                         strna(ju));
+                }
+
+                if (!strv_isempty(bad_variables)) {
+                        _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
+                        log_exec_warning(context,
+                                         params,
+                                         "Invalid environment variable name evaluates to an empty string: %s",
+                                         strna(jb));
+                }
+        } else
+                final_argv = command->argv;
+
+        log_command_line(context, params, "Executing", executable, final_argv);
+
+        if (exec_fd >= 0) {
+                uint8_t hot = 1;
+
+                /* We have finished with all our initializations. Let's now let the manager know that. From this point
+                 * on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
+
+                if (write(exec_fd, &hot, sizeof(hot)) < 0) {
+                        *exit_status = EXIT_EXEC;
+                        return log_exec_error_errno(context, params, errno, "Failed to enable exec_fd: %m");
+                }
+        }
+
+        r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
+
+        if (exec_fd >= 0) {
+                uint8_t hot = 0;
+
+                /* The execve() failed. This means the exec_fd is still open. Which means we need to tell the manager
+                 * that POLLHUP on it no longer means execve() succeeded. */
+
+                if (write(exec_fd, &hot, sizeof(hot)) < 0) {
+                        *exit_status = EXIT_EXEC;
+                        return log_exec_error_errno(context, params, errno, "Failed to disable exec_fd: %m");
+                }
+        }
+
+        *exit_status = EXIT_EXEC;
+        return log_exec_error_errno(context, params, r, "Failed to execute %s: %m", executable);
+}
diff --git a/src/core/exec-invoke.h b/src/core/exec-invoke.h
new file mode 100644 (file)
index 0000000..a8a3ac6
--- /dev/null
@@ -0,0 +1,16 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+#pragma once
+
+typedef struct ExecCommand ExecCommand;
+typedef struct ExecContext ExecContext;
+typedef struct ExecParameters ExecParameters;
+typedef struct ExecRuntime ExecRuntime;
+typedef struct CGroupContext CGroupContext;
+
+int exec_invoke(
+                const ExecCommand *command,
+                const ExecContext *context,
+                ExecParameters *params,
+                ExecRuntime *runtime,
+                const CGroupContext *cgroup_context,
+                int *exit_status);
diff --git a/src/core/execute-serialize.c b/src/core/execute-serialize.c
new file mode 100644 (file)
index 0000000..0d9204f
--- /dev/null
@@ -0,0 +1,4084 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+
+#include "af-list.h"
+#include "capability-util.h"
+#include "cgroup-setup.h"
+#include "escape.h"
+#include "exec-credential.h"
+#include "execute-serialize.h"
+#include "hexdecoct.h"
+#include "fd-util.h"
+#include "fileio.h"
+#include "in-addr-prefix-util.h"
+#include "parse-helpers.h"
+#include "parse-util.h"
+#include "percent-util.h"
+#include "process-util.h"
+#include "rlimit-util.h"
+#include "serialize.h"
+#include "string-util.h"
+#include "strv.h"
+
+static int exec_cgroup_context_serialize(const CGroupContext *c, FILE *f) {
+        _cleanup_free_ char *disable_controllers_str = NULL, *delegate_controllers_str = NULL,
+                            *cpuset_cpus = NULL, *cpuset_mems = NULL, *startup_cpuset_cpus = NULL,
+                            *startup_cpuset_mems = NULL;
+        char *iface;
+        struct in_addr_prefix *iaai;
+        int r;
+
+        assert(f);
+
+        if (!c)
+                return 0;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-cpu-accounting", c->cpu_accounting);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-io-accounting", c->io_accounting);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-block-io-accounting", c->blockio_accounting);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-memory-accounting", c->memory_accounting);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-tasks-accounting", c->tasks_accounting);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-ip-accounting", c->ip_accounting);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-memory-oom-group", c->memory_oom_group);
+        if (r < 0)
+                return r;
+
+        if (c->cpu_weight != CGROUP_WEIGHT_INVALID) {
+                r = serialize_item_format(f, "exec-cgroup-context-cpu-weight", "%" PRIu64, c->cpu_weight);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->startup_cpu_weight != CGROUP_WEIGHT_INVALID) {
+                r = serialize_item_format(f, "exec-cgroup-context-startup-cpu-weight", "%" PRIu64, c->startup_cpu_weight);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->cpu_shares != CGROUP_CPU_SHARES_INVALID) {
+                r = serialize_item_format(f, "exec-cgroup-context-cpu-shares", "%" PRIu64, c->cpu_shares);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->startup_cpu_shares != CGROUP_CPU_SHARES_INVALID) {
+                r = serialize_item_format(f, "exec-cgroup-context-startup-cpu-shares", "%" PRIu64, c->startup_cpu_shares);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->cpu_quota_per_sec_usec != USEC_INFINITY) {
+                r = serialize_usec(f, "exec-cgroup-context-cpu-quota-per-sec-usec", c->cpu_quota_per_sec_usec);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->cpu_quota_period_usec != USEC_INFINITY) {
+                r = serialize_usec(f, "exec-cgroup-context-cpu-quota-period-usec", c->cpu_quota_period_usec);
+                if (r < 0)
+                        return r;
+        }
+
+        cpuset_cpus = cpu_set_to_range_string(&c->cpuset_cpus);
+        if (!cpuset_cpus)
+                return log_oom_debug();
+
+        r = serialize_item(f, "exec-cgroup-context-allowed-cpus", cpuset_cpus);
+        if (r < 0)
+                return r;
+
+        startup_cpuset_cpus = cpu_set_to_range_string(&c->startup_cpuset_cpus);
+        if (!startup_cpuset_cpus)
+                return log_oom_debug();
+
+        r = serialize_item(f, "exec-cgroup-context-startup-allowed-cpus", startup_cpuset_cpus);
+        if (r < 0)
+                return r;
+
+        cpuset_mems = cpu_set_to_range_string(&c->cpuset_mems);
+        if (!cpuset_mems)
+                return log_oom_debug();
+
+        r = serialize_item(f, "exec-cgroup-context-allowed-memory-nodes", cpuset_mems);
+        if (r < 0)
+                return r;
+
+        startup_cpuset_mems = cpu_set_to_range_string(&c->startup_cpuset_mems);
+        if (!startup_cpuset_mems)
+                return log_oom_debug();
+
+        r = serialize_item(f, "exec-cgroup-context-startup-allowed-memory-nodes", startup_cpuset_mems);
+        if (r < 0)
+                return r;
+
+        if (c->io_weight != CGROUP_WEIGHT_INVALID) {
+                r = serialize_item_format(f, "exec-cgroup-context-io-weight", "%" PRIu64, c->io_weight);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->startup_io_weight != CGROUP_WEIGHT_INVALID) {
+                r = serialize_item_format(f, "exec-cgroup-context-startup-io-weight", "%" PRIu64, c->startup_io_weight);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID) {
+                r = serialize_item_format(f, "exec-cgroup-context-block-io-weight", "%" PRIu64, c->blockio_weight);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->startup_blockio_weight != CGROUP_BLKIO_WEIGHT_INVALID) {
+                r = serialize_item_format(f, "exec-cgroup-context-startup-block-io-weight", "%" PRIu64, c->startup_blockio_weight);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->default_memory_min > 0) {
+                r = serialize_item_format(f, "exec-cgroup-context-default-memory-min", "%" PRIu64, c->default_memory_min);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->default_memory_low > 0) {
+                r = serialize_item_format(f, "exec-cgroup-context-default-memory-low", "%" PRIu64, c->default_memory_low);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->memory_min > 0) {
+                r = serialize_item_format(f, "exec-cgroup-context-memory-min", "%" PRIu64, c->memory_min);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->memory_low > 0) {
+                r = serialize_item_format(f, "exec-cgroup-context-memory-low", "%" PRIu64, c->memory_low);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->startup_memory_low > 0) {
+                r = serialize_item_format(f, "exec-cgroup-context-startup-memory-low", "%" PRIu64, c->startup_memory_low);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->memory_high != CGROUP_LIMIT_MAX) {
+                r = serialize_item_format(f, "exec-cgroup-context-memory-high", "%" PRIu64, c->memory_high);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->startup_memory_high != CGROUP_LIMIT_MAX) {
+                r = serialize_item_format(f, "exec-cgroup-context-startup-memory-high", "%" PRIu64, c->startup_memory_high);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->memory_max != CGROUP_LIMIT_MAX) {
+                r = serialize_item_format(f, "exec-cgroup-context-memory-max", "%" PRIu64, c->memory_max);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->startup_memory_max != CGROUP_LIMIT_MAX) {
+                r = serialize_item_format(f, "exec-cgroup-context-startup-memory-max", "%" PRIu64, c->startup_memory_max);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->memory_swap_max != CGROUP_LIMIT_MAX) {
+                r = serialize_item_format(f, "exec-cgroup-context-memory-swap-max", "%" PRIu64, c->memory_swap_max);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->startup_memory_swap_max != CGROUP_LIMIT_MAX) {
+                r = serialize_item_format(f, "exec-cgroup-context-startup-memory-swap-max", "%" PRIu64, c->startup_memory_swap_max);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->memory_zswap_max != CGROUP_LIMIT_MAX) {
+                r = serialize_item_format(f, "exec-cgroup-context-memory-zswap-max", "%" PRIu64, c->memory_zswap_max);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->startup_memory_zswap_max != CGROUP_LIMIT_MAX) {
+                r = serialize_item_format(f, "exec-cgroup-context-startup-memory-zswap-max", "%" PRIu64, c->startup_memory_zswap_max);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->memory_limit != CGROUP_LIMIT_MAX) {
+                r = serialize_item_format(f, "exec-cgroup-context-memory-limit", "%" PRIu64, c->memory_limit);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->tasks_max.value != UINT64_MAX) {
+                r = serialize_item_format(f, "exec-cgroup-context-tasks-max-value", "%" PRIu64, c->tasks_max.value);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->tasks_max.scale > 0) {
+                r = serialize_item_format(f, "exec-cgroup-context-tasks-max-scale", "%" PRIu64, c->tasks_max.scale);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-default-memory-min-set", c->default_memory_min_set);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-default-memory-low-set", c->default_memory_low_set);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-default-startup-memory-low-set", c->default_startup_memory_low_set);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-memory-min-set", c->memory_min_set);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-memory-low-set", c->memory_low_set);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-startup-memory-low-set", c->startup_memory_low_set);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-startup-memory-high-set", c->startup_memory_high_set);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-startup-memory-max-set", c->startup_memory_max_set);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-startup-memory-swap-max-set", c->startup_memory_swap_max_set);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-startup-memory-zswap-max-set", c->startup_memory_zswap_max_set);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-cgroup-context-device-policy", cgroup_device_policy_to_string(c->device_policy));
+        if (r < 0)
+                return r;
+
+        r = cg_mask_to_string(c->disable_controllers, &disable_controllers_str);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-cgroup-context-disable-controllers", disable_controllers_str);
+        if (r < 0)
+                return r;
+
+        r = cg_mask_to_string(c->delegate_controllers, &delegate_controllers_str);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-cgroup-context-delegate-controllers", delegate_controllers_str);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-delegate", c->delegate);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-cgroup-context-managed-oom-swap", managed_oom_mode_to_string(c->moom_swap));
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-cgroup-context-managed-oom-memory-pressure", managed_oom_mode_to_string(c->moom_mem_pressure));
+        if (r < 0)
+                return r;
+
+        r = serialize_item_format(f, "exec-cgroup-context-managed-oom-memory-pressure-limit", "%" PRIu32, c->moom_mem_pressure_limit);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-cgroup-context-managed-oom-preference", managed_oom_preference_to_string(c->moom_preference));
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-cgroup-context-memory-pressure-watch", cgroup_pressure_watch_to_string(c->memory_pressure_watch));
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-cgroup-context-delegate-subgroup", c->delegate_subgroup);
+        if (r < 0)
+                return r;
+
+        if (c->memory_pressure_threshold_usec != USEC_INFINITY) {
+                r = serialize_usec(f, "exec-cgroup-context-memory-pressure-threshold-usec", c->memory_pressure_threshold_usec);
+                if (r < 0)
+                        return r;
+        }
+
+        LIST_FOREACH(device_allow, a, c->device_allow) {
+                r = serialize_item_format(f, "exec-cgroup-context-device-allow", "%s %s%s%s",
+                                          a->path,
+                                          a->r ? "r" : "", a->w ? "w" : "", a->m ? "m" : "");
+                if (r < 0)
+                        return r;
+        }
+
+        LIST_FOREACH(device_weights, iw, c->io_device_weights) {
+                r = serialize_item_format(f, "exec-cgroup-context-io-device-weight", "%s %" PRIu64,
+                                          iw->path,
+                                          iw->weight);
+                if (r < 0)
+                        return r;
+        }
+
+        LIST_FOREACH(device_latencies, l, c->io_device_latencies) {
+                r = serialize_item_format(f, "exec-cgroup-context-io-device-latency-target-usec", "%s " USEC_FMT,
+                                          l->path,
+                                          l->target_usec);
+                if (r < 0)
+                        return r;
+        }
+
+        LIST_FOREACH(device_limits, il, c->io_device_limits)
+                for (CGroupIOLimitType type = 0; type < _CGROUP_IO_LIMIT_TYPE_MAX; type++) {
+                        _cleanup_free_ char *key = NULL;
+
+                        if (il->limits[type] == cgroup_io_limit_defaults[type])
+                                continue;
+
+                        key = strjoin("exec-cgroup-context-io-device-limit-",
+                                        cgroup_io_limit_type_to_string(type));
+                        if (!key)
+                                return -ENOMEM;
+
+                        r = serialize_item_format(f, key, "%s %" PRIu64, il->path, il->limits[type]);
+                        if (r < 0)
+                                return r;
+                }
+
+        LIST_FOREACH(device_weights, w, c->blockio_device_weights) {
+                r = serialize_item_format(f, "exec-cgroup-context-blockio-device-weight", "%s %" PRIu64,
+                                          w->path,
+                                          w->weight);
+                if (r < 0)
+                        return r;
+        }
+
+        LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths) {
+                if (b->rbps != CGROUP_LIMIT_MAX) {
+                        r = serialize_item_format(f, "exec-cgroup-context-blockio-read-bandwidth", "%s %" PRIu64,
+                                                  b->path,
+                                                  b->rbps);
+                        if (r < 0)
+                                return r;
+                }
+                if (b->wbps != CGROUP_LIMIT_MAX) {
+                        r = serialize_item_format(f, "exec-cgroup-context-blockio-write-bandwidth", "%s %" PRIu64,
+                                                  b->path,
+                                                  b->wbps);
+                        if (r < 0)
+                                return r;
+                }
+        }
+
+        SET_FOREACH(iaai, c->ip_address_allow) {
+                r = serialize_item(f,
+                                   "exec-cgroup-context-ip-address-allow",
+                                   IN_ADDR_PREFIX_TO_STRING(iaai->family, &iaai->address, iaai->prefixlen));
+                if (r < 0)
+                        return r;
+        }
+        SET_FOREACH(iaai, c->ip_address_deny) {
+                r = serialize_item(f,
+                                   "exec-cgroup-context-ip-address-deny",
+                                   IN_ADDR_PREFIX_TO_STRING(iaai->family, &iaai->address, iaai->prefixlen));
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-ip-address-allow-reduced", c->ip_address_allow_reduced);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-cgroup-context-ip-address-deny-reduced", c->ip_address_deny_reduced);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-cgroup-context-ip-ingress-filter-path=", c->ip_filters_ingress);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-cgroup-context-ip-egress-filter-path=", c->ip_filters_egress);
+        if (r < 0)
+                return r;
+
+        LIST_FOREACH(programs, p, c->bpf_foreign_programs) {
+                r = serialize_item_format(f, "exec-cgroup-context-bpf-program", "%" PRIu32 " %s",
+                                          p->attach_type,
+                                          p->bpffs_path);
+                if (r < 0)
+                        return r;
+        }
+
+        LIST_FOREACH(socket_bind_items, bi, c->socket_bind_allow) {
+                fprintf(f, "exec-cgroup-context-socket-bind-allow=");
+                cgroup_context_dump_socket_bind_item(bi, f);
+                fputc('\n', f);
+        }
+
+        LIST_FOREACH(socket_bind_items, bi, c->socket_bind_deny) {
+                fprintf(f, "exec-cgroup-context-socket-bind-deny=");
+                cgroup_context_dump_socket_bind_item(bi, f);
+                fputc('\n', f);
+        }
+
+        SET_FOREACH(iface, c->restrict_network_interfaces) {
+                r = serialize_item(f, "exec-cgroup-context-restrict-network-interfaces", iface);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_bool_elide(
+                        f,
+                        "exec-cgroup-context-restrict-network-interfaces-is-allow-list",
+                        c->restrict_network_interfaces_is_allow_list);
+        if (r < 0)
+                return r;
+
+        fputc('\n', f); /* End marker */
+
+        return 0;
+}
+
+static int exec_cgroup_context_deserialize(CGroupContext *c, FILE *f) {
+        int r;
+
+        assert(f);
+
+        if (!c)
+                return 0;
+
+        for (;;) {
+                _cleanup_free_ char *l = NULL;
+                const char *val;
+
+                r = deserialize_read_line(f, &l);
+                if (r < 0)
+                        return r;
+                if (r == 0) /* eof or end marker */
+                        break;
+
+                if ((val = startswith(l, "exec-cgroup-context-cpu-accounting="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->cpu_accounting = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-io-accounting="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->io_accounting = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-block-io-accounting="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->blockio_accounting = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-accounting="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->memory_accounting = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-tasks-accounting="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->tasks_accounting = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-ip-accounting="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->ip_accounting = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-oom-group="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->memory_oom_group = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-cpu-weight="))) {
+                        r = safe_atou64(val, &c->cpu_weight);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-cpu-weight="))) {
+                        r = safe_atou64(val, &c->startup_cpu_weight);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-cpu-shares="))) {
+                        r = safe_atou64(val, &c->cpu_shares);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-cpu-shares="))) {
+                        r = safe_atou64(val, &c->startup_cpu_shares);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-cpu-quota-per-sec-usec="))) {
+                        r = deserialize_usec(val, &c->cpu_quota_per_sec_usec);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-cpu-quota-period-usec="))) {
+                        r = deserialize_usec(val, &c->cpu_quota_period_usec);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-allowed-cpus="))) {
+                        if (c->cpuset_cpus.set)
+                                return -EINVAL; /* duplicated */
+
+                        r = parse_cpu_set_full(
+                                        val,
+                                        &c->cpuset_cpus,
+                                        /* warn= */ false,
+                                        /* unit= */ NULL,
+                                        /* filename= */ NULL,
+                                        /* line= */ 0,
+                                        /* lvalue= */ NULL);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-allowed-cpus="))) {
+                        if (c->startup_cpuset_cpus.set)
+                                return -EINVAL; /* duplicated */
+
+                        r = parse_cpu_set_full(
+                                        val,
+                                        &c->startup_cpuset_cpus,
+                                        /* warn= */ false,
+                                        /* unit= */ NULL,
+                                        /* filename= */ NULL,
+                                        /* line= */ 0,
+                                        /* lvalue= */ NULL);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-allowed-memory-nodes="))) {
+                        if (c->cpuset_mems.set)
+                                return -EINVAL; /* duplicated */
+
+                        r = parse_cpu_set_full(
+                                        val,
+                                        &c->cpuset_mems,
+                                        /* warn= */ false,
+                                        /* unit= */ NULL,
+                                        /* filename= */ NULL,
+                                        /* line= */ 0,
+                                        /* lvalue= */ NULL);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-allowed-memory-nodes="))) {
+                        if (c->startup_cpuset_mems.set)
+                                return -EINVAL; /* duplicated */
+
+                        r = parse_cpu_set_full(
+                                        val,
+                                        &c->startup_cpuset_mems,
+                                        /* warn= */ false,
+                                        /* unit= */ NULL,
+                                        /* filename= */ NULL,
+                                        /* line= */ 0,
+                                        /* lvalue= */ NULL);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-io-weight="))) {
+                        r = safe_atou64(val, &c->io_weight);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-io-weight="))) {
+                        r = safe_atou64(val, &c->startup_io_weight);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-block-io-weight="))) {
+                        r = safe_atou64(val, &c->blockio_weight);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-block-io-weight="))) {
+                        r = safe_atou64(val, &c->startup_blockio_weight);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-default-memory-min="))) {
+                        r = safe_atou64(val, &c->default_memory_min);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-default-memory-low="))) {
+                        r = safe_atou64(val, &c->default_memory_low);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-min="))) {
+                        r = safe_atou64(val, &c->memory_min);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-low="))) {
+                        r = safe_atou64(val, &c->memory_low);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-memory-low="))) {
+                        r = safe_atou64(val, &c->startup_memory_low);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-high="))) {
+                        r = safe_atou64(val, &c->memory_high);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-memory-high="))) {
+                        r = safe_atou64(val, &c->startup_memory_high);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-max="))) {
+                        r = safe_atou64(val, &c->memory_max);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-memory-max="))) {
+                        r = safe_atou64(val, &c->startup_memory_max);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-swap-max="))) {
+                        r = safe_atou64(val, &c->memory_swap_max);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-memory-swap-max="))) {
+                        r = safe_atou64(val, &c->startup_memory_swap_max);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-zswap-max="))) {
+                        r = safe_atou64(val, &c->memory_zswap_max);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-memory-zswap-max="))) {
+                        r = safe_atou64(val, &c->startup_memory_zswap_max);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-limit="))) {
+                        r = safe_atou64(val, &c->memory_limit);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-tasks-max-value="))) {
+                        r = safe_atou64(val, &c->tasks_max.value);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-tasks-max-scale="))) {
+                        r = safe_atou64(val, &c->tasks_max.scale);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-default-memory-min-set="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->default_memory_min_set = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-default-memory-low-set="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->default_memory_low_set = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-default-startup-memory-low-set="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->default_startup_memory_low_set = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-min-set="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->memory_min_set = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-low-set="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->memory_low_set = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-memory-low-set="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->startup_memory_low_set = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-memory-high-set="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->startup_memory_high_set = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-memory-max-set="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->startup_memory_max_set = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-memory-swap-max-set="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->startup_memory_swap_max_set = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-startup-memory-zswap-max-set="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->startup_memory_zswap_max_set = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-device-policy="))) {
+                        c->device_policy = cgroup_device_policy_from_string(val);
+                        if (c->device_policy < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-cgroup-context-disable-controllers="))) {
+                        r = cg_mask_from_string(val, &c->disable_controllers);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-delegate-controllers="))) {
+                        r = cg_mask_from_string(val, &c->delegate_controllers);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-delegate="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->delegate = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-managed-oom-swap="))) {
+                        c->moom_swap = managed_oom_mode_from_string(val);
+                        if (c->moom_swap < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-cgroup-context-managed-oom-memory-pressure="))) {
+                        c->moom_mem_pressure = managed_oom_mode_from_string(val);
+                        if (c->moom_mem_pressure < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-cgroup-context-managed-oom-memory-pressure-limit="))) {
+                        r = safe_atou32(val, &c->moom_mem_pressure_limit);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-managed-oom-preference="))) {
+                        c->moom_preference = managed_oom_preference_from_string(val);
+                        if (c->moom_preference < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-pressure-watch="))) {
+                        c->memory_pressure_watch = cgroup_pressure_watch_from_string(val);
+                        if (c->memory_pressure_watch < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-cgroup-context-delegate-subgroup="))) {
+                        r = free_and_strdup(&c->delegate_subgroup, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-memory-pressure-threshold-usec="))) {
+                        r = deserialize_usec(val, &c->memory_pressure_threshold_usec);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-device-allow="))) {
+                        _cleanup_free_ char *path = NULL, *rwm = NULL;
+
+                        r = extract_many_words(&val, " ", 0, &path, &rwm, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r == 0)
+                                return -EINVAL;
+                        if (!isempty(rwm) && !in_charset(rwm, "rwm"))
+                                return -EINVAL;
+
+                        r = cgroup_context_add_or_update_device_allow(c, path, rwm);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-io-device-weight="))) {
+                        _cleanup_free_ char *path = NULL, *weight = NULL;
+                        CGroupIODeviceWeight *a = NULL;
+
+                        r = extract_many_words(&val, " ", 0, &path, &weight, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 2)
+                                return -EINVAL;
+
+                        LIST_FOREACH(device_weights, b, c->io_device_weights)
+                                if (path_equal(b->path, path)) {
+                                        a = b;
+                                        break;
+                                }
+
+                        if (!a) {
+                                a = new0(CGroupIODeviceWeight, 1);
+                                if (!a)
+                                        return log_oom_debug();
+
+                                a->path = TAKE_PTR(path);
+
+                                LIST_PREPEND(device_weights, c->io_device_weights, a);
+                        }
+
+                        r = safe_atou64(weight, &a->weight);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-io-device-latency-target-usec="))) {
+                        _cleanup_free_ char *path = NULL, *target = NULL;
+                        CGroupIODeviceLatency *a = NULL;
+
+                        r = extract_many_words(&val, " ", 0, &path, &target, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 2)
+                                return -EINVAL;
+
+                        LIST_FOREACH(device_latencies, b, c->io_device_latencies)
+                                if (path_equal(b->path, path)) {
+                                        a = b;
+                                        break;
+                                }
+
+                        if (!a) {
+                                a = new0(CGroupIODeviceLatency, 1);
+                                if (!a)
+                                        return log_oom_debug();
+
+                                a->path = TAKE_PTR(path);
+
+                                LIST_PREPEND(device_latencies, c->io_device_latencies, a);
+                        }
+
+                        r = deserialize_usec(target, &a->target_usec);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-io-device-limit-"))) {
+                        _cleanup_free_ char *type = NULL, *path = NULL, *limits = NULL;
+                        CGroupIODeviceLimit *limit = NULL;
+                        CGroupIOLimitType t;
+
+                        r = extract_many_words(&val, "= ", 0, &type, &path, &limits, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 3)
+                                return -EINVAL;
+
+                        t = cgroup_io_limit_type_from_string(type);
+                        if (t < 0)
+                                return t;
+
+                        LIST_FOREACH(device_limits, i, c->io_device_limits)
+                                if (path_equal(path, i->path)) {
+                                        limit = i;
+                                        break;
+                                }
+
+                        if (!limit) {
+                                limit = new0(CGroupIODeviceLimit, 1);
+                                if (!limit)
+                                        return log_oom_debug();
+
+                                limit->path = TAKE_PTR(path);
+                                for (CGroupIOLimitType i = 0; i < _CGROUP_IO_LIMIT_TYPE_MAX; i++)
+                                        limit->limits[i] = cgroup_io_limit_defaults[i];
+
+                                LIST_PREPEND(device_limits, c->io_device_limits, limit);
+                        }
+
+                        r = safe_atou64(limits, &limit->limits[t]);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-block-io-device-weight="))) {
+                        _cleanup_free_ char *path = NULL, *weight = NULL;
+                        CGroupBlockIODeviceWeight *a = NULL;
+
+                        r = extract_many_words(&val, " ", 0, &path, &weight, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 2)
+                                return -EINVAL;
+
+                        a = new0(CGroupBlockIODeviceWeight, 1);
+                        if (!a)
+                                return log_oom_debug();
+
+                        a->path = TAKE_PTR(path);
+
+                        LIST_PREPEND(device_weights, c->blockio_device_weights, a);
+
+                        r = safe_atou64(weight, &a->weight);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-block-io-read-bandwidth="))) {
+                        _cleanup_free_ char *path = NULL, *bw = NULL;
+                        CGroupBlockIODeviceBandwidth *a = NULL;
+
+                        r = extract_many_words(&val, " ", 0, &path, &bw, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 2)
+                                return -EINVAL;
+
+                        LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths)
+                                if (path_equal(b->path, path)) {
+                                        a = b;
+                                        break;
+                                }
+
+                        if (!a) {
+                                a = new0(CGroupBlockIODeviceBandwidth, 1);
+                                if (!a)
+                                        return log_oom_debug();
+
+                                a->path = TAKE_PTR(path);
+                                a->wbps = CGROUP_LIMIT_MAX;
+
+                                LIST_PREPEND(device_bandwidths, c->blockio_device_bandwidths, a);
+                        }
+
+                        r = safe_atou64(bw, &a->rbps);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-block-io-write-bandwidth="))) {
+                        _cleanup_free_ char *path = NULL, *bw = NULL;
+                        CGroupBlockIODeviceBandwidth *a = NULL;
+
+                        r = extract_many_words(&val, " ", 0, &path, &bw, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 2)
+                                return -EINVAL;
+
+                        LIST_FOREACH(device_bandwidths, b, c->blockio_device_bandwidths)
+                                if (path_equal(b->path, path)) {
+                                        a = b;
+                                        break;
+                                }
+
+                        if (!a) {
+                                a = new0(CGroupBlockIODeviceBandwidth, 1);
+                                if (!a)
+                                        return log_oom_debug();
+
+                                a->path = TAKE_PTR(path);
+                                a->rbps = CGROUP_LIMIT_MAX;
+
+                                LIST_PREPEND(device_bandwidths, c->blockio_device_bandwidths, a);
+                        }
+
+                        r = safe_atou64(bw, &a->wbps);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-ip-address-allow="))) {
+                        struct in_addr_prefix a;
+
+                        r = in_addr_prefix_from_string_auto(val, &a.family, &a.address, &a.prefixlen);
+                        if (r < 0)
+                                return r;
+
+                        r = in_addr_prefix_add(&c->ip_address_allow, &a);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-ip-address-deny="))) {
+                        struct in_addr_prefix a;
+
+                        r = in_addr_prefix_from_string_auto(val, &a.family, &a.address, &a.prefixlen);
+                        if (r < 0)
+                                return r;
+
+                        r = in_addr_prefix_add(&c->ip_address_deny, &a);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-ip-address-allow-reduced="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->ip_address_allow_reduced = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-ip-address-deny-reduced="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->ip_address_deny_reduced = r;
+                } else if ((val = startswith(l, "exec-cgroup-context-ip-ingress-filter-path="))) {
+                        r = deserialize_strv(&c->ip_filters_ingress, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-ip-egress-filter-path="))) {
+                        r = deserialize_strv(&c->ip_filters_egress, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-bpf-program="))) {
+                        _cleanup_free_ char *type = NULL, *path = NULL;
+                        uint32_t t;
+
+                        r = extract_many_words(&val, " ", 0, &type, &path, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 2)
+                                return -EINVAL;
+
+                        r = safe_atou32(type, &t);
+                        if (r < 0)
+                                return r;
+
+                        r = cgroup_context_add_bpf_foreign_program(c, t, path);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-socket-bind-allow="))) {
+                        CGroupSocketBindItem *item;
+                        uint16_t nr_ports, port_min;
+                        int af, ip_protocol;
+
+                        r = parse_socket_bind_item(val, &af, &ip_protocol, &nr_ports, &port_min);
+                        if (r < 0)
+                                return r;
+
+                        item = new(CGroupSocketBindItem, 1);
+                        if (!item)
+                                return log_oom_debug();
+                        *item = (CGroupSocketBindItem) {
+                                .address_family = af,
+                                .ip_protocol = ip_protocol,
+                                .nr_ports = nr_ports,
+                                .port_min = port_min,
+                        };
+
+                        LIST_PREPEND(socket_bind_items, c->socket_bind_allow, item);
+                } else if ((val = startswith(l, "exec-cgroup-context-socket-bind-deny="))) {
+                        CGroupSocketBindItem *item;
+                        uint16_t nr_ports, port_min;
+                        int af, ip_protocol;
+
+                        r = parse_socket_bind_item(val, &af, &ip_protocol, &nr_ports, &port_min);
+                        if (r < 0)
+                                return r;
+
+                        item = new(CGroupSocketBindItem, 1);
+                        if (!item)
+                                return log_oom_debug();
+                        *item = (CGroupSocketBindItem) {
+                                .address_family = af,
+                                .ip_protocol = ip_protocol,
+                                .nr_ports = nr_ports,
+                                .port_min = port_min,
+                        };
+
+                        LIST_PREPEND(socket_bind_items, c->socket_bind_deny, item);
+                } else if ((val = startswith(l, "exec-cgroup-context-restrict-network-interfaces="))) {
+                        r = set_ensure_allocated(&c->restrict_network_interfaces, &string_hash_ops);
+                        if (r < 0)
+                                return r;
+
+                        r = set_put_strdup(&c->restrict_network_interfaces, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-cgroup-context-restrict-network-interfaces-is-allow-list="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->restrict_network_interfaces_is_allow_list = r;
+                } else
+                        log_warning("Failed to parse serialized line, ignorning: %s", l);
+        }
+
+        return 0;
+}
+
+static int exec_runtime_serialize(const ExecRuntime *rt, FILE *f, FDSet *fds) {
+        int r;
+
+        assert(f);
+        assert(fds);
+
+        if (!rt) {
+                fputc('\n', f); /* End marker */
+                return 0;
+        }
+
+        if (rt->shared) {
+                r = serialize_item(f, "exec-runtime-id", rt->shared->id);
+                if (r < 0)
+                        return r;
+
+                r = serialize_item(f, "exec-runtime-tmp-dir", rt->shared->tmp_dir);
+                if (r < 0)
+                        return r;
+
+                r = serialize_item(f, "exec-runtime-var-tmp-dir", rt->shared->var_tmp_dir);
+                if (r < 0)
+                        return r;
+
+                if (rt->shared->netns_storage_socket[0] >= 0 && rt->shared->netns_storage_socket[1] >= 0) {
+                        int a, b;
+
+                        a = fdset_put_dup(fds, rt->shared->netns_storage_socket[0]);
+                        if (a < 0)
+                                return a;
+
+                        b = fdset_put_dup(fds, rt->shared->netns_storage_socket[1]);
+                        if (b < 0)
+                                return b;
+
+                        r = serialize_item_format(f, "exec-runtime-netns-storage-socket", "%d %d", a, b);
+                        if (r < 0)
+                                return r;
+                }
+
+                if (rt->shared->ipcns_storage_socket[0] >= 0 && rt->shared->ipcns_storage_socket[1] >= 0) {
+                        int a, b;
+
+                        a = fdset_put_dup(fds, rt->shared->ipcns_storage_socket[0]);
+                        if (a < 0)
+                                return a;
+
+                        b = fdset_put_dup(fds, rt->shared->ipcns_storage_socket[1]);
+                        if (b < 0)
+                                return b;
+
+                        r = serialize_item_format(f, "exec-runtime-ipcns-storage-socket", "%d %d", a, b);
+                        if (r < 0)
+                                return r;
+                }
+        }
+
+        if (rt->dynamic_creds) {
+                r = dynamic_user_serialize_one(rt->dynamic_creds->user, "exec-runtime-dynamic-creds-user", f, fds);
+                if (r < 0)
+                        return r;
+        }
+
+        if (rt->dynamic_creds && rt->dynamic_creds->group && rt->dynamic_creds->group == rt->dynamic_creds->user) {
+                r = serialize_bool(f, "exec-runtime-dynamic-creds-group-copy", true);
+                if (r < 0)
+                        return r;
+        } else if (rt->dynamic_creds) {
+                r = dynamic_user_serialize_one(rt->dynamic_creds->group, "exec-runtime-dynamic-creds-group", f, fds);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_item(f, "exec-runtime-ephemeral-copy", rt->ephemeral_copy);
+        if (r < 0)
+                return r;
+
+        if (rt->ephemeral_storage_socket[0] >= 0 && rt->ephemeral_storage_socket[1] >= 0) {
+                int a, b;
+
+                a = fdset_put_dup(fds, rt->ephemeral_storage_socket[0]);
+                if (a < 0)
+                        return a;
+
+                b = fdset_put_dup(fds, rt->ephemeral_storage_socket[1]);
+                if (b < 0)
+                        return b;
+
+                r = serialize_item_format(f, "exec-runtime-ephemeral-storage-socket", "%d %d", a, b);
+                if (r < 0)
+                        return r;
+        }
+
+        fputc('\n', f); /* End marker */
+
+        return 0;
+}
+
+static int exec_runtime_deserialize(ExecRuntime *rt, FILE *f, FDSet *fds) {
+        int r;
+
+        assert(rt);
+        assert(rt->shared);
+        assert(rt->dynamic_creds);
+        assert(f);
+        assert(fds);
+
+        for (;;) {
+                _cleanup_free_ char *l = NULL;
+                const char *val;
+
+                r = deserialize_read_line(f, &l);
+                if (r < 0)
+                        return r;
+                if (r == 0) /* eof or end marker */
+                        break;
+
+                if ((val = startswith(l, "exec-runtime-id="))) {
+                        r = free_and_strdup(&rt->shared->id, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-runtime-tmp-dir="))) {
+                        r = free_and_strdup(&rt->shared->tmp_dir, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-runtime-var-tmp-dir="))) {
+                        r = free_and_strdup(&rt->shared->var_tmp_dir, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-runtime-netns-storage-socket="))) {
+                        for (size_t i = 0; i < 2; ++i) {
+                                _cleanup_free_ char *w = NULL;
+                                int fd;
+
+                                r = extract_first_word(&val, &w, WHITESPACE, 0);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        break;
+
+                                if ((fd = parse_fd(w)) < 0 || !fdset_contains(fds, fd))
+                                        log_debug("Failed to parse %s value: %s, ignoring.", l, w);
+                                else {
+                                        r = fdset_remove(fds, fd);
+                                        if (r < 0) {
+                                                log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                                continue;
+                                        }
+
+                                        rt->shared->netns_storage_socket[i] = fd;
+                                }
+                        }
+                } else if ((val = startswith(l, "exec-runtime-ipcns-storage-socket="))) {
+                        for (size_t i = 0; i < 2; ++i) {
+                                _cleanup_free_ char *w = NULL;
+                                int fd;
+
+                                r = extract_first_word(&val, &w, WHITESPACE, 0);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        break;
+
+                                if ((fd = parse_fd(w)) < 0 || !fdset_contains(fds, fd))
+                                        log_debug("Failed to parse %s value: %s, ignoring.", l, w);
+                                else {
+                                        r = fdset_remove(fds, fd);
+                                        if (r < 0) {
+                                                log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                                continue;
+                                        }
+
+                                        rt->shared->ipcns_storage_socket[i] = fd;
+                                }
+                        }
+                } else if ((val = startswith(l, "exec-runtime-dynamic-creds-user=")))
+                        dynamic_user_deserialize_one(/* m= */ NULL, val, fds, &rt->dynamic_creds->user);
+                else if ((val = startswith(l, "exec-runtime-dynamic-creds-group=")))
+                        dynamic_user_deserialize_one(/* m= */ NULL, val, fds, &rt->dynamic_creds->group);
+                else if ((val = startswith(l, "exec-runtime-dynamic-creds-group-copy="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        if (!r)
+                                continue; /* Nothing to do */
+
+                        if (!rt->dynamic_creds->user)
+                                return -EINVAL;
+
+                        rt->dynamic_creds->group = dynamic_user_ref(rt->dynamic_creds->user);
+                } else if ((val = startswith(l, "exec-runtime-ephemeral-copy="))) {
+                        r = free_and_strdup(&rt->ephemeral_copy, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-runtime-ephemeral-storage-socket="))) {
+                        for (size_t i = 0; i < 2; ++i) {
+                                _cleanup_free_ char *w = NULL;
+                                int fd;
+
+                                r = extract_first_word(&val, &w, WHITESPACE, 0);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        break;
+
+                                if ((fd = parse_fd(w)) < 0 || !fdset_contains(fds, fd))
+                                        log_debug("Failed to parse %s value: %s, ignoring.", l, w);
+                                else {
+                                        r = fdset_remove(fds, fd);
+                                        if (r < 0) {
+                                                log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                                continue;
+                                        }
+
+                                        rt->ephemeral_storage_socket[i] = fd;
+                                }
+                        }
+                } else
+                        log_warning("Failed to parse serialized line, ignorning: %s", l);
+        }
+
+        return 0;
+}
+
+static int exec_parameters_serialize(const ExecParameters *p, FILE *f, FDSet *fds) {
+        int r;
+
+        assert(f);
+        assert(fds);
+
+        if (!p)
+                return 0;
+
+        r = serialize_item(f, "exec-parameters-runtime-scope", runtime_scope_to_string(p->runtime_scope));
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-parameters-environment", p->environment);
+        if (r < 0)
+                return r;
+
+        if (p->n_socket_fds) {
+                r = serialize_item_format(f, "exec-parameters-n-socket-fds", "%zu", p->n_socket_fds);
+                if (r < 0)
+                        return r;
+        }
+
+        if (p->n_storage_fds) {
+                r = serialize_item_format(f, "exec-parameters-n-storage-fds", "%zu", p->n_storage_fds);
+                if (r < 0)
+                        return r;
+        }
+
+        if (p->n_socket_fds + p->n_storage_fds > 0) {
+                _cleanup_free_ char *serialized_fds = NULL;
+
+                if (!p->fds)
+                        return -EINVAL;
+
+                for (size_t i = 0; i < p->n_socket_fds + p->n_storage_fds; ++i) {
+                        int copy = -EBADF;
+
+                        if (p->fds[i] >= 0) {
+                                copy = fdset_put_dup(fds, p->fds[i]);
+                                if (copy < 0)
+                                        return copy;
+                        }
+
+                        r = strextendf(&serialized_fds, "%d ", copy);
+                        if (r < 0)
+                                return r;
+                }
+
+                r = serialize_item(f, "exec-parameters-fds", serialized_fds);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_strv(f, "exec-parameters-fd-names", p->fd_names);
+        if (r < 0)
+                return r;
+
+        if (p->flags != 0) {
+                r = serialize_item_format(f, "exec-parameters-flags", "%u", (unsigned) p->flags);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_bool_elide(f, "exec-parameters-selinux-context-net", p->selinux_context_net);
+        if (r < 0)
+                return r;
+
+        if (p->cgroup_supported != 0) {
+                r = serialize_item_format(f, "exec-parameters-cgroup-supported", "%u", (unsigned) p->cgroup_supported);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_item(f, "exec-parameters-cgroup-path", p->cgroup_path);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_format(f, "exec-parameters-cgroup-id", "%" PRIu64, p->cgroup_id);
+        if (r < 0)
+                return r;
+
+        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
+                _cleanup_free_ char *key = NULL;
+
+                key = strjoin("exec-parameters-prefix-directories-", exec_directory_type_to_string(dt));
+                if (!key)
+                        return log_oom_debug();
+
+                /* Always serialize, even an empty prefix, as this is a fixed array and we always expect
+                 * to have all elements (unless fuzzing is happening, hence the NULL check). */
+                r = serialize_item(f, key, strempty(p->prefix ? p->prefix[dt] : NULL));
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_item(f, "exec-parameters-received-credentials-directory", p->received_credentials_directory);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-parameters-received-encrypted-credentials-directory", p->received_encrypted_credentials_directory);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-parameters-confirm-spawn", p->confirm_spawn);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-parameters-shall-confirm-spawn", p->shall_confirm_spawn);
+        if (r < 0)
+                return r;
+
+        if (p->watchdog_usec > 0) {
+                r = serialize_usec(f, "exec-parameters-watchdog-usec", p->watchdog_usec);
+                if (r < 0)
+                        return r;
+        }
+
+        if (p->idle_pipe) {
+                _cleanup_free_ char *serialized_fds = NULL;
+
+                for (size_t i = 0; i < 4; ++i) {
+                        int copy = -EBADF;
+
+                        if (p->idle_pipe[i] >= 0) {
+                                copy = fdset_put_dup(fds, p->idle_pipe[i]);
+                                if (copy < 0)
+                                        return copy;
+                        }
+
+                        r = strextendf(&serialized_fds, "%d ", copy);
+                        if (r < 0)
+                                return r;
+                }
+
+                r = serialize_item(f, "exec-parameters-idle-pipe", serialized_fds);
+                if (r < 0)
+                        return r;
+        }
+
+        if (p->stdin_fd >= 0) {
+                r = serialize_fd(f, fds, "exec-parameters-stdin-fd", p->stdin_fd);
+                if (r < 0)
+                        return r;
+        }
+
+        if (p->stdout_fd >= 0) {
+                r = serialize_fd(f, fds, "exec-parameters-stdout-fd", p->stdout_fd);
+                if (r < 0)
+                        return r;
+        }
+
+        if (p->stderr_fd >= 0) {
+                r = serialize_fd(f, fds, "exec-parameters-stderr-fd", p->stderr_fd);
+                if (r < 0)
+                        return r;
+        }
+
+        if (p->exec_fd >= 0) {
+                r = serialize_fd(f, fds, "exec-parameters-exec-fd", p->exec_fd);
+                if (r < 0)
+                        return r;
+        }
+
+        if (p->bpf_outer_map_fd >= 0) {
+                r = serialize_fd(f, fds, "exec-parameters-bpf-outer-map-fd", p->bpf_outer_map_fd);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_item(f, "exec-parameters-notify-socket", p->notify_socket);
+        if (r < 0)
+                return r;
+
+        LIST_FOREACH(open_files, file, p->open_files) {
+                _cleanup_free_ char *ofs = NULL;
+
+                r = open_file_to_string(file, &ofs);
+                if (r < 0)
+                        return r;
+
+                r = serialize_item(f, "exec-parameters-open-file", ofs);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_item(f, "exec-parameters-fallback-smack-process-label", p->fallback_smack_process_label);
+        if (r < 0)
+                return r;
+
+        if (p->user_lookup_fd >= 0) {
+                r = serialize_fd(f, fds, "exec-parameters-user-lookup-fd", p->user_lookup_fd);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_strv(f, "exec-parameters-files-env", p->files_env);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-parameters-unit-id", p->unit_id);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-parameters-invocation-id-string", p->invocation_id_string);
+        if (r < 0)
+                return r;
+
+        fputc('\n', f); /* End marker */
+
+        return 0;
+}
+
+static int exec_parameters_deserialize(ExecParameters *p, FILE *f, FDSet *fds) {
+        int r, nr_open;
+
+        assert(p);
+        assert(f);
+        assert(fds);
+
+        nr_open = read_nr_open();
+        if (nr_open < 3)
+                nr_open = HIGH_RLIMIT_NOFILE;
+        assert(nr_open > 0); /* For compilers/static analyzers */
+
+        for (;;) {
+                _cleanup_free_ char *l = NULL;
+                const char *val;
+
+                r = deserialize_read_line(f, &l);
+                if (r < 0)
+                        return r;
+                if (r == 0) /* eof or end marker */
+                        break;
+
+                if ((val = startswith(l, "exec-parameters-runtime-scope="))) {
+                        p->runtime_scope = runtime_scope_from_string(val);
+                        if (p->runtime_scope < 0)
+                                return p->runtime_scope;
+                } else if ((val = startswith(l, "exec-parameters-environment="))) {
+                        r = deserialize_strv(&p->environment, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-n-socket-fds="))) {
+                        if (p->fds)
+                                return -EINVAL; /* Already received */
+
+                        r = safe_atozu(val, &p->n_socket_fds);
+                        if (r < 0)
+                                return r;
+
+                        if (p->n_socket_fds > (size_t) nr_open)
+                                return -EINVAL; /* too many, someone is playing games with us */
+                } else if ((val = startswith(l, "exec-parameters-n-storage-fds="))) {
+                        if (p->fds)
+                                return -EINVAL; /* Already received */
+
+                        r = safe_atozu(val, &p->n_storage_fds);
+                        if (r < 0)
+                                return r;
+
+                        if (p->n_storage_fds > (size_t) nr_open)
+                                return -EINVAL; /* too many, someone is playing games with us */
+                } else if ((val = startswith(l, "exec-parameters-fds="))) {
+                        if (p->n_socket_fds + p->n_storage_fds == 0)
+                                return log_warning_errno(
+                                                SYNTHETIC_ERRNO(EINVAL),
+                                                "Got exec-parameters-fds= without "
+                                                "prior exec-parameters-n-socket-fds= or exec-parameters-n-storage-fds=");
+                        if (p->n_socket_fds + p->n_storage_fds > (size_t) nr_open)
+                                return -EINVAL; /* too many, someone is playing games with us */
+
+                        if (p->fds)
+                                return -EINVAL; /* duplicated */
+
+                        p->fds = new(int, p->n_socket_fds + p->n_storage_fds);
+                        if (!p->fds)
+                                return log_oom_debug();
+
+                        /* Ensure we don't leave any FD uninitialized on error, it makes the fuzzer sad */
+                        for (size_t i = 0; i < p->n_socket_fds + p->n_storage_fds; ++i)
+                                p->fds[i] = -EBADF;
+
+                        for (size_t i = 0; i < p->n_socket_fds + p->n_storage_fds; ++i) {
+                                _cleanup_free_ char *w = NULL;
+                                int fd;
+
+                                r = extract_first_word(&val, &w, WHITESPACE, 0);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        break;
+
+                                if ((fd = parse_fd(w)) < 0 || !fdset_contains(fds, fd))
+                                        log_debug("Failed to parse %s value: %s, ignoring.", l, w);
+                                else {
+                                        r = fdset_remove(fds, fd);
+                                        if (r < 0) {
+                                                log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                                continue;
+                                        }
+
+                                        p->fds[i] = fd;
+                                }
+                        }
+                } else if ((val = startswith(l, "exec-parameters-fd-names="))) {
+                        r = deserialize_strv(&p->fd_names, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-flags="))) {
+                        unsigned flags;
+
+                        r = safe_atou(val, &flags);
+                        if (r < 0)
+                                return r;
+                        p->flags = flags;
+                } else if ((val = startswith(l, "exec-parameters-selinux-context-net="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+
+                        p->selinux_context_net = r;
+                } else if ((val = startswith(l, "exec-parameters-cgroup-supported="))) {
+                        unsigned cgroup_supported;
+
+                        r = safe_atou(val, &cgroup_supported);
+                        if (r < 0)
+                                return r;
+                        p->cgroup_supported = cgroup_supported;
+                } else if ((val = startswith(l, "exec-parameters-cgroup-path="))) {
+                        r = free_and_strdup(&p->cgroup_path, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-cgroup-id="))) {
+                        r = safe_atou64(val, &p->cgroup_id);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-prefix-directories-"))) {
+                        _cleanup_free_ char *type = NULL, *prefix = NULL;
+                        ExecDirectoryType dt;
+
+                        r = extract_many_words(&val, "= ", 0, &type, &prefix, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r == 0)
+                                return -EINVAL;
+
+                        dt = exec_directory_type_from_string(type);
+                        if (dt < 0)
+                                return -EINVAL;
+
+                        if (!p->prefix) {
+                                p->prefix = new0(char*, _EXEC_DIRECTORY_TYPE_MAX+1);
+                                if (!p->prefix)
+                                        return log_oom_debug();
+                        }
+
+                        if (isempty(prefix))
+                                p->prefix[dt] = mfree(p->prefix[dt]);
+                        else
+                                free_and_replace(p->prefix[dt], prefix);
+                } else if ((val = startswith(l, "exec-parameters-received-credentials-directory="))) {
+                        r = free_and_strdup(&p->received_credentials_directory, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-received-encrypted-credentials-directory="))) {
+                        r = free_and_strdup(&p->received_encrypted_credentials_directory, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-confirm-spawn="))) {
+                        r = free_and_strdup(&p->confirm_spawn, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-shall-confirm-spawn="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+
+                        p->shall_confirm_spawn = r;
+                } else if ((val = startswith(l, "exec-parameters-watchdog-usec="))) {
+                        r = deserialize_usec(val, &p->watchdog_usec);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-idle-pipe="))) {
+                        if (p->idle_pipe)
+                                return -EINVAL; /* duplicated */
+
+                        p->idle_pipe = new(int, 4);
+                        if (!p->idle_pipe)
+                                return log_oom_debug();
+
+                        p->idle_pipe[0] = p->idle_pipe[1] = p->idle_pipe[2] = p->idle_pipe[3] = -EBADF;
+
+                        for (size_t i = 0; i < 4; ++i) {
+                                _cleanup_free_ char *w = NULL;
+                                int fd;
+
+                                r = extract_first_word(&val, &w, WHITESPACE, 0);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        break;
+
+                                if ((fd = parse_fd(w)) < 0 || !fdset_contains(fds, fd))
+                                        log_debug("Failed to parse %s value: %s, ignoring.", l, w);
+                                else {
+                                        r = fdset_remove(fds, fd);
+                                        if (r < 0) {
+                                                log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                                continue;
+                                        }
+
+                                        p->idle_pipe[i] = fd;
+                                }
+                        }
+                } else if ((val = startswith(l, "exec-parameters-stdin-fd="))) {
+                        int fd;
+
+                        if ((fd = parse_fd(val)) < 0 || !fdset_contains(fds, fd))
+                                log_debug("Failed to parse %s value: %s, ignoring.", l, val);
+                        else {
+                                r = fdset_remove(fds, fd);
+                                if (r < 0) {
+                                        log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                        continue;
+                                }
+
+                                p->stdin_fd = fd;
+                        }
+                } else if ((val = startswith(l, "exec-parameters-stdout-fd="))) {
+                        int fd;
+
+                        if ((fd = parse_fd(val)) < 0 || !fdset_contains(fds, fd))
+                                log_debug("Failed to parse %s value: %s, ignoring.", l, val);
+                        else {
+                                r = fdset_remove(fds, fd);
+                                if (r < 0) {
+                                        log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                        continue;
+                                }
+
+                                p->stdout_fd = fd;
+                        }
+                } else if ((val = startswith(l, "exec-parameters-stderr-fd="))) {
+                        int fd;
+
+                        if ((fd = parse_fd(val)) < 0 || !fdset_contains(fds, fd))
+                                log_debug("Failed to parse %s value: %s, ignoring.", l, val);
+                        else {
+                                r = fdset_remove(fds, fd);
+                                if (r < 0) {
+                                        log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                        continue;
+                                }
+
+                                p->stderr_fd = fd;
+                        }
+                } else if ((val = startswith(l, "exec-parameters-exec-fd="))) {
+                        int fd;
+
+                        if ((fd = parse_fd(val)) < 0 || !fdset_contains(fds, fd))
+                                log_debug("Failed to parse %s value: %s, ignoring.", l, val);
+                        else {
+                                r = fdset_remove(fds, fd);
+                                if (r < 0) {
+                                        log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                        continue;
+                                }
+
+                                /* This is special and relies on close-on-exec semantics, make sure it's
+                                 * there */
+                                r = fd_cloexec(fd, true);
+                                if (r < 0)
+                                        return r;
+
+                                p->exec_fd = fd;
+                        }
+                } else if ((val = startswith(l, "exec-parameters-bpf-outer-map-fd="))) {
+                        int fd;
+
+                        if ((fd = parse_fd(val)) < 0 || !fdset_contains(fds, fd))
+                                log_debug("Failed to parse %s value: %s, ignoring.", l, val);
+                        else {
+                                r = fdset_remove(fds, fd);
+                                if (r < 0) {
+                                        log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                        continue;
+                                }
+
+                                p->bpf_outer_map_fd = fd;
+                        }
+                } else if ((val = startswith(l, "exec-parameters-notify-socket="))) {
+                        r = free_and_strdup(&p->notify_socket, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-open-file="))) {
+                        OpenFile *of = NULL;
+
+                        r = open_file_parse(val, &of);
+                        if (r < 0)
+                                return r;
+
+                        LIST_APPEND(open_files, p->open_files, of);
+                } else if ((val = startswith(l, "exec-parameters-fallback-smack-process-label="))) {
+                        r = free_and_strdup(&p->fallback_smack_process_label, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-user-lookup-fd="))) {
+                        int fd;
+
+                        if ((fd = parse_fd(val)) < 0 || !fdset_contains(fds, fd))
+                                log_debug("Failed to parse %s value: %s, ignoring.", l, val);
+                        else {
+                                r = fdset_remove(fds, fd);
+                                if (r < 0) {
+                                        log_debug_errno(r, "Failed to remove %s value=%d from fdset, ignoring: %m", l, fd);
+                                        continue;
+                                }
+
+                                p->user_lookup_fd = fd;
+                        }
+                } else if ((val = startswith(l, "exec-parameters-files-env="))) {
+                        r = deserialize_strv(&p->files_env, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-unit-id="))) {
+                        r = free_and_strdup(&p->unit_id, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-parameters-invocation-id-string="))) {
+                        if (strlen(val) > SD_ID128_STRING_MAX - 1)
+                                return -EINVAL;
+
+                        r = sd_id128_from_string(val, &p->invocation_id);
+                        if (r < 0)
+                                return r;
+
+                        sd_id128_to_string(p->invocation_id, p->invocation_id_string);
+                } else
+                        log_warning("Failed to parse serialized line, ignorning: %s", l);
+        }
+
+        /* Bail out if we got exec-parameters-n-{socket/storage}-fds= but no corresponding
+         * exec-parameters-fds= */
+        if (p->n_socket_fds + p->n_storage_fds > 0 && !p->fds)
+                return -EINVAL;
+
+        return 0;
+}
+
+static int serialize_std_out_err(const ExecContext *c, FILE *f, int fileno) {
+        char *key, *value;
+        const char *type;
+
+        assert(c);
+        assert(f);
+        assert(IN_SET(fileno, STDOUT_FILENO, STDERR_FILENO));
+
+        type = fileno == STDOUT_FILENO ? "output" : "error";
+
+        switch (fileno == STDOUT_FILENO ? c->std_output : c->std_error) {
+        case EXEC_OUTPUT_NAMED_FD:
+                key = strjoina("exec-context-std-", type, "-fd-name");
+                value = c->stdio_fdname[fileno];
+
+                break;
+
+        case EXEC_OUTPUT_FILE:
+                key = strjoina("exec-context-std-", type, "-file");
+                value = c->stdio_file[fileno];
+
+                break;
+
+        case EXEC_OUTPUT_FILE_APPEND:
+                key = strjoina("exec-context-std-", type, "-file-append");
+                value = c->stdio_file[fileno];
+
+                break;
+
+        case EXEC_OUTPUT_FILE_TRUNCATE:
+                key = strjoina("exec-context-std-", type, "-file-truncate");
+                value = c->stdio_file[fileno];
+
+                break;
+
+        default:
+                return 0;
+        }
+
+        return serialize_item(f, key, value);
+}
+
+static int exec_context_serialize(const ExecContext *c, FILE *f) {
+        int r;
+
+        assert(f);
+
+        if (!c)
+                return 0;
+
+        r = serialize_strv(f, "exec-context-environment", c->environment);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-context-environment-files", c->environment_files);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-context-pass-environment", c->pass_environment);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-context-unset-environment", c->unset_environment);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-working-directory", c->working_directory);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-root-directory", c->root_directory);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-root-image", c->root_image);
+        if (r < 0)
+                return r;
+
+        if (c->root_image_options) {
+                _cleanup_free_ char *options = NULL;
+
+                LIST_FOREACH(mount_options, o, c->root_image_options) {
+                        if (isempty(o->options))
+                                continue;
+
+                        _cleanup_free_ char *escaped = NULL;
+                        escaped = shell_escape(o->options, ":");
+                        if (!escaped)
+                                return log_oom_debug();
+
+                        if (!strextend(&options,
+                                        " ",
+                                        partition_designator_to_string(o->partition_designator),
+                                               ":",
+                                               escaped))
+                                        return log_oom_debug();
+                }
+
+                r = serialize_item(f, "exec-context-root-image-options", options);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_item(f, "exec-context-root-verity", c->root_verity);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-root-hash-path", c->root_hash_path);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-root-hash-sig-path", c->root_hash_sig_path);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_hexmem(f, "exec-context-root-hash", c->root_hash, c->root_hash_size);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_base64mem(f, "exec-context-root-hash-sig", c->root_hash_sig, c->root_hash_sig_size);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-root-ephemeral", c->root_ephemeral);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_format(f, "exec-context-umask", "%04o", c->umask);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-non-blocking", c->non_blocking);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_tristate(f, "exec-context-private-mounts", c->private_mounts);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_tristate(f, "exec-context-memory-ksm", c->memory_ksm);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-private-tmp", c->private_tmp);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-private-devices", c->private_devices);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-protect-kernel-tunables", c->protect_kernel_tunables);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-protect-kernel-modules", c->protect_kernel_modules);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-protect-kernel-logs", c->protect_kernel_logs);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-protect-clock", c->protect_clock);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-protect-control-groups", c->protect_control_groups);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-private-network", c->private_network);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-private-users", c->private_users);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-private-ipc", c->private_ipc);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-remove-ipc", c->remove_ipc);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-protect-home", protect_home_to_string(c->protect_home));
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-protect-system", protect_system_to_string(c->protect_system));
+        if (r < 0)
+                return r;
+
+        if (c->mount_apivfs_set) {
+                r = serialize_bool(f, "exec-context-mount-api-vfs", c->mount_apivfs);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_bool_elide(f, "exec-context-same-pgrp", c->same_pgrp);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-cpu-sched-reset-on-fork", c->cpu_sched_reset_on_fork);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool(f, "exec-context-ignore-sigpipe", c->ignore_sigpipe);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-memory-deny-write-execute", c->memory_deny_write_execute);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-restrict-realtime", c->restrict_realtime);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-restrict-suid-sgid", c->restrict_suid_sgid);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-keyring-mode", exec_keyring_mode_to_string(c->keyring_mode));
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-protect-hostname", c->protect_hostname);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-protect-proc", protect_proc_to_string(c->protect_proc));
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-proc-subset", proc_subset_to_string(c->proc_subset));
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-runtime-directory-preserve-mode", exec_preserve_mode_to_string(c->runtime_directory_preserve_mode));
+        if (r < 0)
+                return r;
+
+        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
+                _cleanup_free_ char *key = NULL, *value = NULL;
+
+                key = strjoin("exec-context-directories-", exec_directory_type_to_string(dt));
+                if (!key)
+                        return log_oom_debug();
+
+                if (asprintf(&value, "%04o", c->directories[dt].mode) < 0)
+                        return log_oom_debug();
+
+                for (size_t i = 0; i < c->directories[dt].n_items; i++) {
+                        _cleanup_free_ char *path_escaped = NULL;
+
+                        path_escaped = shell_escape(c->directories[dt].items[i].path, ":");
+                        if (!path_escaped)
+                                return log_oom_debug();
+
+                        if (!strextend(&value, " ", path_escaped))
+                                return log_oom_debug();
+
+                        if (!strextend(&value, ":", yes_no(c->directories[dt].items[i].only_create)))
+                                return log_oom_debug();
+
+                        STRV_FOREACH(d, c->directories[dt].items[i].symlinks) {
+                                _cleanup_free_ char *link_escaped = NULL;
+
+                                link_escaped = shell_escape(*d, ":");
+                                if (!link_escaped)
+                                        return log_oom_debug();
+
+                                if (!strextend(&value, ":", link_escaped))
+                                        return log_oom_debug();
+                        }
+                }
+
+                r = serialize_item(f, key, value);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_usec(f, "exec-context-timeout-clean-usec", c->timeout_clean_usec);
+        if (r < 0)
+                return r;
+
+        if (c->nice_set) {
+                r = serialize_item_format(f, "exec-context-nice", "%i", c->nice);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_bool_elide(f, "exec-context-working-directory-missing-ok", c->working_directory_missing_ok);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-working-directory-home", c->working_directory_home);
+        if (r < 0)
+                return r;
+
+        if (c->oom_score_adjust_set) {
+                r = serialize_item_format(f, "exec-context-oom-score-adjust", "%i", c->oom_score_adjust);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->coredump_filter_set) {
+                r = serialize_item_format(f, "exec-context-coredump-filter", "%"PRIx64, c->coredump_filter);
+                if (r < 0)
+                        return r;
+        }
+
+        for (unsigned i = 0; i < RLIM_NLIMITS; i++) {
+                _cleanup_free_ char *key = NULL, *limit = NULL;
+
+                if (!c->rlimit[i])
+                        continue;
+
+                key = strjoin("exec-context-limit-", rlimit_to_string(i));
+                if (!key)
+                        return log_oom_debug();
+
+                r = rlimit_format(c->rlimit[i], &limit);
+                if (r < 0)
+                        return r;
+
+                r = serialize_item(f, key, limit);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->ioprio_set) {
+                r = serialize_item_format(f, "exec-context-ioprio", "%d", c->ioprio);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->cpu_sched_set) {
+                _cleanup_free_ char *policy_str = NULL;
+
+                r = sched_policy_to_string_alloc(c->cpu_sched_policy, &policy_str);
+                if (r < 0)
+                        return r;
+
+                r = serialize_item(f, "exec-context-cpu-scheduling-policy", policy_str);
+                if (r < 0)
+                        return r;
+
+                r = serialize_item_format(f, "exec-context-cpu-scheduling-priority", "%i", c->cpu_sched_priority);
+                if (r < 0)
+                        return r;
+
+                r = serialize_bool_elide(f, "exec-context-cpu-scheduling-reset-on-fork", c->cpu_sched_reset_on_fork);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->cpu_set.set) {
+                _cleanup_free_ char *affinity = NULL;
+
+                affinity = cpu_set_to_range_string(&c->cpu_set);
+                if (!affinity)
+                        return log_oom_debug();
+
+                r = serialize_item(f, "exec-context-cpu-affinity", affinity);
+                if (r < 0)
+                        return r;
+        }
+
+        if (mpol_is_valid(numa_policy_get_type(&c->numa_policy))) {
+                _cleanup_free_ char *nodes = NULL;
+
+                nodes = cpu_set_to_range_string(&c->numa_policy.nodes);
+                if (!nodes)
+                        return log_oom_debug();
+
+                if (nodes) {
+                        r = serialize_item(f, "exec-context-numa-mask", nodes);
+                        if (r < 0)
+                                return r;
+                }
+
+                r = serialize_item_format(f, "exec-context-numa-policy", "%d", c->numa_policy.type);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_bool_elide(f, "exec-context-cpu-affinity-from-numa", c->cpu_affinity_from_numa);
+        if (r < 0)
+                return r;
+
+        if (c->timer_slack_nsec != NSEC_INFINITY) {
+                r = serialize_item_format(f, "exec-context-timer-slack-nsec", NSEC_FMT, c->timer_slack_nsec);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_item(f, "exec-context-std-input", exec_input_to_string(c->std_input));
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-std-output", exec_output_to_string(c->std_output));
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-std-error", exec_output_to_string(c->std_error));
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-stdio-as-fds", c->stdio_as_fds);
+        if (r < 0)
+                return r;
+
+        switch (c->std_input) {
+        case EXEC_INPUT_NAMED_FD:
+                r = serialize_item(f, "exec-context-std-input-fd-name", c->stdio_fdname[STDIN_FILENO]);
+                if (r < 0)
+                        return r;
+                break;
+
+        case EXEC_INPUT_FILE:
+                r = serialize_item(f, "exec-context-std-input-file", c->stdio_file[STDIN_FILENO]);
+                if (r < 0)
+                        return r;
+                break;
+
+        default:
+                break;
+        }
+
+        r = serialize_std_out_err(c, f, STDOUT_FILENO);
+        if (r < 0)
+                return r;
+
+        r = serialize_std_out_err(c, f, STDERR_FILENO);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_base64mem(f, "exec-context-stdin-data", c->stdin_data, c->stdin_data_size);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-tty-path", c->tty_path);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-tty-reset", c->tty_reset);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-tty-vhangup", c->tty_vhangup);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-tty-vt-disallocate", c->tty_vt_disallocate);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_format(f, "exec-context-tty-rows", "%u", c->tty_rows);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_format(f, "exec-context-tty-columns", "%u", c->tty_cols);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_format(f, "exec-context-syslog-priority", "%i", c->syslog_priority);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool(f, "exec-context-syslog-level-prefix", c->syslog_level_prefix);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-syslog-identifier", c->syslog_identifier);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_format(f, "exec-context-log-level-max", "%d", c->log_level_max);
+        if (r < 0)
+                return r;
+
+        if (c->log_ratelimit_interval_usec > 0) {
+                r = serialize_usec(f, "exec-context-log-ratelimit-interval-usec", c->log_ratelimit_interval_usec);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->log_ratelimit_burst > 0) {
+                r = serialize_item_format(f, "exec-context-log-ratelimit-burst", "%u", c->log_ratelimit_burst);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_string_set(f, "exec-context-log-filter-allowed-patterns", c->log_filter_allowed_patterns);
+        if (r < 0)
+                return r;
+
+        r = serialize_string_set(f, "exec-context-log-filter-denied-patterns", c->log_filter_denied_patterns);
+        if (r < 0)
+                return r;
+
+        for (size_t j = 0; j < c->n_log_extra_fields; j++) {
+                r = serialize_item(f, "exec-context-log-extra-fields", c->log_extra_fields[j].iov_base);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_item(f, "exec-context-log-namespace", c->log_namespace);
+        if (r < 0)
+                return r;
+
+        if (c->secure_bits != 0) {
+                r = serialize_item_format(f, "exec-context-secure-bits", "%d", c->secure_bits);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->capability_bounding_set != CAP_MASK_UNSET) {
+                r = serialize_item_format(f, "exec-context-capability-bounding-set", "%" PRIu64, c->capability_bounding_set);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->capability_ambient_set != 0) {
+                r = serialize_item_format(f, "exec-context-capability-ambient-set", "%" PRIu64, c->capability_ambient_set);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->user) {
+                r = serialize_item(f, "exec-context-user", c->user);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_item(f, "exec-context-group", c->group);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-dynamic-user", c->dynamic_user);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-context-supplementary-groups", c->supplementary_groups);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_tristate(f, "exec-context-set-login-environment", c->set_login_environment);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-pam-name", c->pam_name);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-context-read-write-paths", c->read_write_paths);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-context-read-only-paths", c->read_only_paths);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-context-inaccessible-paths", c->inaccessible_paths);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-context-exec-paths", c->exec_paths);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-context-no-exec-paths", c->no_exec_paths);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-context-exec-search-path", c->exec_search_path);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_format(f, "exec-context-mount-propagation-flag", "%lu", c->mount_propagation_flag);
+        if (r < 0)
+                return r;
+
+        for (size_t i = 0; i < c->n_bind_mounts; i++) {
+                _cleanup_free_ char *src_escaped = NULL, *dst_escaped = NULL;
+
+                src_escaped = shell_escape(c->bind_mounts[i].source, ":");
+                if (!src_escaped)
+                        return log_oom_debug();
+
+                dst_escaped = shell_escape(c->bind_mounts[i].destination, ":");
+                if (!dst_escaped)
+                        return log_oom_debug();
+
+                r = serialize_item_format(f,
+                                          c->bind_mounts[i].read_only ? "exec-context-bind-read-only-path" : "exec-context-bind-path",
+                                          "%s%s:%s:%s",
+                                          c->bind_mounts[i].ignore_enoent ? "-" : "",
+                                          src_escaped,
+                                          dst_escaped,
+                                          c->bind_mounts[i].recursive ? "rbind" : "norbind");
+                if (r < 0)
+                        return r;
+        }
+
+        for (size_t i = 0; i < c->n_temporary_filesystems; i++) {
+                const TemporaryFileSystem *t = c->temporary_filesystems + i;
+                _cleanup_free_ char *escaped = NULL;
+
+                if (!isempty(t->options)) {
+                        escaped = shell_escape(t->options, ":");
+                        if (!escaped)
+                                return log_oom_debug();
+                }
+
+                r = serialize_item_format(f, "exec-context-temporary-filesystems", "%s%s%s",
+                                          t->path,
+                                          isempty(escaped) ? "" : ":",
+                                          strempty(escaped));
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_item(f, "exec-context-utmp-id", c->utmp_id);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-utmp-mode", exec_utmp_mode_to_string(c->utmp_mode));
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-no-new-privileges", c->no_new_privileges);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-selinux-context-ignore", c->selinux_context_ignore);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-apparmor-profile-ignore", c->apparmor_profile_ignore);
+        if (r < 0)
+                return r;
+
+        r = serialize_bool_elide(f, "exec-context-smack-process-label-ignore", c->smack_process_label_ignore);
+        if (r < 0)
+                return r;
+
+        if (c->selinux_context) {
+                r = serialize_item_format(f, "exec-context-selinux-context",
+                                          "%s%s",
+                                          c->selinux_context_ignore ? "-" : "",
+                                          c->selinux_context);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->apparmor_profile) {
+                r = serialize_item_format(f, "exec-context-apparmor-profile",
+                                          "%s%s",
+                                          c->apparmor_profile_ignore ? "-" : "",
+                                          c->apparmor_profile);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->smack_process_label) {
+                r = serialize_item_format(f, "exec-context-smack-process-label",
+                                          "%s%s",
+                                          c->smack_process_label_ignore ? "-" : "",
+                                          c->smack_process_label);
+                if (r < 0)
+                        return r;
+        }
+
+        if (c->personality != PERSONALITY_INVALID) {
+                r = serialize_item(f, "exec-context-personality", personality_to_string(c->personality));
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_bool_elide(f, "exec-context-lock-personality", c->lock_personality);
+        if (r < 0)
+                return r;
+
+#if HAVE_SECCOMP
+        if (!hashmap_isempty(c->syscall_filter)) {
+                void *errno_num, *id;
+                HASHMAP_FOREACH_KEY(errno_num, id, c->syscall_filter) {
+                        r = serialize_item_format(f, "exec-context-syscall-filter", "%d %d", PTR_TO_INT(id) - 1, PTR_TO_INT(errno_num));
+                        if (r < 0)
+                                return r;
+                }
+        }
+
+        if (!set_isempty(c->syscall_archs)) {
+                void *id;
+                SET_FOREACH(id, c->syscall_archs) {
+                        r = serialize_item_format(f, "exec-context-syscall-archs", "%u", PTR_TO_UINT(id) - 1);
+                        if (r < 0)
+                                return r;
+                }
+        }
+
+        if (c->syscall_errno > 0) {
+                r = serialize_item_format(f, "exec-context-syscall-errno", "%d", c->syscall_errno);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_bool_elide(f, "exec-context-syscall-allow-list", c->syscall_allow_list);
+        if (r < 0)
+                return r;
+
+        if (!hashmap_isempty(c->syscall_log)) {
+                void *errno_num, *id;
+                HASHMAP_FOREACH_KEY(errno_num, id, c->syscall_log) {
+                        r = serialize_item_format(f, "exec-context-syscall-log", "%d %d", PTR_TO_INT(id) - 1, PTR_TO_INT(errno_num));
+                        if (r < 0)
+                                return r;
+                }
+        }
+
+        r = serialize_bool_elide(f, "exec-context-syscall-log-allow-list", c->syscall_log_allow_list);
+        if (r < 0)
+                return r;
+#endif
+
+        if (c->restrict_namespaces != NAMESPACE_FLAGS_INITIAL) {
+                r = serialize_item_format(f, "exec-context-restrict-namespaces", "%lu", c->restrict_namespaces);
+                if (r < 0)
+                        return r;
+        }
+
+#if HAVE_LIBBPF
+        if (exec_context_restrict_filesystems_set(c)) {
+                char *fs;
+                SET_FOREACH(fs, c->restrict_filesystems) {
+                        r = serialize_item(f, "exec-context-restrict-filesystems", fs);
+                        if (r < 0)
+                                return r;
+                }
+        }
+
+        r = serialize_bool_elide(f, "exec-context-restrict-filesystems-allow-list", c->restrict_filesystems_allow_list);
+        if (r < 0)
+                return r;
+#endif
+
+        if (!set_isempty(c->address_families)) {
+                void *afp;
+
+                SET_FOREACH(afp, c->address_families) {
+                        int af = PTR_TO_INT(afp);
+
+                        if (af <= 0 || af >= af_max())
+                                continue;
+
+                        r = serialize_item_format(f, "exec-context-address-families", "%d", af);
+                        if (r < 0)
+                                return r;
+                }
+        }
+
+        r = serialize_bool_elide(f, "exec-context-address-families-allow-list", c->address_families_allow_list);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-network-namespace-path", c->network_namespace_path);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, "exec-context-ipc-namespace-path", c->ipc_namespace_path);
+        if (r < 0)
+                return r;
+
+        for (size_t i = 0; i < c->n_mount_images; i++) {
+                _cleanup_free_ char *s = NULL, *source_escaped = NULL, *dest_escaped = NULL;
+
+                source_escaped = shell_escape(c->mount_images[i].source, " ");
+                if (!source_escaped)
+                        return log_oom_debug();
+
+                dest_escaped = shell_escape(c->mount_images[i].destination, " ");
+                if (!dest_escaped)
+                        return log_oom_debug();
+
+                s = strjoin(c->mount_images[i].ignore_enoent ? "-" : "",
+                            source_escaped,
+                            " ",
+                            dest_escaped);
+                if (!s)
+                        return log_oom_debug();
+
+                LIST_FOREACH(mount_options, o, c->mount_images[i].mount_options) {
+                        _cleanup_free_ char *escaped = NULL;
+
+                        if (isempty(o->options))
+                                continue;
+
+                        escaped = shell_escape(o->options, ":");
+                        if (!escaped)
+                                return log_oom_debug();
+
+                        if (!strextend(&s,
+                                       " ",
+                                       partition_designator_to_string(o->partition_designator),
+                                       ":",
+                                       escaped))
+                                return log_oom_debug();
+                }
+
+                r = serialize_item(f, "exec-context-mount-image", s);
+                if (r < 0)
+                        return r;
+        }
+
+        for (size_t i = 0; i < c->n_extension_images; i++) {
+                _cleanup_free_ char *s = NULL, *source_escaped = NULL;
+
+                source_escaped = shell_escape(c->extension_images[i].source, ":");
+                if (!source_escaped)
+                        return log_oom_debug();
+
+                s = strjoin(c->extension_images[i].ignore_enoent ? "-" : "",
+                            source_escaped);
+                if (!s)
+                        return log_oom_debug();
+
+                LIST_FOREACH(mount_options, o, c->extension_images[i].mount_options) {
+                        _cleanup_free_ char *escaped = NULL;
+
+                        if (isempty(o->options))
+                                continue;
+
+                        escaped = shell_escape(o->options, ":");
+                        if (!escaped)
+                                return log_oom_debug();
+
+                        if (!strextend(&s,
+                                       " ",
+                                       partition_designator_to_string(o->partition_designator),
+                                       ":",
+                                       escaped))
+                                return log_oom_debug();
+                }
+
+                r = serialize_item(f, "exec-context-extension-image", s);
+                if (r < 0)
+                        return r;
+        }
+
+        r = serialize_strv(f, "exec-context-extension-directories", c->extension_directories);
+        if (r < 0)
+                return r;
+
+        ExecSetCredential *sc;
+        HASHMAP_FOREACH(sc, c->set_credentials) {
+                _cleanup_free_ char *data = NULL;
+
+                if (base64mem(sc->data, sc->size, &data) < 0)
+                        return log_oom_debug();
+
+                r = serialize_item_format(f, "exec-context-set-credentials", "%s %s %s", sc->id, yes_no(sc->encrypted), data);
+                if (r < 0)
+                        return r;
+        }
+
+        ExecLoadCredential *lc;
+        HASHMAP_FOREACH(lc, c->load_credentials) {
+                r = serialize_item_format(f, "exec-context-load-credentials", "%s %s %s", lc->id, yes_no(lc->encrypted), lc->path);
+                if (r < 0)
+                        return r;
+        }
+
+        if (!set_isempty(c->import_credentials)) {
+                char *ic;
+                SET_FOREACH(ic, c->import_credentials) {
+                        r = serialize_item(f, "exec-context-import-credentials", ic);
+                        if (r < 0)
+                                return r;
+                }
+        }
+
+        r = serialize_image_policy(f, "exec-context-root-image-policy", c->root_image_policy);
+        if (r < 0)
+                return r;
+
+        r = serialize_image_policy(f, "exec-context-mount-image-policy", c->mount_image_policy);
+        if (r < 0)
+                return r;
+
+        r = serialize_image_policy(f, "exec-context-extension-image-policy", c->extension_image_policy);
+        if (r < 0)
+                return r;
+
+        fputc('\n', f); /* End marker */
+
+        return 0;
+}
+
+static int exec_context_deserialize(ExecContext *c, FILE *f) {
+        int r;
+
+        assert(f);
+
+        if (!c)
+                return 0;
+
+        for (;;) {
+                _cleanup_free_ char *l = NULL;
+                const char *val;
+
+                r = deserialize_read_line(f, &l);
+                if (r < 0)
+                        return r;
+                if (r == 0) /* eof or end marker */
+                        break;
+
+                if ((val = startswith(l, "exec-context-environment="))) {
+                        r = deserialize_strv(&c->environment, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-environment-files="))) {
+                        r = deserialize_strv(&c->environment_files, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-pass-environment="))) {
+                        r = deserialize_strv(&c->pass_environment, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-unset-environment="))) {
+                        r = deserialize_strv(&c->unset_environment, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-working-directory="))) {
+                        r = free_and_strdup(&c->working_directory, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-root-directory="))) {
+                        r = free_and_strdup(&c->root_directory, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-root-image="))) {
+                        r = free_and_strdup(&c->root_image, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-root-image-options="))) {
+                        for (;;) {
+                                _cleanup_free_ char *word = NULL, *mount_options = NULL, *partition = NULL;
+                                PartitionDesignator partition_designator;
+                                MountOptions *o = NULL;
+                                const char *p;
+
+                                r = extract_first_word(&val, &word, NULL, 0);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        break;
+
+                                p = word;
+                                r = extract_many_words(&p, ":", EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS, &partition, &mount_options, NULL);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        continue;
+
+                                partition_designator = partition_designator_from_string(partition);
+                                if (partition_designator < 0)
+                                        return -EINVAL;
+
+                                o = new(MountOptions, 1);
+                                if (!o)
+                                        return log_oom_debug();
+                                *o = (MountOptions) {
+                                        .partition_designator = partition_designator,
+                                        .options = TAKE_PTR(mount_options),
+                                };
+                                LIST_APPEND(mount_options, c->root_image_options, o);
+                        }
+                } else if ((val = startswith(l, "exec-context-root-verity="))) {
+                        r = free_and_strdup(&c->root_verity, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-root-hash-path="))) {
+                        r = free_and_strdup(&c->root_hash_path, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-root-hash-sig-path="))) {
+                        r = free_and_strdup(&c->root_hash_sig_path, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-root-hash="))) {
+                        c->root_hash = mfree(c->root_hash);
+                        r = unhexmem(val, strlen(val), &c->root_hash, &c->root_hash_size);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-root-hash-sig="))) {
+                        c->root_hash_sig = mfree(c->root_hash_sig);
+                        r= unbase64mem(val, strlen(val), &c->root_hash_sig, &c->root_hash_sig_size);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-root-ephemeral="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->root_ephemeral = r;
+                } else if ((val = startswith(l, "exec-context-umask="))) {
+                        r = parse_mode(val, &c->umask);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-private-non-blocking="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->non_blocking = r;
+                } else if ((val = startswith(l, "exec-context-private-mounts="))) {
+                        r = safe_atoi(val, &c->private_mounts);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-memory-ksm="))) {
+                        r = safe_atoi(val, &c->memory_ksm);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-private-tmp="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->private_tmp = r;
+                } else if ((val = startswith(l, "exec-context-private-devices="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->private_devices = r;
+                } else if ((val = startswith(l, "exec-context-protect-kernel-tunables="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->protect_kernel_tunables = r;
+                } else if ((val = startswith(l, "exec-context-protect-kernel-modules="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->protect_kernel_modules = r;
+                } else if ((val = startswith(l, "exec-context-protect-kernel-logs="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->protect_kernel_logs = r;
+                } else if ((val = startswith(l, "exec-context-protect-clock="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->protect_clock = r;
+                } else if ((val = startswith(l, "exec-context-protect-control-groups="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->protect_control_groups = r;
+                } else if ((val = startswith(l, "exec-context-private-network="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->private_network = r;
+                } else if ((val = startswith(l, "exec-context-private-users="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->private_users = r;
+                } else if ((val = startswith(l, "exec-context-private-ipc="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->private_ipc = r;
+                } else if ((val = startswith(l, "exec-context-remove-ipc="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->remove_ipc = r;
+                } else if ((val = startswith(l, "exec-context-protect-home="))) {
+                        c->protect_home = protect_home_from_string(val);
+                        if (c->protect_home < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-context-protect-system="))) {
+                        c->protect_system = protect_system_from_string(val);
+                        if (c->protect_system < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-context-mount-api-vfs="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->mount_apivfs = r;
+                        c->mount_apivfs_set = true;
+                } else if ((val = startswith(l, "exec-context-same-pgrp="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->same_pgrp = r;
+                } else if ((val = startswith(l, "exec-context-cpu-sched-reset-on-fork="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->cpu_sched_reset_on_fork = r;
+                } else if ((val = startswith(l, "exec-context-non-blocking="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        r = c->non_blocking;
+                } else if ((val = startswith(l, "exec-context-ignore-sigpipe="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->ignore_sigpipe = r;
+                } else if ((val = startswith(l, "exec-context-memory-deny-write-execute="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->memory_deny_write_execute = r;
+                } else if ((val = startswith(l, "exec-context-restrict-realtime="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->restrict_realtime = r;
+                } else if ((val = startswith(l, "exec-context-restrict-suid-sgid="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->restrict_suid_sgid = r;
+                } else if ((val = startswith(l, "exec-context-keyring-mode="))) {
+                        c->keyring_mode = exec_keyring_mode_from_string(val);
+                        if (c->keyring_mode < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-context-protect-hostname="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->protect_hostname = r;
+                } else if ((val = startswith(l, "exec-context-protect-proc="))) {
+                        c->protect_proc = protect_proc_from_string(val);
+                        if (c->protect_proc < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-context-proc-subset="))) {
+                        c->proc_subset = proc_subset_from_string(val);
+                        if (c->proc_subset < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-context-runtime-directory-preserve-mode="))) {
+                        c->runtime_directory_preserve_mode = exec_preserve_mode_from_string(val);
+                        if (c->runtime_directory_preserve_mode < 0)
+                                return -EINVAL;
+                } else if ((val = startswith(l, "exec-context-directories-"))) {
+                        _cleanup_free_ char *type = NULL, *mode = NULL;
+                        ExecDirectoryType dt;
+
+                        r = extract_many_words(&val, "= ", 0, &type, &mode, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r == 0 || !mode)
+                                return -EINVAL;
+
+                        dt = exec_directory_type_from_string(type);
+                        if (dt < 0)
+                                return -EINVAL;
+
+                        r = parse_mode(mode, &c->directories[dt].mode);
+                        if (r < 0)
+                                return r;
+
+                        for (;;) {
+                                _cleanup_free_ char *tuple = NULL, *path = NULL, *only_create = NULL;
+                                const char *p;
+
+                                r = extract_first_word(&val, &tuple, WHITESPACE, EXTRACT_RETAIN_ESCAPE);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        break;
+
+                                p = tuple;
+                                r = extract_many_words(&p, ":", EXTRACT_UNESCAPE_SEPARATORS, &path, &only_create, NULL);
+                                if (r < 0)
+                                        return r;
+                                if (r < 2)
+                                        continue;
+
+                                r = exec_directory_add(&c->directories[dt], path, NULL);
+                                if (r < 0)
+                                        return r;
+
+                                r = parse_boolean(only_create);
+                                if (r < 0)
+                                        return r;
+                                c->directories[dt].items[c->directories[dt].n_items - 1].only_create = r;
+
+                                if (isempty(p))
+                                        continue;
+
+                                for (;;) {
+                                        _cleanup_free_ char *link = NULL;
+
+                                        r = extract_first_word(&p, &link, ":", EXTRACT_UNESCAPE_SEPARATORS);
+                                        if (r < 0)
+                                                return r;
+                                        if (r == 0)
+                                                break;
+
+                                        r = strv_consume(&c->directories[dt].items[c->directories[dt].n_items - 1].symlinks, TAKE_PTR(link));
+                                        if (r < 0)
+                                                return r;
+                                }
+                        }
+                } else if ((val = startswith(l, "exec-context-timeout-clean-usec="))) {
+                        r = deserialize_usec(val, &c->timeout_clean_usec);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-nice="))) {
+                        r = safe_atoi(val, &c->nice);
+                        if (r < 0)
+                                return r;
+                        c->nice_set = true;
+                } else if ((val = startswith(l, "exec-context-working-directory-missing-ok="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->working_directory_missing_ok = r;
+                } else if ((val = startswith(l, "exec-context-working-directory-home="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->working_directory_home = r;
+                } else if ((val = startswith(l, "exec-context-oom-score-adjust="))) {
+                        r = safe_atoi(val, &c->oom_score_adjust);
+                        if (r < 0)
+                                return r;
+                        c->oom_score_adjust_set = true;
+                } else if ((val = startswith(l, "exec-context-coredump-filter="))) {
+                        r = safe_atoux64(val, &c->coredump_filter);
+                        if (r < 0)
+                                return r;
+                        c->coredump_filter_set = true;
+                } else if ((val = startswith(l, "exec-context-limit-"))) {
+                        _cleanup_free_ struct rlimit *rlimit = NULL;
+                        _cleanup_free_ char *limit = NULL;
+                        int type;
+
+                        r = extract_first_word(&val, &limit, "=", 0);
+                        if (r < 0)
+                                return r;
+                        if (r == 0 || !val)
+                                return -EINVAL;
+
+                        type = rlimit_from_string(limit);
+                        if (type < 0)
+                                return -EINVAL;
+
+                        if (!c->rlimit[type]) {
+                                rlimit = new0(struct rlimit, 1);
+                                if (!rlimit)
+                                        return log_oom_debug();
+
+                                r = rlimit_parse(type, val, rlimit);
+                                if (r < 0)
+                                        return r;
+
+                                c->rlimit[type] = TAKE_PTR(rlimit);
+                        } else {
+                                r = rlimit_parse(type, val, c->rlimit[type]);
+                                if (r < 0)
+                                        return r;
+                        }
+                } else if ((val = startswith(l, "exec-context-ioprio="))) {
+                        r = safe_atoi(val, &c->ioprio);
+                        if (r < 0)
+                                return r;
+                        c->ioprio_set = true;
+                } else if ((val = startswith(l, "exec-context-cpu-scheduling-policy="))) {
+                        r = sched_policy_from_string(val);
+                        if (r < 0)
+                                return r;
+                        c->cpu_sched_set = true;
+                } else if ((val = startswith(l, "exec-context-cpu-scheduling-priority="))) {
+                        r = safe_atoi(val, &c->cpu_sched_priority);
+                        if (r < 0)
+                                return r;
+                        c->cpu_sched_set = true;
+                } else if ((val = startswith(l, "exec-context-cpu-scheduling-reset-on-fork="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->cpu_sched_reset_on_fork = r;
+                        c->cpu_sched_set = true;
+                } else if ((val = startswith(l, "exec-context-cpu-affinity="))) {
+                        if (c->cpu_set.set)
+                                return -EINVAL; /* duplicated */
+
+                        r = parse_cpu_set(val, &c->cpu_set);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-numa-mask="))) {
+                        if (c->numa_policy.nodes.set)
+                                return -EINVAL; /* duplicated */
+
+                        r = parse_cpu_set(val, &c->numa_policy.nodes);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-numa-policy="))) {
+                        r = safe_atoi(val, &c->numa_policy.type);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-cpu-affinity-from-numa="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->cpu_affinity_from_numa = r;
+                } else if ((val = startswith(l, "exec-context-timer-slack-nsec="))) {
+                        r = deserialize_usec(val, (usec_t *)&c->timer_slack_nsec);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-std-input="))) {
+                        c->std_input = exec_input_from_string(val);
+                        if (c->std_input < 0)
+                                return c->std_input;
+                } else if ((val = startswith(l, "exec-context-std-output="))) {
+                        c->std_output = exec_output_from_string(val);
+                        if (c->std_output < 0)
+                                return c->std_output;
+                } else if ((val = startswith(l, "exec-context-std-error="))) {
+                        c->std_error = exec_output_from_string(val);
+                        if (c->std_error < 0)
+                                return c->std_error;
+                } else if ((val = startswith(l, "exec-context-stdio-as-fds="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->stdio_as_fds = r;
+                } else if ((val = startswith(l, "exec-context-std-input-fd-name="))) {
+                        r = free_and_strdup(&c->stdio_fdname[STDIN_FILENO], val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-std-output-fd-name="))) {
+                        r = free_and_strdup(&c->stdio_fdname[STDOUT_FILENO], val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-std-error-fd-name="))) {
+                        r = free_and_strdup(&c->stdio_fdname[STDERR_FILENO], val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-std-input-file="))) {
+                        r = free_and_strdup(&c->stdio_file[STDIN_FILENO], val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-std-output-file="))) {
+                        r = free_and_strdup(&c->stdio_file[STDOUT_FILENO], val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-std-output-file-append="))) {
+                        r = free_and_strdup(&c->stdio_file[STDOUT_FILENO], val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-std-output-file-truncate="))) {
+                        r = free_and_strdup(&c->stdio_file[STDOUT_FILENO], val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-std-error-file="))) {
+                        r = free_and_strdup(&c->stdio_file[STDERR_FILENO], val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-std-error-file-append="))) {
+                        r = free_and_strdup(&c->stdio_file[STDERR_FILENO], val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-std-error-file-truncate="))) {
+                        r = free_and_strdup(&c->stdio_file[STDERR_FILENO], val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-stdin-data="))) {
+                        if (c->stdin_data)
+                                return -EINVAL; /* duplicated */
+
+                        r = unbase64mem(val, strlen(val), &c->stdin_data, &c->stdin_data_size);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-tty-path="))) {
+                        r = free_and_strdup(&c->tty_path, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-tty-reset="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->tty_reset = r;
+                } else if ((val = startswith(l, "exec-context-tty-vhangup="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->tty_vhangup = r;
+                } else if ((val = startswith(l, "exec-context-tty-vt-disallocate="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->tty_vt_disallocate = r;
+                } else if ((val = startswith(l, "exec-context-tty-rows="))) {
+                        r = safe_atou(val, &c->tty_rows);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-tty-columns="))) {
+                        r = safe_atou(val, &c->tty_cols);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-syslog-priority="))) {
+                        r = safe_atoi(val, &c->syslog_priority);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-syslog-level-prefix="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->syslog_level_prefix = r;
+                } else if ((val = startswith(l, "exec-context-syslog-identifier="))) {
+                        r = free_and_strdup(&c->syslog_identifier, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-log-level-max="))) {
+                        r = safe_atoi(val, &c->log_level_max);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-log-ratelimit-interval-usec="))) {
+                        r = deserialize_usec(val, &c->log_ratelimit_interval_usec);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-log-ratelimit-burst="))) {
+                        r = safe_atou(val, &c->log_ratelimit_burst);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-log-filter-allowed-patterns="))) {
+                        r = set_put_strdup(&c->log_filter_allowed_patterns, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-log-filter-denied-patterns="))) {
+                        r = set_put_strdup(&c->log_filter_denied_patterns, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-log-extra-fields="))) {
+                        if (!GREEDY_REALLOC(c->log_extra_fields, c->n_log_extra_fields + 1))
+                                return log_oom_debug();
+
+                        c->log_extra_fields[c->n_log_extra_fields++].iov_base = strdup(val);
+                        if (!c->log_extra_fields[c->n_log_extra_fields-1].iov_base)
+                                return log_oom_debug();
+                } else if ((val = startswith(l, "exec-context-log-namespace="))) {
+                        r = free_and_strdup(&c->log_namespace, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-secure-bits="))) {
+                        r = safe_atoi(val, &c->secure_bits);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-capability-bounding-set="))) {
+                        r = safe_atou64(val, &c->capability_bounding_set);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-capability-ambient-set="))) {
+                        r = safe_atou64(val, &c->capability_ambient_set);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-user="))) {
+                        r = free_and_strdup(&c->user, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-group="))) {
+                        r = free_and_strdup(&c->group, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-dynamic-user="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->dynamic_user = r;
+                } else if ((val = startswith(l, "exec-context-supplementary-groups="))) {
+                        r = deserialize_strv(&c->supplementary_groups, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-set-login-environment="))) {
+                        r = safe_atoi(val, &c->set_login_environment);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-pam-name="))) {
+                        r = free_and_strdup(&c->pam_name, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-read-write-paths="))) {
+                        r = deserialize_strv(&c->read_write_paths, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-read-only-paths="))) {
+                        r = deserialize_strv(&c->read_only_paths, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-inaccessible-paths="))) {
+                        r = deserialize_strv(&c->inaccessible_paths, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-exec-paths="))) {
+                        r = deserialize_strv(&c->exec_paths, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-no-exec-paths="))) {
+                        r = deserialize_strv(&c->no_exec_paths, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-exec-search-path="))) {
+                        r = deserialize_strv(&c->exec_search_path, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-mount-propagation-flag="))) {
+                        r = safe_atolu(val, &c->mount_propagation_flag);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-bind-read-only-path="))) {
+                        _cleanup_free_ char *source = NULL, *destination = NULL;
+                        bool rbind = true, ignore_enoent = false;
+                        char *s = NULL, *d = NULL;
+
+                        r = extract_first_word(&val,
+                                               &source,
+                                               ":" WHITESPACE,
+                                               EXTRACT_UNQUOTE|EXTRACT_DONT_COALESCE_SEPARATORS|EXTRACT_UNESCAPE_SEPARATORS);
+                        if (r < 0)
+                                return r;
+                        if (r == 0)
+                                return -EINVAL;
+
+                        s = source;
+                        if (s[0] == '-') {
+                                ignore_enoent = true;
+                                s++;
+                        }
+
+                        if (val && val[-1] == ':') {
+                                r = extract_first_word(&val,
+                                                       &destination,
+                                                       ":" WHITESPACE,
+                                                       EXTRACT_UNQUOTE|EXTRACT_DONT_COALESCE_SEPARATORS|EXTRACT_UNESCAPE_SEPARATORS);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        continue;
+
+                                d = destination;
+
+                                if (val && val[-1] == ':') {
+                                        _cleanup_free_ char *options = NULL;
+
+                                        r = extract_first_word(&val, &options, NULL, EXTRACT_UNQUOTE);
+                                        if (r < 0)
+                                                return -r;
+
+                                        if (isempty(options) || streq(options, "rbind"))
+                                                rbind = true;
+                                        else if (streq(options, "norbind"))
+                                                rbind = false;
+                                        else
+                                                continue;
+                                }
+                        } else
+                                d = s;
+
+                        r = bind_mount_add(&c->bind_mounts, &c->n_bind_mounts,
+                                        &(BindMount) {
+                                                .source = s,
+                                                .destination = d,
+                                                .read_only = true,
+                                                .recursive = rbind,
+                                                .ignore_enoent = ignore_enoent,
+                                        });
+                        if (r < 0)
+                                return log_oom_debug();
+                } else if ((val = startswith(l, "exec-context-bind-path="))) {
+                        _cleanup_free_ char *source = NULL, *destination = NULL;
+                        bool rbind = true, ignore_enoent = false;
+                        char *s = NULL, *d = NULL;
+
+                        r = extract_first_word(&val,
+                                               &source,
+                                               ":" WHITESPACE,
+                                               EXTRACT_UNQUOTE|EXTRACT_DONT_COALESCE_SEPARATORS|EXTRACT_UNESCAPE_SEPARATORS);
+                        if (r < 0)
+                                return r;
+                        if (r == 0)
+                                return -EINVAL;
+
+                        s = source;
+                        if (s[0] == '-') {
+                                ignore_enoent = true;
+                                s++;
+                        }
+
+                        if (val && val[-1] == ':') {
+                                r = extract_first_word(&val,
+                                                       &destination,
+                                                       ":" WHITESPACE,
+                                                       EXTRACT_UNQUOTE|EXTRACT_DONT_COALESCE_SEPARATORS|EXTRACT_UNESCAPE_SEPARATORS);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        continue;
+
+                                d = destination;
+
+                                if (val && val[-1] == ':') {
+                                        _cleanup_free_ char *options = NULL;
+
+                                        r = extract_first_word(&val, &options, NULL, EXTRACT_UNQUOTE);
+                                        if (r < 0)
+                                                return -r;
+
+                                        if (isempty(options) || streq(options, "rbind"))
+                                                rbind = true;
+                                        else if (streq(options, "norbind"))
+                                                rbind = false;
+                                        else
+                                                continue;
+                                }
+                        } else
+                                d = s;
+
+                        r = bind_mount_add(&c->bind_mounts, &c->n_bind_mounts,
+                                        &(BindMount) {
+                                                .source = s,
+                                                .destination = d,
+                                                .read_only = false,
+                                                .recursive = rbind,
+                                                .ignore_enoent = ignore_enoent,
+                                        });
+                        if (r < 0)
+                                return log_oom_debug();
+                } else if ((val = startswith(l, "exec-context-temporary-filesystems="))) {
+                        _cleanup_free_ char *path = NULL, *options = NULL;
+
+                        r = extract_many_words(&val, ":", EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS, &path, &options, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r < 1)
+                                continue;
+
+                        r = temporary_filesystem_add(&c->temporary_filesystems, &c->n_temporary_filesystems, path, options);
+                        if (r < 0)
+                                return log_oom_debug();
+                } else if ((val = startswith(l, "exec-context-utmp-id="))) {
+                        r = free_and_strdup(&c->utmp_id, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-utmp-mode="))) {
+                        c->utmp_mode = exec_utmp_mode_from_string(val);
+                        if (c->utmp_mode < 0)
+                                return c->utmp_mode;
+                } else if ((val = startswith(l, "exec-context-no-new-privileges="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->no_new_privileges = r;
+                } else if ((val = startswith(l, "exec-context-selinux-context-ignore="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->selinux_context_ignore = r;
+                } else if ((val = startswith(l, "exec-context-apparmor-profile-ignore="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->apparmor_profile_ignore = r;
+                } else if ((val = startswith(l, "exec-context-smack-process-label-ignore="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->smack_process_label_ignore = r;
+                } else if ((val = startswith(l, "exec-context-selinux-context="))) {
+                        if (val[0] == '-') {
+                                c->selinux_context_ignore = true;
+                                val++;
+                        }
+
+                        r = free_and_strdup(&c->selinux_context, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-apparmor-profile="))) {
+                        if (val[0] == '-') {
+                                c->apparmor_profile_ignore = true;
+                                val++;
+                        }
+
+                        r = free_and_strdup(&c->apparmor_profile, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-smack-process-label="))) {
+                        if (val[0] == '-') {
+                                c->smack_process_label_ignore = true;
+                                val++;
+                        }
+
+                        r = free_and_strdup(&c->smack_process_label, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-personality=")))
+                        c->personality = personality_from_string(val);
+                else if ((val = startswith(l, "exec-context-lock-personality="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->lock_personality = r;
+#if HAVE_SECCOMP
+                } else if ((val = startswith(l, "exec-context-syscall-filter="))) {
+                        _cleanup_free_ char *s_id = NULL, *s_errno_num = NULL;
+                        int id, errno_num;
+
+                        r = extract_many_words(&val, NULL, 0, &s_id, &s_errno_num, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 2)
+                                continue;
+
+                        r = safe_atoi(s_id, &id);
+                        if (r < 0)
+                                return r;
+
+                        r = safe_atoi(s_errno_num, &errno_num);
+                        if (r < 0)
+                                return r;
+
+                        r = hashmap_ensure_put(&c->syscall_filter, NULL, INT_TO_PTR(id + 1), INT_TO_PTR(errno_num));
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-syscall-archs="))) {
+                        unsigned int id;
+
+                        r = safe_atou(val, &id);
+                        if (r < 0)
+                                return r;
+
+                        r = set_ensure_put(&c->syscall_archs, NULL, UINT_TO_PTR(id + 1));
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-syscall-errno="))) {
+                        r = safe_atoi(val, &c->syscall_errno);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-syscall-allow-list="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->syscall_allow_list = r;
+                } else if ((val = startswith(l, "exec-context-syscall-log="))) {
+                        _cleanup_free_ char *s_id = NULL, *s_errno_num = NULL;
+                        int id, errno_num;
+
+                        r = extract_many_words(&val, " ", 0, &s_id, &s_errno_num, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 2)
+                                continue;
+
+                        r = safe_atoi(s_id, &id);
+                        if (r < 0)
+                                return r;
+
+                        r = safe_atoi(s_errno_num, &errno_num);
+                        if (r < 0)
+                                return r;
+
+                        r = hashmap_ensure_put(&c->syscall_log, NULL, INT_TO_PTR(id + 1), INT_TO_PTR(errno_num));
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-syscall-log-allow-list="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->syscall_log_allow_list = r;
+#endif
+                } else if ((val = startswith(l, "exec-context-restrict-namespaces="))) {
+                        r = safe_atolu(val, &c->restrict_namespaces);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-restrict-filesystems="))) {
+                        r = set_ensure_allocated(&c->restrict_filesystems, &string_hash_ops);
+                        if (r < 0)
+                                return r;
+
+                        r = set_put_strdup(&c->restrict_filesystems, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-restrict-filesystems-allow-list="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->restrict_filesystems_allow_list = r;
+                } else if ((val = startswith(l, "exec-context-address-families="))) {
+                        int af;
+
+                        r = safe_atoi(val, &af);
+                        if (r < 0)
+                                return r;
+
+                        r = set_ensure_put(&c->address_families, NULL, INT_TO_PTR(af));
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-address-families-allow-list="))) {
+                        r = parse_boolean(val);
+                        if (r < 0)
+                                return r;
+                        c->address_families_allow_list = r;
+                } else if ((val = startswith(l, "exec-context-network-namespace-path="))) {
+                        r = free_and_strdup(&c->network_namespace_path, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-ipc-namespace-path="))) {
+                        r = free_and_strdup(&c->ipc_namespace_path, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-mount-image="))) {
+                        _cleanup_(mount_options_free_allp) MountOptions *options = NULL;
+                        _cleanup_free_ char *source = NULL, *destination = NULL;
+                        bool permissive = false;
+                        char *s;
+
+                        r = extract_many_words(&val,
+                                               NULL,
+                                               EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS,
+                                               &source,
+                                               &destination,
+                                               NULL);
+                        if (r < 0)
+                                return r;
+                        if (r == 0)
+                                return -EINVAL;
+
+                        s = source;
+                        if (s[0] == '-') {
+                                permissive = true;
+                                s++;
+                        }
+
+                        if (isempty(destination))
+                                continue;
+
+                        for (;;) {
+                                _cleanup_free_ char *tuple = NULL, *partition = NULL, *opts = NULL;
+                                PartitionDesignator partition_designator;
+                                MountOptions *o = NULL;
+                                const char *p;
+
+                                r = extract_first_word(&val, &tuple, NULL, EXTRACT_UNQUOTE|EXTRACT_RETAIN_ESCAPE);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        break;
+
+                                p = tuple;
+                                r = extract_many_words(&p,
+                                                       ":",
+                                                       EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS,
+                                                       &partition,
+                                                       &opts,
+                                                       NULL);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        continue;
+                                if (r == 1) {
+                                        o = new(MountOptions, 1);
+                                        if (!o)
+                                                return log_oom_debug();
+                                        *o = (MountOptions) {
+                                                .partition_designator = PARTITION_ROOT,
+                                                .options = TAKE_PTR(partition),
+                                        };
+                                        LIST_APPEND(mount_options, options, o);
+
+                                        continue;
+                                }
+
+                                partition_designator = partition_designator_from_string(partition);
+                                if (partition_designator < 0)
+                                        continue;
+
+                                o = new(MountOptions, 1);
+                                if (!o)
+                                        return log_oom_debug();
+                                *o = (MountOptions) {
+                                        .partition_designator = partition_designator,
+                                        .options = TAKE_PTR(opts),
+                                };
+                                LIST_APPEND(mount_options, options, o);
+                        }
+
+                        r = mount_image_add(&c->mount_images, &c->n_mount_images,
+                                        &(MountImage) {
+                                                .source = s,
+                                                .destination = destination,
+                                                .mount_options = options,
+                                                .ignore_enoent = permissive,
+                                                .type = MOUNT_IMAGE_DISCRETE,
+                                        });
+                        if (r < 0)
+                                return log_oom_debug();
+                } else if ((val = startswith(l, "exec-context-extension-image="))) {
+                        _cleanup_(mount_options_free_allp) MountOptions *options = NULL;
+                        _cleanup_free_ char *source = NULL;
+                        bool permissive = false;
+                        char *s;
+
+                        r = extract_first_word(&val,
+                                               &source,
+                                               NULL,
+                                               EXTRACT_UNQUOTE|EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS);
+                        if (r < 0)
+                                return r;
+                        if (r == 0)
+                                return -EINVAL;
+
+                        s = source;
+                        if (s[0] == '-') {
+                                permissive = true;
+                                s++;
+                        }
+
+                        for (;;) {
+                                _cleanup_free_ char *tuple = NULL, *partition = NULL, *opts = NULL;
+                                PartitionDesignator partition_designator;
+                                MountOptions *o = NULL;
+                                const char *p;
+
+                                r = extract_first_word(&val, &tuple, NULL, EXTRACT_UNQUOTE|EXTRACT_RETAIN_ESCAPE);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        break;
+
+                                p = tuple;
+                                r = extract_many_words(&p,
+                                                       ":",
+                                                       EXTRACT_CUNESCAPE|EXTRACT_UNESCAPE_SEPARATORS,
+                                                       &partition,
+                                                       &opts,
+                                                       NULL);
+                                if (r < 0)
+                                        return r;
+                                if (r == 0)
+                                        continue;
+                                if (r == 1) {
+                                        o = new(MountOptions, 1);
+                                        if (!o)
+                                                return log_oom_debug();
+                                        *o = (MountOptions) {
+                                                .partition_designator = PARTITION_ROOT,
+                                                .options = TAKE_PTR(partition),
+                                        };
+                                        LIST_APPEND(mount_options, options, o);
+
+                                        continue;
+                                }
+
+                                partition_designator = partition_designator_from_string(partition);
+                                if (partition_designator < 0)
+                                        continue;
+
+                                o = new(MountOptions, 1);
+                                if (!o)
+                                        return log_oom_debug();
+                                *o = (MountOptions) {
+                                        .partition_designator = partition_designator,
+                                        .options = TAKE_PTR(opts),
+                                };
+                                LIST_APPEND(mount_options, options, o);
+                        }
+
+                        r = mount_image_add(&c->extension_images, &c->n_extension_images,
+                                        &(MountImage) {
+                                                .source = s,
+                                                .mount_options = options,
+                                                .ignore_enoent = permissive,
+                                                .type = MOUNT_IMAGE_EXTENSION,
+                                        });
+                        if (r < 0)
+                                return log_oom_debug();
+                } else if ((val = startswith(l, "exec-context-extension-directories="))) {
+                        r = deserialize_strv(&c->extension_directories, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-set-credentials="))) {
+                        _cleanup_(exec_set_credential_freep) ExecSetCredential *sc = NULL;
+                        _cleanup_free_ char *id = NULL, *encrypted = NULL, *data = NULL;
+
+                        r = extract_many_words(&val, " ", 0, &id, &encrypted, &data, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 3)
+                                return -EINVAL;
+
+                        r = parse_boolean(encrypted);
+                        if (r < 0)
+                                return r;
+
+                        sc = new(ExecSetCredential, 1);
+                        if (!sc)
+                                return -ENOMEM;
+
+                        *sc = (ExecSetCredential) {
+                                .id =  TAKE_PTR(id),
+                                .encrypted = r,
+                        };
+
+                        r = unbase64mem(data, strlen(data), &sc->data, &sc->size);
+                        if (r < 0)
+                                return r;
+
+                        r = hashmap_ensure_put(&c->set_credentials, &exec_set_credential_hash_ops, sc->id, sc);
+                        if (r < 0)
+                                return r;
+
+                        TAKE_PTR(sc);
+                } else if ((val = startswith(l, "exec-context-load-credentials="))) {
+                        _cleanup_(exec_load_credential_freep) ExecLoadCredential *lc = NULL;
+                        _cleanup_free_ char *id = NULL, *encrypted = NULL, *path = NULL;
+
+                        r = extract_many_words(&val, " ", 0, &id, &encrypted, &path, NULL);
+                        if (r < 0)
+                                return r;
+                        if (r != 3)
+                                return -EINVAL;
+
+                        r = parse_boolean(encrypted);
+                        if (r < 0)
+                                return r;
+
+                        lc = new(ExecLoadCredential, 1);
+                        if (!lc)
+                                return -ENOMEM;
+
+                        *lc = (ExecLoadCredential) {
+                                .id =  TAKE_PTR(id),
+                                .path = TAKE_PTR(path),
+                                .encrypted = r,
+                        };
+
+                        r = hashmap_ensure_put(&c->load_credentials, &exec_load_credential_hash_ops, lc->id, lc);
+                        if (r < 0)
+                                return r;
+
+                        TAKE_PTR(lc);
+                } else if ((val = startswith(l, "exec-context-import-credentials="))) {
+                        r = set_ensure_allocated(&c->import_credentials, &string_hash_ops);
+                        if (r < 0)
+                                return r;
+
+                        r = set_put_strdup(&c->import_credentials, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-root-image-policy="))) {
+                        if (c->root_image_policy)
+                                return -EINVAL; /* duplicated */
+
+                        r = image_policy_from_string(val, &c->root_image_policy);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-mount-image-policy="))) {
+                        if (c->mount_image_policy)
+                                return -EINVAL; /* duplicated */
+
+                        r = image_policy_from_string(val, &c->mount_image_policy);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-context-extension-image-policy="))) {
+                        if (c->extension_image_policy)
+                                return -EINVAL; /* duplicated */
+
+                        r = image_policy_from_string(val, &c->extension_image_policy);
+                        if (r < 0)
+                                return r;
+                } else
+                        log_warning("Failed to parse serialized line, ignoring: %s", l);
+        }
+
+        return 0;
+}
+
+static int exec_command_serialize(const ExecCommand *c, FILE *f) {
+        int r;
+
+        assert(c);
+        assert(f);
+
+        r = serialize_item(f, "exec-command-path", c->path);
+        if (r < 0)
+                return r;
+
+        r = serialize_strv(f, "exec-command-argv", c->argv);
+        if (r < 0)
+                return r;
+
+        r = serialize_item_format(f, "exec-command-flags", "%d", (int) c->flags);
+        if (r < 0)
+                return r;
+
+        fputc('\n', f); /* End marker */
+
+        return 0;
+}
+
+static int exec_command_deserialize(ExecCommand *c, FILE *f) {
+        int r;
+
+        assert(c);
+        assert(f);
+
+        for (;;) {
+                _cleanup_free_ char *l = NULL;
+                const char *val;
+
+                r = deserialize_read_line(f, &l);
+                if (r < 0)
+                        return r;
+                if (r == 0) /* eof or end marker */
+                        break;
+
+                if ((val = startswith(l, "exec-command-path="))) {
+                        r = free_and_strdup(&c->path, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-command-argv="))) {
+                        r = deserialize_strv(&c->argv, val);
+                        if (r < 0)
+                                return r;
+                } else if ((val = startswith(l, "exec-command-flags="))) {
+                        r = safe_atoi(val, &c->flags);
+                        if (r < 0)
+                                return r;
+                } else
+                        log_warning("Failed to parse serialized line, ignorning: %s", l);
+
+        }
+
+        return 0;
+}
+
+int exec_serialize_invocation(
+                FILE *f,
+                FDSet *fds,
+                const ExecContext *ctx,
+                const ExecCommand *cmd,
+                const ExecParameters *p,
+                const ExecRuntime *rt,
+                const CGroupContext *cg) {
+
+        int r;
+
+        assert(f);
+        assert(fds);
+
+        r = exec_context_serialize(ctx, f);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to serialize context: %m");
+
+        r = exec_command_serialize(cmd, f);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to serialize command: %m");
+
+        r = exec_parameters_serialize(p, f, fds);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to serialize parameters: %m");
+
+        r = exec_runtime_serialize(rt, f, fds);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to serialize runtime: %m");
+
+        r = exec_cgroup_context_serialize(cg, f);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to serialize cgroup context: %m");
+
+        return 0;
+}
+
+int exec_deserialize_invocation(
+                FILE *f,
+                FDSet *fds,
+                ExecContext *ctx,
+                ExecCommand *cmd,
+                ExecParameters *p,
+                ExecRuntime *rt,
+                CGroupContext *cg) {
+
+        int r;
+
+        assert(f);
+        assert(fds);
+
+        r = exec_context_deserialize(ctx, f);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to deserialize context: %m");
+
+        r = exec_command_deserialize(cmd, f);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to deserialize command: %m");
+
+        r = exec_parameters_deserialize(p, f, fds);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to deserialize parameters: %m");
+
+        r = exec_runtime_deserialize(rt, f, fds);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to deserialize runtime: %m");
+
+        r = exec_cgroup_context_deserialize(cg, f);
+        if (r < 0)
+                return log_debug_errno(r, "Failed to deserialize cgroup context: %m");
+
+        return 0;
+}
diff --git a/src/core/execute-serialize.h b/src/core/execute-serialize.h
new file mode 100644 (file)
index 0000000..89c8e09
--- /dev/null
@@ -0,0 +1,23 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+#pragma once
+
+#include "execute.h"
+
+/* These functions serialize/deserialize for invocation purposes (i.e.: serialized object is passed to a
+ * child process) rather than to save state across reload/reexec. */
+
+int exec_serialize_invocation(FILE *f,
+        FDSet *fds,
+        const ExecContext *ctx,
+        const ExecCommand *cmd,
+        const ExecParameters *p,
+        const ExecRuntime *rt,
+        const CGroupContext *cg);
+
+int exec_deserialize_invocation(FILE *f,
+        FDSet *fds,
+        ExecContext *ctx,
+        ExecCommand *cmd,
+        ExecParameters *p,
+        ExecRuntime *rt,
+        CGroupContext *cg);
index 7cf6601ee7eb8564eddb8f2b2966b18eff1f5c16..e4e4008cc8e9bc7f206ee67e9382caa19a207d5d 100644 (file)
@@ -3,9 +3,7 @@
 #include <errno.h>
 #include <fcntl.h>
 #include <poll.h>
-#include <sys/eventfd.h>
 #include <sys/file.h>
-#include <sys/ioctl.h>
 #include <sys/mman.h>
 #include <sys/personality.h>
 #include <sys/prctl.h>
 
 #include <linux/fs.h> /* Must be included after <sys/mount.h> */
 
-#if HAVE_PAM
-#include <security/pam_appl.h>
-#endif
-
-#if HAVE_SELINUX
-#include <selinux/selinux.h>
-#endif
-
-#if HAVE_APPARMOR
-#include <sys/apparmor.h>
-#endif
-
 #include "sd-messages.h"
 
 #include "af-list.h"
 #include "alloc-util.h"
-#if HAVE_APPARMOR
-#include "apparmor-util.h"
-#endif
-#include "argv-util.h"
 #include "async.h"
-#include "barrier.h"
-#include "bpf-lsm.h"
-#include "btrfs-util.h"
 #include "cap-list.h"
 #include "capability-util.h"
-#include "chattr-util.h"
 #include "cgroup-setup.h"
-#include "chase.h"
-#include "chown-recursive.h"
 #include "constants.h"
 #include "cpu-set-util.h"
-#include "data-fd-util.h"
 #include "env-file.h"
 #include "env-util.h"
 #include "errno-list.h"
 #include "escape.h"
 #include "exec-credential.h"
 #include "execute.h"
+#include "execute-serialize.h"
 #include "exit-status.h"
 #include "fd-util.h"
+#include "fileio.h"
 #include "format-util.h"
 #include "glob-util.h"
 #include "hexdecoct.h"
-#include "io-util.h"
 #include "ioprio-util.h"
 #include "lock-util.h"
 #include "log.h"
 #include "manager-dump.h"
 #include "memory-util.h"
 #include "missing_fs.h"
-#include "missing_ioprio.h"
 #include "missing_prctl.h"
 #include "mkdir-label.h"
 #include "namespace.h"
 #include "parse-util.h"
 #include "path-util.h"
-#include "proc-cmdline.h"
 #include "process-util.h"
-#include "psi-util.h"
 #include "rlimit-util.h"
 #include "rm-rf.h"
 #include "seccomp-util.h"
 #include "securebits-util.h"
 #include "selinux-util.h"
-#include "signal-util.h"
-#include "smack-util.h"
-#include "socket-util.h"
+#include "serialize.h"
 #include "sort-util.h"
 #include "special.h"
 #include "stat-util.h"
 #include "user-util.h"
 #include "utmp-wtmp.h"
 
-#define IDLE_TIMEOUT_USEC (5*USEC_PER_SEC)
-#define IDLE_TIMEOUT2_USEC (1*USEC_PER_SEC)
-
-#define SNDBUF_SIZE (8*1024*1024)
-
-static int shift_fds(int fds[], size_t n_fds) {
-        if (n_fds <= 0)
-                return 0;
-
-        /* Modifies the fds array! (sorts it) */
-
-        assert(fds);
-
-        for (int start = 0;;) {
-                int restart_from = -1;
-
-                for (int i = start; i < (int) n_fds; i++) {
-                        int nfd;
-
-                        /* Already at right index? */
-                        if (fds[i] == i+3)
-                                continue;
-
-                        nfd = fcntl(fds[i], F_DUPFD, i + 3);
-                        if (nfd < 0)
-                                return -errno;
-
-                        safe_close(fds[i]);
-                        fds[i] = nfd;
-
-                        /* Hmm, the fd we wanted isn't free? Then
-                         * let's remember that and try again from here */
-                        if (nfd != i+3 && restart_from < 0)
-                                restart_from = i;
-                }
-
-                if (restart_from < 0)
-                        break;
-
-                start = restart_from;
-        }
-
-        return 0;
-}
-
-static int flags_fds(
-                const int fds[],
-                size_t n_socket_fds,
-                size_t n_fds,
-                bool nonblock) {
-
-        int r;
-
-        if (n_fds <= 0)
-                return 0;
-
-        assert(fds);
-
-        /* Drops/Sets O_NONBLOCK and FD_CLOEXEC from the file flags.
-         * O_NONBLOCK only applies to socket activation though. */
-
-        for (size_t i = 0; i < n_fds; i++) {
-
-                if (i < n_socket_fds) {
-                        r = fd_nonblock(fds[i], nonblock);
-                        if (r < 0)
-                                return r;
-                }
-
-                /* We unconditionally drop FD_CLOEXEC from the fds,
-                 * since after all we want to pass these fds to our
-                 * children */
-
-                r = fd_cloexec(fds[i], false);
-                if (r < 0)
-                        return r;
-        }
-
-        return 0;
-}
-
-static const char *exec_context_tty_path(const ExecContext *context) {
+const char *exec_context_tty_path(const ExecContext *context) {
         assert(context);
 
         if (context->stdio_as_fds)
@@ -194,7 +84,7 @@ static const char *exec_context_tty_path(const ExecContext *context) {
         return "/dev/console";
 }
 
-static int exec_context_tty_size(const ExecContext *context, unsigned *ret_rows, unsigned *ret_cols) {
+int exec_context_tty_size(const ExecContext *context, unsigned *ret_rows, unsigned *ret_cols) {
         unsigned rows, cols;
         const char *tty;
 
@@ -215,7 +105,7 @@ static int exec_context_tty_size(const ExecContext *context, unsigned *ret_rows,
         return 0;
 }
 
-static void exec_context_tty_reset(const ExecContext *context, const ExecParameters *p) {
+void exec_context_tty_reset(const ExecContext *context, const ExecParameters *p) {
         _cleanup_close_ int fd = -EBADF;
         const char *path = exec_context_tty_path(ASSERT_PTR(context));
 
@@ -270,4918 +160,207 @@ static bool is_terminal_output(ExecOutput o) {
                       EXEC_OUTPUT_JOURNAL_AND_CONSOLE);
 }
 
-static bool is_kmsg_output(ExecOutput o) {
-        return IN_SET(o,
-                      EXEC_OUTPUT_KMSG,
-                      EXEC_OUTPUT_KMSG_AND_CONSOLE);
-}
-
-static bool exec_context_needs_term(const ExecContext *c) {
-        assert(c);
-
-        /* Return true if the execution context suggests we should set $TERM to something useful. */
-
-        if (is_terminal_input(c->std_input))
-                return true;
-
-        if (is_terminal_output(c->std_output))
-                return true;
-
-        if (is_terminal_output(c->std_error))
-                return true;
-
-        return !!c->tty_path;
-}
-
-static int open_null_as(int flags, int nfd) {
-        int fd;
-
-        assert(nfd >= 0);
-
-        fd = open("/dev/null", flags|O_NOCTTY);
-        if (fd < 0)
-                return -errno;
-
-        return move_fd(fd, nfd, false);
-}
-
-static int connect_journal_socket(
-                int fd,
-                const char *log_namespace,
-                uid_t uid,
-                gid_t gid) {
-
-        uid_t olduid = UID_INVALID;
-        gid_t oldgid = GID_INVALID;
-        const char *j;
-        int r;
-
-        j = log_namespace ?
-                strjoina("/run/systemd/journal.", log_namespace, "/stdout") :
-                "/run/systemd/journal/stdout";
-
-        if (gid_is_valid(gid)) {
-                oldgid = getgid();
-
-                if (setegid(gid) < 0)
-                        return -errno;
-        }
-
-        if (uid_is_valid(uid)) {
-                olduid = getuid();
-
-                if (seteuid(uid) < 0) {
-                        r = -errno;
-                        goto restore_gid;
-                }
-        }
-
-        r = connect_unix_path(fd, AT_FDCWD, j);
-
-        /* If we fail to restore the uid or gid, things will likely fail later on. This should only happen if
-           an LSM interferes. */
-
-        if (uid_is_valid(uid))
-                (void) seteuid(olduid);
-
- restore_gid:
-        if (gid_is_valid(gid))
-                (void) setegid(oldgid);
-
-        return r;
-}
-
-static int connect_logger_as(
-                const Unit *unit,
-                const ExecContext *context,
-                const ExecParameters *params,
-                ExecOutput output,
-                const char *ident,
-                int nfd,
-                uid_t uid,
-                gid_t gid) {
-
-        _cleanup_close_ int fd = -EBADF;
-        int r;
-
-        assert(context);
-        assert(params);
-        assert(output < _EXEC_OUTPUT_MAX);
-        assert(ident);
-        assert(nfd >= 0);
-
-        fd = socket(AF_UNIX, SOCK_STREAM, 0);
-        if (fd < 0)
-                return -errno;
-
-        r = connect_journal_socket(fd, context->log_namespace, uid, gid);
-        if (r < 0)
-                return r;
-
-        if (shutdown(fd, SHUT_RD) < 0)
-                return -errno;
-
-        (void) fd_inc_sndbuf(fd, SNDBUF_SIZE);
-
-        if (dprintf(fd,
-                "%s\n"
-                "%s\n"
-                "%i\n"
-                "%i\n"
-                "%i\n"
-                "%i\n"
-                "%i\n",
-                context->syslog_identifier ?: ident,
-                params->flags & EXEC_PASS_LOG_UNIT ? unit->id : "",
-                context->syslog_priority,
-                !!context->syslog_level_prefix,
-                false,
-                is_kmsg_output(output),
-                is_terminal_output(output)) < 0)
-                return -errno;
-
-        return move_fd(TAKE_FD(fd), nfd, false);
-}
-
-static int open_terminal_as(const char *path, int flags, int nfd) {
-        int fd;
-
-        assert(path);
-        assert(nfd >= 0);
-
-        fd = open_terminal(path, flags | O_NOCTTY);
-        if (fd < 0)
-                return fd;
-
-        return move_fd(fd, nfd, false);
-}
-
-static int acquire_path(const char *path, int flags, mode_t mode) {
-        _cleanup_close_ int fd = -EBADF;
-        int r;
-
-        assert(path);
-
-        if (IN_SET(flags & O_ACCMODE, O_WRONLY, O_RDWR))
-                flags |= O_CREAT;
-
-        fd = open(path, flags|O_NOCTTY, mode);
-        if (fd >= 0)
-                return TAKE_FD(fd);
-
-        if (errno != ENXIO) /* ENXIO is returned when we try to open() an AF_UNIX file system socket on Linux */
-                return -errno;
-
-        /* So, it appears the specified path could be an AF_UNIX socket. Let's see if we can connect to it. */
-
-        fd = socket(AF_UNIX, SOCK_STREAM, 0);
-        if (fd < 0)
-                return -errno;
-
-        r = connect_unix_path(fd, AT_FDCWD, path);
-        if (IN_SET(r, -ENOTSOCK, -EINVAL))
-                /* Propagate initial error if we get ENOTSOCK or EINVAL, i.e. we have indication that this
-                 * wasn't an AF_UNIX socket after all */
-                return -ENXIO;
-        if (r < 0)
-                return r;
-
-        if ((flags & O_ACCMODE) == O_RDONLY)
-                r = shutdown(fd, SHUT_WR);
-        else if ((flags & O_ACCMODE) == O_WRONLY)
-                r = shutdown(fd, SHUT_RD);
-        else
-                r = 0;
-        if (r < 0)
-                return -errno;
-
-        return TAKE_FD(fd);
-}
-
-static int fixup_input(
-                const ExecContext *context,
-                int socket_fd,
-                bool apply_tty_stdin) {
-
-        ExecInput std_input;
-
-        assert(context);
-
-        std_input = context->std_input;
-
-        if (is_terminal_input(std_input) && !apply_tty_stdin)
-                return EXEC_INPUT_NULL;
-
-        if (std_input == EXEC_INPUT_SOCKET && socket_fd < 0)
-                return EXEC_INPUT_NULL;
-
-        if (std_input == EXEC_INPUT_DATA && context->stdin_data_size == 0)
-                return EXEC_INPUT_NULL;
-
-        return std_input;
-}
-
-static int fixup_output(ExecOutput output, int socket_fd) {
-
-        if (output == EXEC_OUTPUT_SOCKET && socket_fd < 0)
-                return EXEC_OUTPUT_INHERIT;
-
-        return output;
-}
-
-static int setup_input(
-                const ExecContext *context,
-                const ExecParameters *params,
-                int socket_fd,
-                const int named_iofds[static 3]) {
-
-        ExecInput i;
-        int r;
-
+bool exec_needs_network_namespace(const ExecContext *context) {
         assert(context);
-        assert(params);
-        assert(named_iofds);
-
-        if (params->stdin_fd >= 0) {
-                if (dup2(params->stdin_fd, STDIN_FILENO) < 0)
-                        return -errno;
-
-                /* Try to make this the controlling tty, if it is a tty, and reset it */
-                if (isatty(STDIN_FILENO)) {
-                        unsigned rows = context->tty_rows, cols = context->tty_cols;
-
-                        (void) exec_context_tty_size(context, &rows, &cols);
-                        (void) ioctl(STDIN_FILENO, TIOCSCTTY, context->std_input == EXEC_INPUT_TTY_FORCE);
-                        (void) reset_terminal_fd(STDIN_FILENO, true);
-                        (void) terminal_set_size_fd(STDIN_FILENO, NULL, rows, cols);
-                }
-
-                return STDIN_FILENO;
-        }
-
-        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
-
-        switch (i) {
-
-        case EXEC_INPUT_NULL:
-                return open_null_as(O_RDONLY, STDIN_FILENO);
-
-        case EXEC_INPUT_TTY:
-        case EXEC_INPUT_TTY_FORCE:
-        case EXEC_INPUT_TTY_FAIL: {
-                unsigned rows, cols;
-                int fd;
-
-                fd = acquire_terminal(exec_context_tty_path(context),
-                                      i == EXEC_INPUT_TTY_FAIL  ? ACQUIRE_TERMINAL_TRY :
-                                      i == EXEC_INPUT_TTY_FORCE ? ACQUIRE_TERMINAL_FORCE :
-                                                                  ACQUIRE_TERMINAL_WAIT,
-                                      USEC_INFINITY);
-                if (fd < 0)
-                        return fd;
-
-                r = exec_context_tty_size(context, &rows, &cols);
-                if (r < 0)
-                        return r;
-
-                r = terminal_set_size_fd(fd, exec_context_tty_path(context), rows, cols);
-                if (r < 0)
-                        return r;
-
-                return move_fd(fd, STDIN_FILENO, false);
-        }
-
-        case EXEC_INPUT_SOCKET:
-                assert(socket_fd >= 0);
-
-                return RET_NERRNO(dup2(socket_fd, STDIN_FILENO));
-
-        case EXEC_INPUT_NAMED_FD:
-                assert(named_iofds[STDIN_FILENO] >= 0);
-
-                (void) fd_nonblock(named_iofds[STDIN_FILENO], false);
-                return RET_NERRNO(dup2(named_iofds[STDIN_FILENO], STDIN_FILENO));
-
-        case EXEC_INPUT_DATA: {
-                int fd;
-
-                fd = acquire_data_fd(context->stdin_data, context->stdin_data_size, 0);
-                if (fd < 0)
-                        return fd;
-
-                return move_fd(fd, STDIN_FILENO, false);
-        }
-
-        case EXEC_INPUT_FILE: {
-                bool rw;
-                int fd;
-
-                assert(context->stdio_file[STDIN_FILENO]);
-
-                rw = (context->std_output == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDOUT_FILENO])) ||
-                        (context->std_error == EXEC_OUTPUT_FILE && streq_ptr(context->stdio_file[STDIN_FILENO], context->stdio_file[STDERR_FILENO]));
-
-                fd = acquire_path(context->stdio_file[STDIN_FILENO], rw ? O_RDWR : O_RDONLY, 0666 & ~context->umask);
-                if (fd < 0)
-                        return fd;
-
-                return move_fd(fd, STDIN_FILENO, false);
-        }
 
-        default:
-                assert_not_reached();
-        }
+        return context->private_network || context->network_namespace_path;
 }
 
-static bool can_inherit_stderr_from_stdout(
-                const ExecContext *context,
-                ExecOutput o,
-                ExecOutput e) {
-
-        assert(context);
-
-        /* Returns true, if given the specified STDERR and STDOUT output we can directly dup() the stdout fd to the
-         * stderr fd */
-
-        if (e == EXEC_OUTPUT_INHERIT)
-                return true;
-        if (e != o)
-                return false;
-
-        if (e == EXEC_OUTPUT_NAMED_FD)
-                return streq_ptr(context->stdio_fdname[STDOUT_FILENO], context->stdio_fdname[STDERR_FILENO]);
-
-        if (IN_SET(e, EXEC_OUTPUT_FILE, EXEC_OUTPUT_FILE_APPEND, EXEC_OUTPUT_FILE_TRUNCATE))
-                return streq_ptr(context->stdio_file[STDOUT_FILENO], context->stdio_file[STDERR_FILENO]);
-
-        return true;
+static bool exec_needs_ephemeral(const ExecContext *context) {
+        return (context->root_image || context->root_directory) && context->root_ephemeral;
 }
 
-static int setup_output(
-                const Unit *unit,
-                const ExecContext *context,
-                const ExecParameters *params,
-                int fileno,
-                int socket_fd,
-                const int named_iofds[static 3],
-                const char *ident,
-                uid_t uid,
-                gid_t gid,
-                dev_t *journal_stream_dev,
-                ino_t *journal_stream_ino) {
-
-        ExecOutput o;
-        ExecInput i;
-        int r;
-
-        assert(unit);
+bool exec_needs_ipc_namespace(const ExecContext *context) {
         assert(context);
-        assert(params);
-        assert(ident);
-        assert(journal_stream_dev);
-        assert(journal_stream_ino);
-
-        if (fileno == STDOUT_FILENO && params->stdout_fd >= 0) {
-
-                if (dup2(params->stdout_fd, STDOUT_FILENO) < 0)
-                        return -errno;
-
-                return STDOUT_FILENO;
-        }
-
-        if (fileno == STDERR_FILENO && params->stderr_fd >= 0) {
-                if (dup2(params->stderr_fd, STDERR_FILENO) < 0)
-                        return -errno;
-
-                return STDERR_FILENO;
-        }
-
-        i = fixup_input(context, socket_fd, params->flags & EXEC_APPLY_TTY_STDIN);
-        o = fixup_output(context->std_output, socket_fd);
-
-        if (fileno == STDERR_FILENO) {
-                ExecOutput e;
-                e = fixup_output(context->std_error, socket_fd);
-
-                /* This expects the input and output are already set up */
-
-                /* Don't change the stderr file descriptor if we inherit all
-                 * the way and are not on a tty */
-                if (e == EXEC_OUTPUT_INHERIT &&
-                    o == EXEC_OUTPUT_INHERIT &&
-                    i == EXEC_INPUT_NULL &&
-                    !is_terminal_input(context->std_input) &&
-                    getppid() != 1)
-                        return fileno;
-
-                /* Duplicate from stdout if possible */
-                if (can_inherit_stderr_from_stdout(context, o, e))
-                        return RET_NERRNO(dup2(STDOUT_FILENO, fileno));
-
-                o = e;
-
-        } else if (o == EXEC_OUTPUT_INHERIT) {
-                /* If input got downgraded, inherit the original value */
-                if (i == EXEC_INPUT_NULL && is_terminal_input(context->std_input))
-                        return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
-
-                /* If the input is connected to anything that's not a /dev/null or a data fd, inherit that... */
-                if (!IN_SET(i, EXEC_INPUT_NULL, EXEC_INPUT_DATA))
-                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
-
-                /* If we are not started from PID 1 we just inherit STDOUT from our parent process. */
-                if (getppid() != 1)
-                        return fileno;
-
-                /* We need to open /dev/null here anew, to get the right access mode. */
-                return open_null_as(O_WRONLY, fileno);
-        }
-
-        switch (o) {
-
-        case EXEC_OUTPUT_NULL:
-                return open_null_as(O_WRONLY, fileno);
-
-        case EXEC_OUTPUT_TTY:
-                if (is_terminal_input(i))
-                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
-
-                /* We don't reset the terminal if this is just about output */
-                return open_terminal_as(exec_context_tty_path(context), O_WRONLY, fileno);
-
-        case EXEC_OUTPUT_KMSG:
-        case EXEC_OUTPUT_KMSG_AND_CONSOLE:
-        case EXEC_OUTPUT_JOURNAL:
-        case EXEC_OUTPUT_JOURNAL_AND_CONSOLE:
-                r = connect_logger_as(unit, context, params, o, ident, fileno, uid, gid);
-                if (r < 0) {
-                        log_unit_warning_errno(unit, r, "Failed to connect %s to the journal socket, ignoring: %m",
-                                               fileno == STDOUT_FILENO ? "stdout" : "stderr");
-                        r = open_null_as(O_WRONLY, fileno);
-                } else {
-                        struct stat st;
-
-                        /* If we connected this fd to the journal via a stream, patch the device/inode into the passed
-                         * parameters, but only then. This is useful so that we can set $JOURNAL_STREAM that permits
-                         * services to detect whether they are connected to the journal or not.
-                         *
-                         * If both stdout and stderr are connected to a stream then let's make sure to store the data
-                         * about STDERR as that's usually the best way to do logging. */
-
-                        if (fstat(fileno, &st) >= 0 &&
-                            (*journal_stream_ino == 0 || fileno == STDERR_FILENO)) {
-                                *journal_stream_dev = st.st_dev;
-                                *journal_stream_ino = st.st_ino;
-                        }
-                }
-                return r;
-
-        case EXEC_OUTPUT_SOCKET:
-                assert(socket_fd >= 0);
-
-                return RET_NERRNO(dup2(socket_fd, fileno));
-
-        case EXEC_OUTPUT_NAMED_FD:
-                assert(named_iofds[fileno] >= 0);
-
-                (void) fd_nonblock(named_iofds[fileno], false);
-                return RET_NERRNO(dup2(named_iofds[fileno], fileno));
-
-        case EXEC_OUTPUT_FILE:
-        case EXEC_OUTPUT_FILE_APPEND:
-        case EXEC_OUTPUT_FILE_TRUNCATE: {
-                bool rw;
-                int fd, flags;
-
-                assert(context->stdio_file[fileno]);
-
-                rw = context->std_input == EXEC_INPUT_FILE &&
-                        streq_ptr(context->stdio_file[fileno], context->stdio_file[STDIN_FILENO]);
-
-                if (rw)
-                        return RET_NERRNO(dup2(STDIN_FILENO, fileno));
-
-                flags = O_WRONLY;
-                if (o == EXEC_OUTPUT_FILE_APPEND)
-                        flags |= O_APPEND;
-                else if (o == EXEC_OUTPUT_FILE_TRUNCATE)
-                        flags |= O_TRUNC;
-
-                fd = acquire_path(context->stdio_file[fileno], flags, 0666 & ~context->umask);
-                if (fd < 0)
-                        return fd;
-
-                return move_fd(fd, fileno, 0);
-        }
-
-        default:
-                assert_not_reached();
-        }
-}
-
-static int chown_terminal(int fd, uid_t uid) {
-        int r;
-
-        assert(fd >= 0);
-
-        /* Before we chown/chmod the TTY, let's ensure this is actually a tty */
-        if (isatty(fd) < 1) {
-                if (IN_SET(errno, EINVAL, ENOTTY))
-                        return 0; /* not a tty */
-
-                return -errno;
-        }
-
-        /* This might fail. What matters are the results. */
-        r = fchmod_and_chown(fd, TTY_MODE, uid, GID_INVALID);
-        if (r < 0)
-                return r;
-
-        return 1;
-}
-
-static int setup_confirm_stdio(
-                const ExecContext *context,
-                const char *vc,
-                int *ret_saved_stdin,
-                int *ret_saved_stdout) {
-
-        _cleanup_close_ int fd = -EBADF, saved_stdin = -EBADF, saved_stdout = -EBADF;
-        unsigned rows, cols;
-        int r;
-
-        assert(ret_saved_stdin);
-        assert(ret_saved_stdout);
-
-        saved_stdin = fcntl(STDIN_FILENO, F_DUPFD, 3);
-        if (saved_stdin < 0)
-                return -errno;
-
-        saved_stdout = fcntl(STDOUT_FILENO, F_DUPFD, 3);
-        if (saved_stdout < 0)
-                return -errno;
-
-        fd = acquire_terminal(vc, ACQUIRE_TERMINAL_WAIT, DEFAULT_CONFIRM_USEC);
-        if (fd < 0)
-                return fd;
-
-        r = chown_terminal(fd, getuid());
-        if (r < 0)
-                return r;
-
-        r = reset_terminal_fd(fd, true);
-        if (r < 0)
-                return r;
-
-        r = exec_context_tty_size(context, &rows, &cols);
-        if (r < 0)
-                return r;
-
-        r = terminal_set_size_fd(fd, vc, rows, cols);
-        if (r < 0)
-                return r;
-
-        r = rearrange_stdio(fd, fd, STDERR_FILENO); /* Invalidates 'fd' also on failure */
-        TAKE_FD(fd);
-        if (r < 0)
-                return r;
-
-        *ret_saved_stdin = TAKE_FD(saved_stdin);
-        *ret_saved_stdout = TAKE_FD(saved_stdout);
-        return 0;
-}
-
-static void write_confirm_error_fd(int err, int fd, const Unit *u) {
-        assert(err < 0);
-
-        if (err == -ETIMEDOUT)
-                dprintf(fd, "Confirmation question timed out for %s, assuming positive response.\n", u->id);
-        else {
-                errno = -err;
-                dprintf(fd, "Couldn't ask confirmation for %s: %m, assuming positive response.\n", u->id);
-        }
-}
-
-static void write_confirm_error(int err, const char *vc, const Unit *u) {
-        _cleanup_close_ int fd = -EBADF;
-
-        assert(vc);
-
-        fd = open_terminal(vc, O_WRONLY|O_NOCTTY|O_CLOEXEC);
-        if (fd < 0)
-                return;
-
-        write_confirm_error_fd(err, fd, u);
-}
-
-static int restore_confirm_stdio(int *saved_stdin, int *saved_stdout) {
-        int r = 0;
-
-        assert(saved_stdin);
-        assert(saved_stdout);
-
-        release_terminal();
-
-        if (*saved_stdin >= 0)
-                if (dup2(*saved_stdin, STDIN_FILENO) < 0)
-                        r = -errno;
-
-        if (*saved_stdout >= 0)
-                if (dup2(*saved_stdout, STDOUT_FILENO) < 0)
-                        r = -errno;
-
-        *saved_stdin = safe_close(*saved_stdin);
-        *saved_stdout = safe_close(*saved_stdout);
-
-        return r;
-}
-
-enum {
-        CONFIRM_PRETEND_FAILURE = -1,
-        CONFIRM_PRETEND_SUCCESS =  0,
-        CONFIRM_EXECUTE = 1,
-};
-
-static int ask_for_confirmation(const ExecContext *context, const char *vc, Unit *u, const char *cmdline) {
-        int saved_stdout = -1, saved_stdin = -1, r;
-        _cleanup_free_ char *e = NULL;
-        char c;
-
-        /* For any internal errors, assume a positive response. */
-        r = setup_confirm_stdio(context, vc, &saved_stdin, &saved_stdout);
-        if (r < 0) {
-                write_confirm_error(r, vc, u);
-                return CONFIRM_EXECUTE;
-        }
-
-        /* confirm_spawn might have been disabled while we were sleeping. */
-        if (manager_is_confirm_spawn_disabled(u->manager)) {
-                r = 1;
-                goto restore_stdio;
-        }
-
-        e = ellipsize(cmdline, 60, 100);
-        if (!e) {
-                log_oom();
-                r = CONFIRM_EXECUTE;
-                goto restore_stdio;
-        }
-
-        for (;;) {
-                r = ask_char(&c, "yfshiDjcn", "Execute %s? [y, f, s – h for help] ", e);
-                if (r < 0) {
-                        write_confirm_error_fd(r, STDOUT_FILENO, u);
-                        r = CONFIRM_EXECUTE;
-                        goto restore_stdio;
-                }
-
-                switch (c) {
-                case 'c':
-                        printf("Resuming normal execution.\n");
-                        manager_disable_confirm_spawn();
-                        r = 1;
-                        break;
-                case 'D':
-                        unit_dump(u, stdout, "  ");
-                        continue; /* ask again */
-                case 'f':
-                        printf("Failing execution.\n");
-                        r = CONFIRM_PRETEND_FAILURE;
-                        break;
-                case 'h':
-                        printf("  c - continue, proceed without asking anymore\n"
-                               "  D - dump, show the state of the unit\n"
-                               "  f - fail, don't execute the command and pretend it failed\n"
-                               "  h - help\n"
-                               "  i - info, show a short summary of the unit\n"
-                               "  j - jobs, show jobs that are in progress\n"
-                               "  s - skip, don't execute the command and pretend it succeeded\n"
-                               "  y - yes, execute the command\n");
-                        continue; /* ask again */
-                case 'i':
-                        printf("  Description: %s\n"
-                               "  Unit:        %s\n"
-                               "  Command:     %s\n",
-                               u->id, u->description, cmdline);
-                        continue; /* ask again */
-                case 'j':
-                        manager_dump_jobs(u->manager, stdout, /* patterns= */ NULL, "  ");
-                        continue; /* ask again */
-                case 'n':
-                        /* 'n' was removed in favor of 'f'. */
-                        printf("Didn't understand 'n', did you mean 'f'?\n");
-                        continue; /* ask again */
-                case 's':
-                        printf("Skipping execution.\n");
-                        r = CONFIRM_PRETEND_SUCCESS;
-                        break;
-                case 'y':
-                        r = CONFIRM_EXECUTE;
-                        break;
-                default:
-                        assert_not_reached();
-                }
-                break;
-        }
-
-restore_stdio:
-        restore_confirm_stdio(&saved_stdin, &saved_stdout);
-        return r;
-}
-
-static int get_fixed_user(
-                const char *username,
-                const char **ret_user,
-                uid_t *ret_uid,
-                gid_t *ret_gid,
-                const char **ret_home,
-                const char **ret_shell) {
-
-        int r;
-
-        assert(username);
-        assert(ret_user);
-
-        /* Note that we don't set $HOME or $SHELL if they are not particularly enlightening anyway
-         * (i.e. are "/" or "/bin/nologin"). */
-
-        r = get_user_creds(&username, ret_uid, ret_gid, ret_home, ret_shell, USER_CREDS_CLEAN);
-        if (r < 0)
-                return r;
-
-        *ret_user = username;
-        return 0;
-}
-
-static int get_fixed_group(
-                const char *groupname,
-                const char **ret_group,
-                gid_t *ret_gid) {
-
-        int r;
-
-        assert(groupname);
-        assert(ret_group);
-
-        r = get_group_creds(&groupname, ret_gid, /* flags = */ 0);
-        if (r < 0)
-                return r;
-
-        *ret_group = groupname;
-        return 0;
-}
-
-static int get_supplementary_groups(const ExecContext *c, const char *user,
-                                    const char *group, gid_t gid,
-                                    gid_t **supplementary_gids, int *ngids) {
-        int r, k = 0;
-        int ngroups_max;
-        bool keep_groups = false;
-        gid_t *groups = NULL;
-        _cleanup_free_ gid_t *l_gids = NULL;
-
-        assert(c);
-
-        /*
-         * If user is given, then lookup GID and supplementary groups list.
-         * We avoid NSS lookups for gid=0. Also we have to initialize groups
-         * here and as early as possible so we keep the list of supplementary
-         * groups of the caller.
-         */
-        if (user && gid_is_valid(gid) && gid != 0) {
-                /* First step, initialize groups from /etc/groups */
-                if (initgroups(user, gid) < 0)
-                        return -errno;
-
-                keep_groups = true;
-        }
-
-        if (strv_isempty(c->supplementary_groups))
-                return 0;
-
-        /*
-         * If SupplementaryGroups= was passed then NGROUPS_MAX has to
-         * be positive, otherwise fail.
-         */
-        errno = 0;
-        ngroups_max = (int) sysconf(_SC_NGROUPS_MAX);
-        if (ngroups_max <= 0)
-                return errno_or_else(EOPNOTSUPP);
-
-        l_gids = new(gid_t, ngroups_max);
-        if (!l_gids)
-                return -ENOMEM;
-
-        if (keep_groups) {
-                /*
-                 * Lookup the list of groups that the user belongs to, we
-                 * avoid NSS lookups here too for gid=0.
-                 */
-                k = ngroups_max;
-                if (getgrouplist(user, gid, l_gids, &k) < 0)
-                        return -EINVAL;
-        } else
-                k = 0;
-
-        STRV_FOREACH(i, c->supplementary_groups) {
-                const char *g;
-
-                if (k >= ngroups_max)
-                        return -E2BIG;
-
-                g = *i;
-                r = get_group_creds(&g, l_gids+k, 0);
-                if (r < 0)
-                        return r;
-
-                k++;
-        }
-
-        /*
-         * Sets ngids to zero to drop all supplementary groups, happens
-         * when we are under root and SupplementaryGroups= is empty.
-         */
-        if (k == 0) {
-                *ngids = 0;
-                return 0;
-        }
-
-        /* Otherwise get the final list of supplementary groups */
-        groups = memdup(l_gids, sizeof(gid_t) * k);
-        if (!groups)
-                return -ENOMEM;
-
-        *supplementary_gids = groups;
-        *ngids = k;
-
-        groups = NULL;
-
-        return 0;
-}
-
-static int enforce_groups(gid_t gid, const gid_t *supplementary_gids, int ngids) {
-        int r;
-
-        /* Handle SupplementaryGroups= if it is not empty */
-        if (ngids > 0) {
-                r = maybe_setgroups(ngids, supplementary_gids);
-                if (r < 0)
-                        return r;
-        }
-
-        if (gid_is_valid(gid)) {
-                /* Then set our gids */
-                if (setresgid(gid, gid, gid) < 0)
-                        return -errno;
-        }
-
-        return 0;
-}
-
-static int set_securebits(unsigned bits, unsigned mask) {
-        unsigned applied;
-        int current;
-
-        current = prctl(PR_GET_SECUREBITS);
-        if (current < 0)
-                return -errno;
-
-        /* Clear all securebits defined in mask and set bits */
-        applied = ((unsigned) current & ~mask) | bits;
-        if ((unsigned) current == applied)
-                return 0;
-
-        if (prctl(PR_SET_SECUREBITS, applied) < 0)
-                return -errno;
-
-        return 1;
-}
-
-static int enforce_user(
-                const ExecContext *context,
-                uid_t uid,
-                uint64_t capability_ambient_set) {
-        assert(context);
-        int r;
-
-        if (!uid_is_valid(uid))
-                return 0;
-
-        /* Sets (but doesn't look up) the UIS and makes sure we keep the capabilities while doing so. For
-         * setting secure bits the capability CAP_SETPCAP is required, so we also need keep-caps in this
-         * case. */
-
-        if ((capability_ambient_set != 0 || context->secure_bits != 0) && uid != 0) {
-
-                /* First step: If we need to keep capabilities but drop privileges we need to make sure we
-                 * keep our caps, while we drop privileges. Add KEEP_CAPS to the securebits */
-                r = set_securebits(1U << SECURE_KEEP_CAPS, 0);
-                if (r < 0)
-                        return r;
-        }
-
-        /* Second step: actually set the uids */
-        if (setresuid(uid, uid, uid) < 0)
-                return -errno;
-
-        /* At this point we should have all necessary capabilities but are otherwise a normal user. However,
-         * the caps might got corrupted due to the setresuid() so we need clean them up later. This is done
-         * outside of this call. */
-        return 0;
-}
-
-#if HAVE_PAM
-
-static int null_conv(
-                int num_msg,
-                const struct pam_message **msg,
-                struct pam_response **resp,
-                void *appdata_ptr) {
-
-        /* We don't support conversations */
-
-        return PAM_CONV_ERR;
-}
-
-#endif
-
-static int setup_pam(
-                const char *name,
-                const char *user,
-                uid_t uid,
-                gid_t gid,
-                const char *tty,
-                char ***env, /* updated on success */
-                const int fds[], size_t n_fds) {
-
-#if HAVE_PAM
-
-        static const struct pam_conv conv = {
-                .conv = null_conv,
-                .appdata_ptr = NULL
-        };
-
-        _cleanup_(barrier_destroy) Barrier barrier = BARRIER_NULL;
-        _cleanup_strv_free_ char **e = NULL;
-        pam_handle_t *handle = NULL;
-        sigset_t old_ss;
-        int pam_code = PAM_SUCCESS, r;
-        bool close_session = false;
-        pid_t pam_pid = 0, parent_pid;
-        int flags = 0;
-
-        assert(name);
-        assert(user);
-        assert(env);
-
-        /* We set up PAM in the parent process, then fork. The child
-         * will then stay around until killed via PR_GET_PDEATHSIG or
-         * systemd via the cgroup logic. It will then remove the PAM
-         * session again. The parent process will exec() the actual
-         * daemon. We do things this way to ensure that the main PID
-         * of the daemon is the one we initially fork()ed. */
-
-        r = barrier_create(&barrier);
-        if (r < 0)
-                goto fail;
-
-        if (log_get_max_level() < LOG_DEBUG)
-                flags |= PAM_SILENT;
-
-        pam_code = pam_start(name, user, &conv, &handle);
-        if (pam_code != PAM_SUCCESS) {
-                handle = NULL;
-                goto fail;
-        }
-
-        if (!tty) {
-                _cleanup_free_ char *q = NULL;
-
-                /* Hmm, so no TTY was explicitly passed, but an fd passed to us directly might be a TTY. Let's figure
-                 * out if that's the case, and read the TTY off it. */
-
-                if (getttyname_malloc(STDIN_FILENO, &q) >= 0)
-                        tty = strjoina("/dev/", q);
-        }
-
-        if (tty) {
-                pam_code = pam_set_item(handle, PAM_TTY, tty);
-                if (pam_code != PAM_SUCCESS)
-                        goto fail;
-        }
-
-        STRV_FOREACH(nv, *env) {
-                pam_code = pam_putenv(handle, *nv);
-                if (pam_code != PAM_SUCCESS)
-                        goto fail;
-        }
-
-        pam_code = pam_acct_mgmt(handle, flags);
-        if (pam_code != PAM_SUCCESS)
-                goto fail;
-
-        pam_code = pam_setcred(handle, PAM_ESTABLISH_CRED | flags);
-        if (pam_code != PAM_SUCCESS)
-                log_debug("pam_setcred() failed, ignoring: %s", pam_strerror(handle, pam_code));
-
-        pam_code = pam_open_session(handle, flags);
-        if (pam_code != PAM_SUCCESS)
-                goto fail;
-
-        close_session = true;
-
-        e = pam_getenvlist(handle);
-        if (!e) {
-                pam_code = PAM_BUF_ERR;
-                goto fail;
-        }
-
-        /* Block SIGTERM, so that we know that it won't get lost in the child */
-
-        assert_se(sigprocmask_many(SIG_BLOCK, &old_ss, SIGTERM, -1) >= 0);
-
-        parent_pid = getpid_cached();
-
-        r = safe_fork("(sd-pam)", 0, &pam_pid);
-        if (r < 0)
-                goto fail;
-        if (r == 0) {
-                int sig, ret = EXIT_PAM;
-
-                /* The child's job is to reset the PAM session on termination */
-                barrier_set_role(&barrier, BARRIER_CHILD);
-
-                /* Make sure we don't keep open the passed fds in this child. We assume that otherwise only
-                 * those fds are open here that have been opened by PAM. */
-                (void) close_many(fds, n_fds);
-
-                /* Drop privileges - we don't need any to pam_close_session and this will make
-                 * PR_SET_PDEATHSIG work in most cases.  If this fails, ignore the error - but expect sd-pam
-                 * threads to fail to exit normally */
-
-                r = maybe_setgroups(0, NULL);
-                if (r < 0)
-                        log_warning_errno(r, "Failed to setgroups() in sd-pam: %m");
-                if (setresgid(gid, gid, gid) < 0)
-                        log_warning_errno(errno, "Failed to setresgid() in sd-pam: %m");
-                if (setresuid(uid, uid, uid) < 0)
-                        log_warning_errno(errno, "Failed to setresuid() in sd-pam: %m");
-
-                (void) ignore_signals(SIGPIPE);
-
-                /* Wait until our parent died. This will only work if the above setresuid() succeeds,
-                 * otherwise the kernel will not allow unprivileged parents kill their privileged children
-                 * this way. We rely on the control groups kill logic to do the rest for us. */
-                if (prctl(PR_SET_PDEATHSIG, SIGTERM) < 0)
-                        goto child_finish;
-
-                /* Tell the parent that our setup is done. This is especially important regarding dropping
-                 * privileges. Otherwise, unit setup might race against our setresuid(2) call.
-                 *
-                 * If the parent aborted, we'll detect this below, hence ignore return failure here. */
-                (void) barrier_place(&barrier);
-
-                /* Check if our parent process might already have died? */
-                if (getppid() == parent_pid) {
-                        sigset_t ss;
-
-                        assert_se(sigemptyset(&ss) >= 0);
-                        assert_se(sigaddset(&ss, SIGTERM) >= 0);
-
-                        for (;;) {
-                                if (sigwait(&ss, &sig) < 0) {
-                                        if (errno == EINTR)
-                                                continue;
-
-                                        goto child_finish;
-                                }
-
-                                assert(sig == SIGTERM);
-                                break;
-                        }
-                }
-
-                pam_code = pam_setcred(handle, PAM_DELETE_CRED | flags);
-                if (pam_code != PAM_SUCCESS)
-                        goto child_finish;
-
-                /* If our parent died we'll end the session */
-                if (getppid() != parent_pid) {
-                        pam_code = pam_close_session(handle, flags);
-                        if (pam_code != PAM_SUCCESS)
-                                goto child_finish;
-                }
-
-                ret = 0;
-
-        child_finish:
-                /* NB: pam_end() when called in child processes should set PAM_DATA_SILENT to let the module
-                 * know about this. See pam_end(3) */
-                (void) pam_end(handle, pam_code | flags | PAM_DATA_SILENT);
-                _exit(ret);
-        }
-
-        barrier_set_role(&barrier, BARRIER_PARENT);
-
-        /* If the child was forked off successfully it will do all the cleanups, so forget about the handle
-         * here. */
-        handle = NULL;
-
-        /* Unblock SIGTERM again in the parent */
-        assert_se(sigprocmask(SIG_SETMASK, &old_ss, NULL) >= 0);
-
-        /* We close the log explicitly here, since the PAM modules might have opened it, but we don't want
-         * this fd around. */
-        closelog();
-
-        /* Synchronously wait for the child to initialize. We don't care for errors as we cannot
-         * recover. However, warn loudly if it happens. */
-        if (!barrier_place_and_sync(&barrier))
-                log_error("PAM initialization failed");
-
-        return strv_free_and_replace(*env, e);
-
-fail:
-        if (pam_code != PAM_SUCCESS) {
-                log_error("PAM failed: %s", pam_strerror(handle, pam_code));
-                r = -EPERM;  /* PAM errors do not map to errno */
-        } else
-                log_error_errno(r, "PAM failed: %m");
-
-        if (handle) {
-                if (close_session)
-                        pam_code = pam_close_session(handle, flags);
-
-                (void) pam_end(handle, pam_code | flags);
-        }
-
-        closelog();
-        return r;
-#else
-        return 0;
-#endif
-}
-
-static void rename_process_from_path(const char *path) {
-        _cleanup_free_ char *buf = NULL;
-        const char *p;
-
-        assert(path);
-
-        /* This resulting string must fit in 10 chars (i.e. the length of "/sbin/init") to look pretty in
-         * /bin/ps */
-
-        if (path_extract_filename(path, &buf) < 0) {
-                rename_process("(...)");
-                return;
-        }
-
-        size_t l = strlen(buf);
-        if (l > 8) {
-                /* The end of the process name is usually more interesting, since the first bit might just be
-                 * "systemd-" */
-                p = buf + l - 8;
-                l = 8;
-        } else
-                p = buf;
-
-        char process_name[11];
-        process_name[0] = '(';
-        memcpy(process_name+1, p, l);
-        process_name[1+l] = ')';
-        process_name[1+l+1] = 0;
-
-        rename_process(process_name);
-}
-
-static bool context_has_address_families(const ExecContext *c) {
-        assert(c);
-
-        return c->address_families_allow_list ||
-                !set_isempty(c->address_families);
-}
-
-static bool context_has_syscall_filters(const ExecContext *c) {
-        assert(c);
-
-        return c->syscall_allow_list ||
-                !hashmap_isempty(c->syscall_filter);
-}
-
-static bool context_has_syscall_logs(const ExecContext *c) {
-        assert(c);
-
-        return c->syscall_log_allow_list ||
-                !hashmap_isempty(c->syscall_log);
-}
-
-static bool context_has_no_new_privileges(const ExecContext *c) {
-        assert(c);
-
-        if (c->no_new_privileges)
-                return true;
-
-        if (have_effective_cap(CAP_SYS_ADMIN) > 0) /* if we are privileged, we don't need NNP */
-                return false;
-
-        /* We need NNP if we have any form of seccomp and are unprivileged */
-        return c->lock_personality ||
-                c->memory_deny_write_execute ||
-                c->private_devices ||
-                c->protect_clock ||
-                c->protect_hostname ||
-                c->protect_kernel_tunables ||
-                c->protect_kernel_modules ||
-                c->protect_kernel_logs ||
-                context_has_address_families(c) ||
-                exec_context_restrict_namespaces_set(c) ||
-                c->restrict_realtime ||
-                c->restrict_suid_sgid ||
-                !set_isempty(c->syscall_archs) ||
-                context_has_syscall_filters(c) ||
-                context_has_syscall_logs(c);
-}
-
-#if HAVE_SECCOMP
-
-static bool skip_seccomp_unavailable(const Unit* u, const char* msg) {
-
-        if (is_seccomp_available())
-                return false;
-
-        log_unit_debug(u, "SECCOMP features not detected in the kernel, skipping %s", msg);
-        return true;
-}
-
-static int apply_syscall_filter(const Unit* u, const ExecContext *c, bool needs_ambient_hack) {
-        uint32_t negative_action, default_action, action;
-        int r;
-
-        assert(u);
-        assert(c);
-
-        if (!context_has_syscall_filters(c))
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "SystemCallFilter="))
-                return 0;
-
-        negative_action = c->syscall_errno == SECCOMP_ERROR_NUMBER_KILL ? scmp_act_kill_process() : SCMP_ACT_ERRNO(c->syscall_errno);
-
-        if (c->syscall_allow_list) {
-                default_action = negative_action;
-                action = SCMP_ACT_ALLOW;
-        } else {
-                default_action = SCMP_ACT_ALLOW;
-                action = negative_action;
-        }
-
-        if (needs_ambient_hack) {
-                r = seccomp_filter_set_add(c->syscall_filter, c->syscall_allow_list, syscall_filter_sets + SYSCALL_FILTER_SET_SETUID);
-                if (r < 0)
-                        return r;
-        }
-
-        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_filter, action, false);
-}
-
-static int apply_syscall_log(const Unit* u, const ExecContext *c) {
-#ifdef SCMP_ACT_LOG
-        uint32_t default_action, action;
-#endif
-
-        assert(u);
-        assert(c);
-
-        if (!context_has_syscall_logs(c))
-                return 0;
-
-#ifdef SCMP_ACT_LOG
-        if (skip_seccomp_unavailable(u, "SystemCallLog="))
-                return 0;
-
-        if (c->syscall_log_allow_list) {
-                /* Log nothing but the ones listed */
-                default_action = SCMP_ACT_ALLOW;
-                action = SCMP_ACT_LOG;
-        } else {
-                /* Log everything but the ones listed */
-                default_action = SCMP_ACT_LOG;
-                action = SCMP_ACT_ALLOW;
-        }
-
-        return seccomp_load_syscall_filter_set_raw(default_action, c->syscall_log, action, false);
-#else
-        /* old libseccomp */
-        log_unit_debug(u, "SECCOMP feature SCMP_ACT_LOG not available, skipping SystemCallLog=");
-        return 0;
-#endif
-}
-
-static int apply_syscall_archs(const Unit *u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        if (set_isempty(c->syscall_archs))
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "SystemCallArchitectures="))
-                return 0;
-
-        return seccomp_restrict_archs(c->syscall_archs);
-}
-
-static int apply_address_families(const Unit* u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        if (!context_has_address_families(c))
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "RestrictAddressFamilies="))
-                return 0;
-
-        return seccomp_restrict_address_families(c->address_families, c->address_families_allow_list);
-}
-
-static int apply_memory_deny_write_execute(const Unit* u, const ExecContext *c) {
-        int r;
-
-        assert(u);
-        assert(c);
-
-        if (!c->memory_deny_write_execute)
-                return 0;
-
-        /* use prctl() if kernel supports it (6.3) */
-        r = prctl(PR_SET_MDWE, PR_MDWE_REFUSE_EXEC_GAIN, 0, 0, 0);
-        if (r == 0) {
-                log_unit_debug(u, "Enabled MemoryDenyWriteExecute= with PR_SET_MDWE");
-                return 0;
-        }
-        if (r < 0 && errno != EINVAL)
-                return log_unit_debug_errno(u, errno, "Failed to enable MemoryDenyWriteExecute= with PR_SET_MDWE: %m");
-        /* else use seccomp */
-        log_unit_debug(u, "Kernel doesn't support PR_SET_MDWE: falling back to seccomp");
-
-        if (skip_seccomp_unavailable(u, "MemoryDenyWriteExecute="))
-                return 0;
-
-        return seccomp_memory_deny_write_execute();
-}
-
-static int apply_restrict_realtime(const Unit* u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        if (!c->restrict_realtime)
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "RestrictRealtime="))
-                return 0;
-
-        return seccomp_restrict_realtime();
-}
-
-static int apply_restrict_suid_sgid(const Unit* u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        if (!c->restrict_suid_sgid)
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "RestrictSUIDSGID="))
-                return 0;
-
-        return seccomp_restrict_suid_sgid();
-}
-
-static int apply_protect_sysctl(const Unit *u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        /* Turn off the legacy sysctl() system call. Many distributions turn this off while building the kernel, but
-         * let's protect even those systems where this is left on in the kernel. */
-
-        if (!c->protect_kernel_tunables)
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "ProtectKernelTunables="))
-                return 0;
-
-        return seccomp_protect_sysctl();
-}
-
-static int apply_protect_kernel_modules(const Unit *u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        /* Turn off module syscalls on ProtectKernelModules=yes */
-
-        if (!c->protect_kernel_modules)
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "ProtectKernelModules="))
-                return 0;
-
-        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_MODULE, SCMP_ACT_ERRNO(EPERM), false);
-}
-
-static int apply_protect_kernel_logs(const Unit *u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        if (!c->protect_kernel_logs)
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "ProtectKernelLogs="))
-                return 0;
-
-        return seccomp_protect_syslog();
-}
-
-static int apply_protect_clock(const Unit *u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        if (!c->protect_clock)
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "ProtectClock="))
-                return 0;
-
-        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_CLOCK, SCMP_ACT_ERRNO(EPERM), false);
-}
-
-static int apply_private_devices(const Unit *u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        /* If PrivateDevices= is set, also turn off iopl and all @raw-io syscalls. */
-
-        if (!c->private_devices)
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "PrivateDevices="))
-                return 0;
-
-        return seccomp_load_syscall_filter_set(SCMP_ACT_ALLOW, syscall_filter_sets + SYSCALL_FILTER_SET_RAW_IO, SCMP_ACT_ERRNO(EPERM), false);
-}
-
-static int apply_restrict_namespaces(const Unit *u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        if (!exec_context_restrict_namespaces_set(c))
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "RestrictNamespaces="))
-                return 0;
-
-        return seccomp_restrict_namespaces(c->restrict_namespaces);
-}
-
-static int apply_lock_personality(const Unit* u, const ExecContext *c) {
-        unsigned long personality;
-        int r;
-
-        assert(u);
-        assert(c);
-
-        if (!c->lock_personality)
-                return 0;
-
-        if (skip_seccomp_unavailable(u, "LockPersonality="))
-                return 0;
-
-        personality = c->personality;
-
-        /* If personality is not specified, use either PER_LINUX or PER_LINUX32 depending on what is currently set. */
-        if (personality == PERSONALITY_INVALID) {
-
-                r = opinionated_personality(&personality);
-                if (r < 0)
-                        return r;
-        }
-
-        return seccomp_lock_personality(personality);
-}
-
-#endif
-
-#if HAVE_LIBBPF
-static int apply_restrict_filesystems(Unit *u, const ExecContext *c) {
-        assert(u);
-        assert(c);
-
-        if (!exec_context_restrict_filesystems_set(c))
-                return 0;
-
-        if (!u->manager->restrict_fs) {
-                /* LSM BPF is unsupported or lsm_bpf_setup failed */
-                log_unit_debug(u, "LSM BPF not supported, skipping RestrictFileSystems=");
-                return 0;
-        }
-
-        return lsm_bpf_unit_restrict_filesystems(u, c->restrict_filesystems, c->restrict_filesystems_allow_list);
-}
-#endif
-
-static int apply_protect_hostname(const Unit *u, const ExecContext *c, int *ret_exit_status) {
-        assert(u);
-        assert(c);
-
-        if (!c->protect_hostname)
-                return 0;
-
-        if (ns_type_supported(NAMESPACE_UTS)) {
-                if (unshare(CLONE_NEWUTS) < 0) {
-                        if (!ERRNO_IS_NOT_SUPPORTED(errno) && !ERRNO_IS_PRIVILEGE(errno)) {
-                                *ret_exit_status = EXIT_NAMESPACE;
-                                return log_unit_error_errno(u, errno, "Failed to set up UTS namespacing: %m");
-                        }
-
-                        log_unit_warning(u, "ProtectHostname=yes is configured, but UTS namespace setup is prohibited (container manager?), ignoring namespace setup.");
-                }
-        } else
-                log_unit_warning(u, "ProtectHostname=yes is configured, but the kernel does not support UTS namespaces, ignoring namespace setup.");
-
-#if HAVE_SECCOMP
-        int r;
-
-        if (skip_seccomp_unavailable(u, "ProtectHostname="))
-                return 0;
-
-        r = seccomp_protect_hostname();
-        if (r < 0) {
-                *ret_exit_status = EXIT_SECCOMP;
-                return log_unit_error_errno(u, r, "Failed to apply hostname restrictions: %m");
-        }
-#endif
-
-        return 0;
-}
-
-static void do_idle_pipe_dance(int idle_pipe[static 4]) {
-        assert(idle_pipe);
-
-        idle_pipe[1] = safe_close(idle_pipe[1]);
-        idle_pipe[2] = safe_close(idle_pipe[2]);
-
-        if (idle_pipe[0] >= 0) {
-                int r;
-
-                r = fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT_USEC);
-
-                if (idle_pipe[3] >= 0 && r == 0 /* timeout */) {
-                        ssize_t n;
-
-                        /* Signal systemd that we are bored and want to continue. */
-                        n = write(idle_pipe[3], "x", 1);
-                        if (n > 0)
-                                /* Wait for systemd to react to the signal above. */
-                                (void) fd_wait_for_event(idle_pipe[0], POLLHUP, IDLE_TIMEOUT2_USEC);
-                }
-
-                idle_pipe[0] = safe_close(idle_pipe[0]);
-
-        }
-
-        idle_pipe[3] = safe_close(idle_pipe[3]);
-}
-
-static const char *exec_directory_env_name_to_string(ExecDirectoryType t);
-
-static int build_environment(
-                const Unit *u,
-                const ExecContext *c,
-                const ExecParameters *p,
-                const CGroupContext *cgroup_context,
-                size_t n_fds,
-                char **fdnames,
-                const char *home,
-                const char *username,
-                const char *shell,
-                dev_t journal_stream_dev,
-                ino_t journal_stream_ino,
-                const char *memory_pressure_path,
-                char ***ret) {
-
-        _cleanup_strv_free_ char **our_env = NULL;
-        size_t n_env = 0;
-        char *x;
-        int r;
-
-        assert(u);
-        assert(c);
-        assert(p);
-        assert(ret);
-
-#define N_ENV_VARS 19
-        our_env = new0(char*, N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
-        if (!our_env)
-                return -ENOMEM;
-
-        if (n_fds > 0) {
-                _cleanup_free_ char *joined = NULL;
-
-                if (asprintf(&x, "LISTEN_PID="PID_FMT, getpid_cached()) < 0)
-                        return -ENOMEM;
-                our_env[n_env++] = x;
-
-                if (asprintf(&x, "LISTEN_FDS=%zu", n_fds) < 0)
-                        return -ENOMEM;
-                our_env[n_env++] = x;
-
-                joined = strv_join(fdnames, ":");
-                if (!joined)
-                        return -ENOMEM;
-
-                x = strjoin("LISTEN_FDNAMES=", joined);
-                if (!x)
-                        return -ENOMEM;
-                our_env[n_env++] = x;
-        }
-
-        if ((p->flags & EXEC_SET_WATCHDOG) && p->watchdog_usec > 0) {
-                if (asprintf(&x, "WATCHDOG_PID="PID_FMT, getpid_cached()) < 0)
-                        return -ENOMEM;
-                our_env[n_env++] = x;
-
-                if (asprintf(&x, "WATCHDOG_USEC="USEC_FMT, p->watchdog_usec) < 0)
-                        return -ENOMEM;
-                our_env[n_env++] = x;
-        }
-
-        /* If this is D-Bus, tell the nss-systemd module, since it relies on being able to use blocking
-         * Varlink calls back to us for look up dynamic users in PID 1. Break the deadlock between D-Bus and
-         * PID 1 by disabling use of PID1' NSS interface for looking up dynamic users. */
-        if (p->flags & EXEC_NSS_DYNAMIC_BYPASS) {
-                x = strdup("SYSTEMD_NSS_DYNAMIC_BYPASS=1");
-                if (!x)
-                        return -ENOMEM;
-                our_env[n_env++] = x;
-        }
-
-        /* We query "root" if this is a system unit and User= is not specified. $USER is always set. $HOME
-         * could cause problem for e.g. getty, since login doesn't override $HOME, and $LOGNAME and $SHELL don't
-         * really make much sense since we're not logged in. Hence we conditionalize the three based on
-         * SetLoginEnvironment= switch. */
-        if (!c->user && !c->dynamic_user && p->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
-                r = get_fixed_user("root", &username, NULL, NULL, &home, &shell);
-                if (r < 0)
-                        return log_unit_error_errno(u, r, "Failed to determine user credentials for root: %m");
-        }
-
-        bool set_user_login_env = c->set_login_environment >= 0 ? c->set_login_environment : (c->user || c->dynamic_user);
-
-        if (username) {
-                x = strjoin("USER=", username);
-                if (!x)
-                        return -ENOMEM;
-                our_env[n_env++] = x;
-
-                if (set_user_login_env) {
-                        x = strjoin("LOGNAME=", username);
-                        if (!x)
-                                return -ENOMEM;
-                        our_env[n_env++] = x;
-                }
-        }
-
-        if (home && set_user_login_env) {
-                x = strjoin("HOME=", home);
-                if (!x)
-                        return -ENOMEM;
-
-                path_simplify(x + 5);
-                our_env[n_env++] = x;
-        }
-
-        if (shell && set_user_login_env) {
-                x = strjoin("SHELL=", shell);
-                if (!x)
-                        return -ENOMEM;
-
-                path_simplify(x + 6);
-                our_env[n_env++] = x;
-        }
-
-        if (!sd_id128_is_null(u->invocation_id)) {
-                if (asprintf(&x, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(u->invocation_id)) < 0)
-                        return -ENOMEM;
-
-                our_env[n_env++] = x;
-        }
-
-        if (exec_context_needs_term(c)) {
-                _cleanup_free_ char *cmdline = NULL;
-                const char *tty_path, *term = NULL;
-
-                tty_path = exec_context_tty_path(c);
-
-                /* If we are forked off PID 1 and we are supposed to operate on /dev/console, then let's try
-                 * to inherit the $TERM set for PID 1. This is useful for containers so that the $TERM the
-                 * container manager passes to PID 1 ends up all the way in the console login shown. */
-
-                if (path_equal_ptr(tty_path, "/dev/console") && getppid() == 1)
-                        term = getenv("TERM");
-                else if (tty_path && in_charset(skip_dev_prefix(tty_path), ALPHANUMERICAL)) {
-                        _cleanup_free_ char *key = NULL;
-
-                        key = strjoin("systemd.tty.term.", skip_dev_prefix(tty_path));
-                        if (!key)
-                                return -ENOMEM;
-
-                        r = proc_cmdline_get_key(key, 0, &cmdline);
-                        if (r < 0)
-                                log_debug_errno(r, "Failed to read %s from kernel cmdline, ignoring: %m", key);
-                        else if (r > 0)
-                                term = cmdline;
-                }
-
-                if (!term)
-                        term = default_term_for_tty(tty_path);
-
-                x = strjoin("TERM=", term);
-                if (!x)
-                        return -ENOMEM;
-                our_env[n_env++] = x;
-        }
-
-        if (journal_stream_dev != 0 && journal_stream_ino != 0) {
-                if (asprintf(&x, "JOURNAL_STREAM=" DEV_FMT ":" INO_FMT, journal_stream_dev, journal_stream_ino) < 0)
-                        return -ENOMEM;
-
-                our_env[n_env++] = x;
-        }
-
-        if (c->log_namespace) {
-                x = strjoin("LOG_NAMESPACE=", c->log_namespace);
-                if (!x)
-                        return -ENOMEM;
-
-                our_env[n_env++] = x;
-        }
-
-        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
-                _cleanup_free_ char *joined = NULL;
-                const char *n;
-
-                if (!p->prefix[t])
-                        continue;
-
-                if (c->directories[t].n_items == 0)
-                        continue;
-
-                n = exec_directory_env_name_to_string(t);
-                if (!n)
-                        continue;
-
-                for (size_t i = 0; i < c->directories[t].n_items; i++) {
-                        _cleanup_free_ char *prefixed = NULL;
-
-                        prefixed = path_join(p->prefix[t], c->directories[t].items[i].path);
-                        if (!prefixed)
-                                return -ENOMEM;
-
-                        if (!strextend_with_separator(&joined, ":", prefixed))
-                                return -ENOMEM;
-                }
-
-                x = strjoin(n, "=", joined);
-                if (!x)
-                        return -ENOMEM;
-
-                our_env[n_env++] = x;
-        }
-
-        _cleanup_free_ char *creds_dir = NULL;
-        r = exec_context_get_credential_directory(c, p, u->id, &creds_dir);
-        if (r < 0)
-                return r;
-        if (r > 0) {
-                x = strjoin("CREDENTIALS_DIRECTORY=", creds_dir);
-                if (!x)
-                        return -ENOMEM;
-
-                our_env[n_env++] = x;
-        }
-
-        if (asprintf(&x, "SYSTEMD_EXEC_PID=" PID_FMT, getpid_cached()) < 0)
-                return -ENOMEM;
-
-        our_env[n_env++] = x;
-
-        if (memory_pressure_path) {
-                x = strjoin("MEMORY_PRESSURE_WATCH=", memory_pressure_path);
-                if (!x)
-                        return -ENOMEM;
-
-                our_env[n_env++] = x;
-
-                if (cgroup_context && !path_equal(memory_pressure_path, "/dev/null")) {
-                        _cleanup_free_ char *b = NULL, *e = NULL;
-
-                        if (asprintf(&b, "%s " USEC_FMT " " USEC_FMT,
-                                     MEMORY_PRESSURE_DEFAULT_TYPE,
-                                     cgroup_context->memory_pressure_threshold_usec == USEC_INFINITY ? MEMORY_PRESSURE_DEFAULT_THRESHOLD_USEC :
-                                     CLAMP(cgroup_context->memory_pressure_threshold_usec, 1U, MEMORY_PRESSURE_DEFAULT_WINDOW_USEC),
-                                     MEMORY_PRESSURE_DEFAULT_WINDOW_USEC) < 0)
-                                return -ENOMEM;
-
-                        if (base64mem(b, strlen(b) + 1, &e) < 0)
-                                return -ENOMEM;
-
-                        x = strjoin("MEMORY_PRESSURE_WRITE=", e);
-                        if (!x)
-                                return -ENOMEM;
-
-                        our_env[n_env++] = x;
-                }
-        }
-
-        assert(n_env < N_ENV_VARS + _EXEC_DIRECTORY_TYPE_MAX);
-#undef N_ENV_VARS
-
-        *ret = TAKE_PTR(our_env);
-
-        return 0;
-}
-
-static int build_pass_environment(const ExecContext *c, char ***ret) {
-        _cleanup_strv_free_ char **pass_env = NULL;
-        size_t n_env = 0;
-
-        STRV_FOREACH(i, c->pass_environment) {
-                _cleanup_free_ char *x = NULL;
-                char *v;
-
-                v = getenv(*i);
-                if (!v)
-                        continue;
-                x = strjoin(*i, "=", v);
-                if (!x)
-                        return -ENOMEM;
-
-                if (!GREEDY_REALLOC(pass_env, n_env + 2))
-                        return -ENOMEM;
-
-                pass_env[n_env++] = TAKE_PTR(x);
-                pass_env[n_env] = NULL;
-        }
-
-        *ret = TAKE_PTR(pass_env);
-
-        return 0;
-}
-
-bool exec_needs_network_namespace(const ExecContext *context) {
-        assert(context);
-
-        return context->private_network || context->network_namespace_path;
-}
-
-static bool exec_needs_ephemeral(const ExecContext *context) {
-        return (context->root_image || context->root_directory) && context->root_ephemeral;
-}
-
-static bool exec_needs_ipc_namespace(const ExecContext *context) {
-        assert(context);
-
-        return context->private_ipc || context->ipc_namespace_path;
-}
-
-bool exec_needs_mount_namespace(
-                const ExecContext *context,
-                const ExecParameters *params,
-                const ExecRuntime *runtime) {
-
-        assert(context);
-
-        if (context->root_image)
-                return true;
-
-        if (!strv_isempty(context->read_write_paths) ||
-            !strv_isempty(context->read_only_paths) ||
-            !strv_isempty(context->inaccessible_paths) ||
-            !strv_isempty(context->exec_paths) ||
-            !strv_isempty(context->no_exec_paths))
-                return true;
-
-        if (context->n_bind_mounts > 0)
-                return true;
-
-        if (context->n_temporary_filesystems > 0)
-                return true;
-
-        if (context->n_mount_images > 0)
-                return true;
-
-        if (context->n_extension_images > 0)
-                return true;
-
-        if (!strv_isempty(context->extension_directories))
-                return true;
-
-        if (!IN_SET(context->mount_propagation_flag, 0, MS_SHARED))
-                return true;
-
-        if (context->private_tmp && runtime && runtime->shared && (runtime->shared->tmp_dir || runtime->shared->var_tmp_dir))
-                return true;
-
-        if (context->private_devices ||
-            context->private_mounts > 0 ||
-            (context->private_mounts < 0 && exec_needs_network_namespace(context)) ||
-            context->protect_system != PROTECT_SYSTEM_NO ||
-            context->protect_home != PROTECT_HOME_NO ||
-            context->protect_kernel_tunables ||
-            context->protect_kernel_modules ||
-            context->protect_kernel_logs ||
-            context->protect_control_groups ||
-            context->protect_proc != PROTECT_PROC_DEFAULT ||
-            context->proc_subset != PROC_SUBSET_ALL ||
-            exec_needs_ipc_namespace(context))
-                return true;
-
-        if (context->root_directory) {
-                if (exec_context_get_effective_mount_apivfs(context))
-                        return true;
-
-                for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
-                        if (params && !params->prefix[t])
-                                continue;
-
-                        if (context->directories[t].n_items > 0)
-                                return true;
-                }
-        }
-
-        if (context->dynamic_user &&
-            (context->directories[EXEC_DIRECTORY_STATE].n_items > 0 ||
-             context->directories[EXEC_DIRECTORY_CACHE].n_items > 0 ||
-             context->directories[EXEC_DIRECTORY_LOGS].n_items > 0))
-                return true;
-
-        if (context->log_namespace)
-                return true;
-
-        return false;
-}
-
-static int setup_private_users(uid_t ouid, gid_t ogid, uid_t uid, gid_t gid) {
-        _cleanup_free_ char *uid_map = NULL, *gid_map = NULL;
-        _cleanup_close_pair_ int errno_pipe[2] = PIPE_EBADF;
-        _cleanup_close_ int unshare_ready_fd = -EBADF;
-        _cleanup_(sigkill_waitp) pid_t pid = 0;
-        uint64_t c = 1;
-        ssize_t n;
-        int r;
-
-        /* Set up a user namespace and map the original UID/GID (IDs from before any user or group changes, i.e.
-         * the IDs from the user or system manager(s)) to itself, the selected UID/GID to itself, and everything else to
-         * nobody. In order to be able to write this mapping we need CAP_SETUID in the original user namespace, which
-         * we however lack after opening the user namespace. To work around this we fork() a temporary child process,
-         * which waits for the parent to create the new user namespace while staying in the original namespace. The
-         * child then writes the UID mapping, under full privileges. The parent waits for the child to finish and
-         * continues execution normally.
-         * For unprivileged users (i.e. without capabilities), the root to root mapping is excluded. As such, it
-         * does not need CAP_SETUID to write the single line mapping to itself. */
-
-        /* Can only set up multiple mappings with CAP_SETUID. */
-        if (have_effective_cap(CAP_SETUID) > 0 && uid != ouid && uid_is_valid(uid))
-                r = asprintf(&uid_map,
-                             UID_FMT " " UID_FMT " 1\n"     /* Map $OUID → $OUID */
-                             UID_FMT " " UID_FMT " 1\n",    /* Map $UID → $UID */
-                             ouid, ouid, uid, uid);
-        else
-                r = asprintf(&uid_map,
-                             UID_FMT " " UID_FMT " 1\n",    /* Map $OUID → $OUID */
-                             ouid, ouid);
-
-        if (r < 0)
-                return -ENOMEM;
-
-        /* Can only set up multiple mappings with CAP_SETGID. */
-        if (have_effective_cap(CAP_SETGID) > 0 && gid != ogid && gid_is_valid(gid))
-                r = asprintf(&gid_map,
-                             GID_FMT " " GID_FMT " 1\n"     /* Map $OGID → $OGID */
-                             GID_FMT " " GID_FMT " 1\n",    /* Map $GID → $GID */
-                             ogid, ogid, gid, gid);
-        else
-                r = asprintf(&gid_map,
-                             GID_FMT " " GID_FMT " 1\n",    /* Map $OGID -> $OGID */
-                             ogid, ogid);
-
-        if (r < 0)
-                return -ENOMEM;
-
-        /* Create a communication channel so that the parent can tell the child when it finished creating the user
-         * namespace. */
-        unshare_ready_fd = eventfd(0, EFD_CLOEXEC);
-        if (unshare_ready_fd < 0)
-                return -errno;
-
-        /* Create a communication channel so that the child can tell the parent a proper error code in case it
-         * failed. */
-        if (pipe2(errno_pipe, O_CLOEXEC) < 0)
-                return -errno;
-
-        r = safe_fork("(sd-userns)", FORK_RESET_SIGNALS|FORK_DEATHSIG, &pid);
-        if (r < 0)
-                return r;
-        if (r == 0) {
-                _cleanup_close_ int fd = -EBADF;
-                const char *a;
-                pid_t ppid;
-
-                /* Child process, running in the original user namespace. Let's update the parent's UID/GID map from
-                 * here, after the parent opened its own user namespace. */
-
-                ppid = getppid();
-                errno_pipe[0] = safe_close(errno_pipe[0]);
-
-                /* Wait until the parent unshared the user namespace */
-                if (read(unshare_ready_fd, &c, sizeof(c)) < 0) {
-                        r = -errno;
-                        goto child_fail;
-                }
-
-                /* Disable the setgroups() system call in the child user namespace, for good. */
-                a = procfs_file_alloca(ppid, "setgroups");
-                fd = open(a, O_WRONLY|O_CLOEXEC);
-                if (fd < 0) {
-                        if (errno != ENOENT) {
-                                r = -errno;
-                                goto child_fail;
-                        }
-
-                        /* If the file is missing the kernel is too old, let's continue anyway. */
-                } else {
-                        if (write(fd, "deny\n", 5) < 0) {
-                                r = -errno;
-                                goto child_fail;
-                        }
-
-                        fd = safe_close(fd);
-                }
-
-                /* First write the GID map */
-                a = procfs_file_alloca(ppid, "gid_map");
-                fd = open(a, O_WRONLY|O_CLOEXEC);
-                if (fd < 0) {
-                        r = -errno;
-                        goto child_fail;
-                }
-                if (write(fd, gid_map, strlen(gid_map)) < 0) {
-                        r = -errno;
-                        goto child_fail;
-                }
-                fd = safe_close(fd);
-
-                /* The write the UID map */
-                a = procfs_file_alloca(ppid, "uid_map");
-                fd = open(a, O_WRONLY|O_CLOEXEC);
-                if (fd < 0) {
-                        r = -errno;
-                        goto child_fail;
-                }
-                if (write(fd, uid_map, strlen(uid_map)) < 0) {
-                        r = -errno;
-                        goto child_fail;
-                }
-
-                _exit(EXIT_SUCCESS);
-
-        child_fail:
-                (void) write(errno_pipe[1], &r, sizeof(r));
-                _exit(EXIT_FAILURE);
-        }
-
-        errno_pipe[1] = safe_close(errno_pipe[1]);
-
-        if (unshare(CLONE_NEWUSER) < 0)
-                return -errno;
-
-        /* Let the child know that the namespace is ready now */
-        if (write(unshare_ready_fd, &c, sizeof(c)) < 0)
-                return -errno;
-
-        /* Try to read an error code from the child */
-        n = read(errno_pipe[0], &r, sizeof(r));
-        if (n < 0)
-                return -errno;
-        if (n == sizeof(r)) { /* an error code was sent to us */
-                if (r < 0)
-                        return r;
-                return -EIO;
-        }
-        if (n != 0) /* on success we should have read 0 bytes */
-                return -EIO;
-
-        r = wait_for_terminate_and_check("(sd-userns)", TAKE_PID(pid), 0);
-        if (r < 0)
-                return r;
-        if (r != EXIT_SUCCESS) /* If something strange happened with the child, let's consider this fatal, too */
-                return -EIO;
-
-        return 0;
-}
-
-static bool exec_directory_is_private(const ExecContext *context, ExecDirectoryType type) {
-        assert(context);
-
-        if (!context->dynamic_user)
-                return false;
-
-        if (type == EXEC_DIRECTORY_CONFIGURATION)
-                return false;
-
-        if (type == EXEC_DIRECTORY_RUNTIME && context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO)
-                return false;
-
-        return true;
-}
-
-static int create_many_symlinks(const char *root, const char *source, char **symlinks) {
-        _cleanup_free_ char *src_abs = NULL;
-        int r;
-
-        assert(source);
-
-        src_abs = path_join(root, source);
-        if (!src_abs)
-                return -ENOMEM;
-
-        STRV_FOREACH(dst, symlinks) {
-                _cleanup_free_ char *dst_abs = NULL;
-
-                dst_abs = path_join(root, *dst);
-                if (!dst_abs)
-                        return -ENOMEM;
-
-                r = mkdir_parents_label(dst_abs, 0755);
-                if (r < 0)
-                        return r;
-
-                r = symlink_idempotent(src_abs, dst_abs, true);
-                if (r < 0)
-                        return r;
-        }
-
-        return 0;
-}
-
-static int setup_exec_directory(
-                Unit *u,
-                const ExecContext *context,
-                const ExecParameters *params,
-                uid_t uid,
-                gid_t gid,
-                ExecDirectoryType type,
-                bool needs_mount_namespace,
-                int *exit_status) {
-
-        static const int exit_status_table[_EXEC_DIRECTORY_TYPE_MAX] = {
-                [EXEC_DIRECTORY_RUNTIME] = EXIT_RUNTIME_DIRECTORY,
-                [EXEC_DIRECTORY_STATE] = EXIT_STATE_DIRECTORY,
-                [EXEC_DIRECTORY_CACHE] = EXIT_CACHE_DIRECTORY,
-                [EXEC_DIRECTORY_LOGS] = EXIT_LOGS_DIRECTORY,
-                [EXEC_DIRECTORY_CONFIGURATION] = EXIT_CONFIGURATION_DIRECTORY,
-        };
-        int r;
-
-        assert(context);
-        assert(params);
-        assert(type >= 0 && type < _EXEC_DIRECTORY_TYPE_MAX);
-        assert(exit_status);
-
-        if (!params->prefix[type])
-                return 0;
-
-        if (params->flags & EXEC_CHOWN_DIRECTORIES) {
-                if (!uid_is_valid(uid))
-                        uid = 0;
-                if (!gid_is_valid(gid))
-                        gid = 0;
-        }
-
-        for (size_t i = 0; i < context->directories[type].n_items; i++) {
-                _cleanup_free_ char *p = NULL, *pp = NULL;
-
-                p = path_join(params->prefix[type], context->directories[type].items[i].path);
-                if (!p) {
-                        r = -ENOMEM;
-                        goto fail;
-                }
-
-                r = mkdir_parents_label(p, 0755);
-                if (r < 0)
-                        goto fail;
-
-                if (IN_SET(type, EXEC_DIRECTORY_STATE, EXEC_DIRECTORY_LOGS) && params->runtime_scope == RUNTIME_SCOPE_USER) {
-
-                        /* If we are in user mode, and a configuration directory exists but a state directory
-                         * doesn't exist, then we likely are upgrading from an older systemd version that
-                         * didn't know the more recent addition to the xdg-basedir spec: the $XDG_STATE_HOME
-                         * directory. In older systemd versions EXEC_DIRECTORY_STATE was aliased to
-                         * EXEC_DIRECTORY_CONFIGURATION, with the advent of $XDG_STATE_HOME is is now
-                         * separated. If a service has both dirs configured but only the configuration dir
-                         * exists and the state dir does not, we assume we are looking at an update
-                         * situation. Hence, create a compatibility symlink, so that all expectations are
-                         * met.
-                         *
-                         * (We also do something similar with the log directory, which still doesn't exist in
-                         * the xdg basedir spec. We'll make it a subdir of the state dir.) */
-
-                        /* this assumes the state dir is always created before the configuration dir */
-                        assert_cc(EXEC_DIRECTORY_STATE < EXEC_DIRECTORY_LOGS);
-                        assert_cc(EXEC_DIRECTORY_LOGS < EXEC_DIRECTORY_CONFIGURATION);
-
-                        r = laccess(p, F_OK);
-                        if (r == -ENOENT) {
-                                _cleanup_free_ char *q = NULL;
-
-                                /* OK, we know that the state dir does not exist. Let's see if the dir exists
-                                 * under the configuration hierarchy. */
-
-                                if (type == EXEC_DIRECTORY_STATE)
-                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], context->directories[type].items[i].path);
-                                else if (type == EXEC_DIRECTORY_LOGS)
-                                        q = path_join(params->prefix[EXEC_DIRECTORY_CONFIGURATION], "log", context->directories[type].items[i].path);
-                                else
-                                        assert_not_reached();
-                                if (!q) {
-                                        r = -ENOMEM;
-                                        goto fail;
-                                }
-
-                                r = laccess(q, F_OK);
-                                if (r >= 0) {
-                                        /* It does exist! This hence looks like an update. Symlink the
-                                         * configuration directory into the state directory. */
-
-                                        r = symlink_idempotent(q, p, /* make_relative= */ true);
-                                        if (r < 0)
-                                                goto fail;
-
-                                        log_unit_notice(u, "Unit state directory %s missing but matching configuration directory %s exists, assuming update from systemd 253 or older, creating compatibility symlink.", p, q);
-                                        continue;
-                                } else if (r != -ENOENT)
-                                        log_unit_warning_errno(u, r, "Unable to detect whether unit configuration directory '%s' exists, assuming not: %m", q);
-
-                        } else if (r < 0)
-                                log_unit_warning_errno(u, r, "Unable to detect whether unit state directory '%s' is missing, assuming it is: %m", p);
-                }
-
-                if (exec_directory_is_private(context, type)) {
-                        /* So, here's one extra complication when dealing with DynamicUser=1 units. In that
-                         * case we want to avoid leaving a directory around fully accessible that is owned by
-                         * a dynamic user whose UID is later on reused. To lock this down we use the same
-                         * trick used by container managers to prohibit host users to get access to files of
-                         * the same UID in containers: we place everything inside a directory that has an
-                         * access mode of 0700 and is owned root:root, so that it acts as security boundary
-                         * for unprivileged host code. We then use fs namespacing to make this directory
-                         * permeable for the service itself.
-                         *
-                         * Specifically: for a service which wants a special directory "foo/" we first create
-                         * a directory "private/" with access mode 0700 owned by root:root. Then we place
-                         * "foo" inside of that directory (i.e. "private/foo/"), and make "foo" a symlink to
-                         * "private/foo". This way, privileged host users can access "foo/" as usual, but
-                         * unprivileged host users can't look into it. Inside of the namespace of the unit
-                         * "private/" is replaced by a more liberally accessible tmpfs, into which the host's
-                         * "private/foo/" is mounted under the same name, thus disabling the access boundary
-                         * for the service and making sure it only gets access to the dirs it needs but no
-                         * others. Tricky? Yes, absolutely, but it works!
-                         *
-                         * Note that we don't do this for EXEC_DIRECTORY_CONFIGURATION as that's assumed not
-                         * to be owned by the service itself.
-                         *
-                         * Also, note that we don't do this for EXEC_DIRECTORY_RUNTIME as that's often used
-                         * for sharing files or sockets with other services. */
-
-                        pp = path_join(params->prefix[type], "private");
-                        if (!pp) {
-                                r = -ENOMEM;
-                                goto fail;
-                        }
-
-                        /* First set up private root if it doesn't exist yet, with access mode 0700 and owned by root:root */
-                        r = mkdir_safe_label(pp, 0700, 0, 0, MKDIR_WARN_MODE);
-                        if (r < 0)
-                                goto fail;
-
-                        if (!path_extend(&pp, context->directories[type].items[i].path)) {
-                                r = -ENOMEM;
-                                goto fail;
-                        }
-
-                        /* Create all directories between the configured directory and this private root, and mark them 0755 */
-                        r = mkdir_parents_label(pp, 0755);
-                        if (r < 0)
-                                goto fail;
-
-                        if (is_dir(p, false) > 0 &&
-                            (laccess(pp, F_OK) == -ENOENT)) {
-
-                                /* Hmm, the private directory doesn't exist yet, but the normal one exists? If so, move
-                                 * it over. Most likely the service has been upgraded from one that didn't use
-                                 * DynamicUser=1, to one that does. */
-
-                                log_unit_info(u, "Found pre-existing public %s= directory %s, migrating to %s.\n"
-                                              "Apparently, service previously had DynamicUser= turned off, and has now turned it on.",
-                                              exec_directory_type_to_string(type), p, pp);
-
-                                r = RET_NERRNO(rename(p, pp));
-                                if (r < 0)
-                                        goto fail;
-                        } else {
-                                /* Otherwise, create the actual directory for the service */
-
-                                r = mkdir_label(pp, context->directories[type].mode);
-                                if (r < 0 && r != -EEXIST)
-                                        goto fail;
-                        }
-
-                        if (!context->directories[type].items[i].only_create) {
-                                /* And link it up from the original place.
-                                 * Notes
-                                 * 1) If a mount namespace is going to be used, then this symlink remains on
-                                 *    the host, and a new one for the child namespace will be created later.
-                                 * 2) It is not necessary to create this symlink when one of its parent
-                                 *    directories is specified and already created. E.g.
-                                 *        StateDirectory=foo foo/bar
-                                 *    In that case, the inode points to pp and p for "foo/bar" are the same:
-                                 *        pp = "/var/lib/private/foo/bar"
-                                 *        p = "/var/lib/foo/bar"
-                                 *    and, /var/lib/foo is a symlink to /var/lib/private/foo. So, not only
-                                 *    we do not need to create the symlink, but we cannot create the symlink.
-                                 *    See issue #24783. */
-                                r = symlink_idempotent(pp, p, true);
-                                if (r < 0)
-                                        goto fail;
-                        }
-
-                } else {
-                        _cleanup_free_ char *target = NULL;
-
-                        if (type != EXEC_DIRECTORY_CONFIGURATION &&
-                            readlink_and_make_absolute(p, &target) >= 0) {
-                                _cleanup_free_ char *q = NULL, *q_resolved = NULL, *target_resolved = NULL;
-
-                                /* This already exists and is a symlink? Interesting. Maybe it's one created
-                                 * by DynamicUser=1 (see above)?
-                                 *
-                                 * We do this for all directory types except for ConfigurationDirectory=,
-                                 * since they all support the private/ symlink logic at least in some
-                                 * configurations, see above. */
-
-                                r = chase(target, NULL, 0, &target_resolved, NULL);
-                                if (r < 0)
-                                        goto fail;
-
-                                q = path_join(params->prefix[type], "private", context->directories[type].items[i].path);
-                                if (!q) {
-                                        r = -ENOMEM;
-                                        goto fail;
-                                }
-
-                                /* /var/lib or friends may be symlinks. So, let's chase them also. */
-                                r = chase(q, NULL, CHASE_NONEXISTENT, &q_resolved, NULL);
-                                if (r < 0)
-                                        goto fail;
-
-                                if (path_equal(q_resolved, target_resolved)) {
-
-                                        /* Hmm, apparently DynamicUser= was once turned on for this service,
-                                         * but is no longer. Let's move the directory back up. */
-
-                                        log_unit_info(u, "Found pre-existing private %s= directory %s, migrating to %s.\n"
-                                                      "Apparently, service previously had DynamicUser= turned on, and has now turned it off.",
-                                                      exec_directory_type_to_string(type), q, p);
-
-                                        r = RET_NERRNO(unlink(p));
-                                        if (r < 0)
-                                                goto fail;
-
-                                        r = RET_NERRNO(rename(q, p));
-                                        if (r < 0)
-                                                goto fail;
-                                }
-                        }
-
-                        r = mkdir_label(p, context->directories[type].mode);
-                        if (r < 0) {
-                                if (r != -EEXIST)
-                                        goto fail;
-
-                                if (type == EXEC_DIRECTORY_CONFIGURATION) {
-                                        struct stat st;
-
-                                        /* Don't change the owner/access mode of the configuration directory,
-                                         * as in the common case it is not written to by a service, and shall
-                                         * not be writable. */
-
-                                        r = RET_NERRNO(stat(p, &st));
-                                        if (r < 0)
-                                                goto fail;
-
-                                        /* Still complain if the access mode doesn't match */
-                                        if (((st.st_mode ^ context->directories[type].mode) & 07777) != 0)
-                                                log_unit_warning(u, "%s \'%s\' already exists but the mode is different. "
-                                                                 "(File system: %o %sMode: %o)",
-                                                                 exec_directory_type_to_string(type), context->directories[type].items[i].path,
-                                                                 st.st_mode & 07777, exec_directory_type_to_string(type), context->directories[type].mode & 07777);
-
-                                        continue;
-                                }
-                        }
-                }
-
-                /* Lock down the access mode (we use chmod_and_chown() to make this idempotent. We don't
-                 * specify UID/GID here, so that path_chown_recursive() can optimize things depending on the
-                 * current UID/GID ownership.) */
-                r = chmod_and_chown(pp ?: p, context->directories[type].mode, UID_INVALID, GID_INVALID);
-                if (r < 0)
-                        goto fail;
-
-                /* Skip the rest (which deals with ownership) in user mode, since ownership changes are not
-                 * available to user code anyway */
-                if (params->runtime_scope != RUNTIME_SCOPE_SYSTEM)
-                        continue;
-
-                /* Then, change the ownership of the whole tree, if necessary. When dynamic users are used we
-                 * drop the suid/sgid bits, since we really don't want SUID/SGID files for dynamic UID/GID
-                 * assignments to exist. */
-                r = path_chown_recursive(pp ?: p, uid, gid, context->dynamic_user ? 01777 : 07777, AT_SYMLINK_FOLLOW);
-                if (r < 0)
-                        goto fail;
-        }
-
-        /* If we are not going to run in a namespace, set up the symlinks - otherwise
-         * they are set up later, to allow configuring empty var/run/etc. */
-        if (!needs_mount_namespace)
-                for (size_t i = 0; i < context->directories[type].n_items; i++) {
-                        r = create_many_symlinks(params->prefix[type],
-                                                 context->directories[type].items[i].path,
-                                                 context->directories[type].items[i].symlinks);
-                        if (r < 0)
-                                goto fail;
-                }
-
-        return 0;
-
-fail:
-        *exit_status = exit_status_table[type];
-        return r;
-}
-
-#if ENABLE_SMACK
-static int setup_smack(
-                const Manager *manager,
-                const ExecContext *context,
-                int executable_fd) {
-        int r;
-
-        assert(context);
-        assert(executable_fd >= 0);
-
-        if (context->smack_process_label) {
-                r = mac_smack_apply_pid(0, context->smack_process_label);
-                if (r < 0)
-                        return r;
-        } else if (manager->defaults.smack_process_label) {
-                _cleanup_free_ char *exec_label = NULL;
-
-                r = mac_smack_read_fd(executable_fd, SMACK_ATTR_EXEC, &exec_label);
-                if (r < 0 && !ERRNO_IS_XATTR_ABSENT(r))
-                        return r;
-
-                r = mac_smack_apply_pid(0, exec_label ?: manager->defaults.smack_process_label);
-                if (r < 0)
-                        return r;
-        }
-
-        return 0;
-}
-#endif
-
-static int compile_bind_mounts(
-                const ExecContext *context,
-                const ExecParameters *params,
-                BindMount **ret_bind_mounts,
-                size_t *ret_n_bind_mounts,
-                char ***ret_empty_directories) {
-
-        _cleanup_strv_free_ char **empty_directories = NULL;
-        BindMount *bind_mounts = NULL;
-        size_t n, h = 0;
-        int r;
-
-        assert(context);
-        assert(params);
-        assert(ret_bind_mounts);
-        assert(ret_n_bind_mounts);
-        assert(ret_empty_directories);
-
-        CLEANUP_ARRAY(bind_mounts, h, bind_mount_free_many);
-
-        n = context->n_bind_mounts;
-        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
-                if (!params->prefix[t])
-                        continue;
-
-                for (size_t i = 0; i < context->directories[t].n_items; i++)
-                        n += !context->directories[t].items[i].only_create;
-        }
-
-        if (n <= 0) {
-                *ret_bind_mounts = NULL;
-                *ret_n_bind_mounts = 0;
-                *ret_empty_directories = NULL;
-                return 0;
-        }
-
-        bind_mounts = new(BindMount, n);
-        if (!bind_mounts)
-                return -ENOMEM;
-
-        for (size_t i = 0; i < context->n_bind_mounts; i++) {
-                BindMount *item = context->bind_mounts + i;
-                _cleanup_free_ char *s = NULL, *d = NULL;
-
-                s = strdup(item->source);
-                if (!s)
-                        return -ENOMEM;
-
-                d = strdup(item->destination);
-                if (!d)
-                        return -ENOMEM;
-
-                bind_mounts[h++] = (BindMount) {
-                        .source = TAKE_PTR(s),
-                        .destination = TAKE_PTR(d),
-                        .read_only = item->read_only,
-                        .recursive = item->recursive,
-                        .ignore_enoent = item->ignore_enoent,
-                };
-        }
-
-        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
-                if (!params->prefix[t])
-                        continue;
-
-                if (context->directories[t].n_items == 0)
-                        continue;
-
-                if (exec_directory_is_private(context, t) &&
-                    !exec_context_with_rootfs(context)) {
-                        char *private_root;
-
-                        /* So this is for a dynamic user, and we need to make sure the process can access its own
-                         * directory. For that we overmount the usually inaccessible "private" subdirectory with a
-                         * tmpfs that makes it accessible and is empty except for the submounts we do this for. */
-
-                        private_root = path_join(params->prefix[t], "private");
-                        if (!private_root)
-                                return -ENOMEM;
-
-                        r = strv_consume(&empty_directories, private_root);
-                        if (r < 0)
-                                return r;
-                }
-
-                for (size_t i = 0; i < context->directories[t].n_items; i++) {
-                        _cleanup_free_ char *s = NULL, *d = NULL;
-
-                        /* When one of the parent directories is in the list, we cannot create the symlink
-                         * for the child directory. See also the comments in setup_exec_directory(). */
-                        if (context->directories[t].items[i].only_create)
-                                continue;
-
-                        if (exec_directory_is_private(context, t))
-                                s = path_join(params->prefix[t], "private", context->directories[t].items[i].path);
-                        else
-                                s = path_join(params->prefix[t], context->directories[t].items[i].path);
-                        if (!s)
-                                return -ENOMEM;
-
-                        if (exec_directory_is_private(context, t) &&
-                            exec_context_with_rootfs(context))
-                                /* When RootDirectory= or RootImage= are set, then the symbolic link to the private
-                                 * directory is not created on the root directory. So, let's bind-mount the directory
-                                 * on the 'non-private' place. */
-                                d = path_join(params->prefix[t], context->directories[t].items[i].path);
-                        else
-                                d = strdup(s);
-                        if (!d)
-                                return -ENOMEM;
-
-                        bind_mounts[h++] = (BindMount) {
-                                .source = TAKE_PTR(s),
-                                .destination = TAKE_PTR(d),
-                                .read_only = false,
-                                .nosuid = context->dynamic_user, /* don't allow suid/sgid when DynamicUser= is on */
-                                .recursive = true,
-                                .ignore_enoent = false,
-                        };
-                }
-        }
-
-        assert(h == n);
-
-        *ret_bind_mounts = TAKE_PTR(bind_mounts);
-        *ret_n_bind_mounts = n;
-        *ret_empty_directories = TAKE_PTR(empty_directories);
-
-        return (int) n;
-}
-
-/* ret_symlinks will contain a list of pairs src:dest that describes
- * the symlinks to create later on. For example, the symlinks needed
- * to safely give private directories to DynamicUser=1 users. */
-static int compile_symlinks(
-                const ExecContext *context,
-                const ExecParameters *params,
-                bool setup_os_release_symlink,
-                char ***ret_symlinks) {
-
-        _cleanup_strv_free_ char **symlinks = NULL;
-        int r;
-
-        assert(context);
-        assert(params);
-        assert(ret_symlinks);
-
-        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
-                for (size_t i = 0; i < context->directories[dt].n_items; i++) {
-                        _cleanup_free_ char *private_path = NULL, *path = NULL;
-
-                        STRV_FOREACH(symlink, context->directories[dt].items[i].symlinks) {
-                                _cleanup_free_ char *src_abs = NULL, *dst_abs = NULL;
-
-                                src_abs = path_join(params->prefix[dt], context->directories[dt].items[i].path);
-                                dst_abs = path_join(params->prefix[dt], *symlink);
-                                if (!src_abs || !dst_abs)
-                                        return -ENOMEM;
-
-                                r = strv_consume_pair(&symlinks, TAKE_PTR(src_abs), TAKE_PTR(dst_abs));
-                                if (r < 0)
-                                        return r;
-                        }
-
-                        if (!exec_directory_is_private(context, dt) ||
-                            exec_context_with_rootfs(context) ||
-                            context->directories[dt].items[i].only_create)
-                                continue;
-
-                        private_path = path_join(params->prefix[dt], "private", context->directories[dt].items[i].path);
-                        if (!private_path)
-                                return -ENOMEM;
-
-                        path = path_join(params->prefix[dt], context->directories[dt].items[i].path);
-                        if (!path)
-                                return -ENOMEM;
-
-                        r = strv_consume_pair(&symlinks, TAKE_PTR(private_path), TAKE_PTR(path));
-                        if (r < 0)
-                                return r;
-                }
-        }
-
-        /* We make the host's os-release available via a symlink, so that we can copy it atomically
-         * and readers will never get a half-written version. Note that, while the paths specified here are
-         * absolute, when they are processed in namespace.c they will be made relative automatically, i.e.:
-         * 'os-release -> .os-release-stage/os-release' is what will be created. */
-        if (setup_os_release_symlink) {
-                r = strv_extend(&symlinks, "/run/host/.os-release-stage/os-release");
-                if (r < 0)
-                        return r;
-
-                r = strv_extend(&symlinks, "/run/host/os-release");
-                if (r < 0)
-                        return r;
-        }
-
-        *ret_symlinks = TAKE_PTR(symlinks);
-
-        return 0;
-}
-
-static bool insist_on_sandboxing(
-                const ExecContext *context,
-                const char *root_dir,
-                const char *root_image,
-                const BindMount *bind_mounts,
-                size_t n_bind_mounts) {
-
-        assert(context);
-        assert(n_bind_mounts == 0 || bind_mounts);
-
-        /* Checks whether we need to insist on fs namespacing. i.e. whether we have settings configured that
-         * would alter the view on the file system beyond making things read-only or invisible, i.e. would
-         * rearrange stuff in a way we cannot ignore gracefully. */
-
-        if (context->n_temporary_filesystems > 0)
-                return true;
-
-        if (root_dir || root_image)
-                return true;
-
-        if (context->n_mount_images > 0)
-                return true;
-
-        if (context->dynamic_user)
-                return true;
-
-        if (context->n_extension_images > 0 || !strv_isempty(context->extension_directories))
-                return true;
-
-        /* If there are any bind mounts set that don't map back onto themselves, fs namespacing becomes
-         * essential. */
-        for (size_t i = 0; i < n_bind_mounts; i++)
-                if (!path_equal(bind_mounts[i].source, bind_mounts[i].destination))
-                        return true;
-
-        if (context->log_namespace)
-                return true;
-
-        return false;
-}
-
-static int setup_ephemeral(const ExecContext *context, ExecRuntime *runtime) {
-        _cleanup_close_ int fd = -EBADF;
-        int r;
-
-        if (!runtime || !runtime->ephemeral_copy)
-                return 0;
-
-        r = posix_lock(runtime->ephemeral_storage_socket[0], LOCK_EX);
-        if (r < 0)
-                return log_debug_errno(r, "Failed to lock ephemeral storage socket: %m");
-
-        CLEANUP_POSIX_UNLOCK(runtime->ephemeral_storage_socket[0]);
-
-        fd = receive_one_fd(runtime->ephemeral_storage_socket[0], MSG_PEEK|MSG_DONTWAIT);
-        if (fd >= 0)
-                /* We got an fd! That means ephemeral has already been set up, so nothing to do here. */
-                return 0;
-
-        if (fd != -EAGAIN)
-                return log_debug_errno(fd, "Failed to receive file descriptor queued on ephemeral storage socket: %m");
-
-        log_debug("Making ephemeral snapshot of %s to %s",
-                  context->root_image ?: context->root_directory, runtime->ephemeral_copy);
-
-        if (context->root_image)
-                fd = copy_file(context->root_image, runtime->ephemeral_copy, O_EXCL, 0600,
-                               COPY_LOCK_BSD|COPY_REFLINK|COPY_CRTIME);
-        else
-                fd = btrfs_subvol_snapshot_at(AT_FDCWD, context->root_directory,
-                                              AT_FDCWD, runtime->ephemeral_copy,
-                                              BTRFS_SNAPSHOT_FALLBACK_COPY |
-                                              BTRFS_SNAPSHOT_FALLBACK_DIRECTORY |
-                                              BTRFS_SNAPSHOT_RECURSIVE |
-                                              BTRFS_SNAPSHOT_LOCK_BSD);
-        if (fd < 0)
-                return log_debug_errno(fd, "Failed to snapshot %s to %s: %m",
-                                       context->root_image ?: context->root_directory, runtime->ephemeral_copy);
-
-        if (context->root_image) {
-                /* A root image might be subject to lots of random writes so let's try to disable COW on it
-                 * which tends to not perform well in combination with lots of random writes.
-                 *
-                 * Note: btrfs actually isn't impressed by us setting the flag after making the reflink'ed
-                 * copy, but we at least want to make the intention clear.
-                 */
-                r = chattr_fd(fd, FS_NOCOW_FL, FS_NOCOW_FL, NULL);
-                if (r < 0)
-                        log_debug_errno(fd, "Failed to disable copy-on-write for %s, ignoring: %m", runtime->ephemeral_copy);
-        }
-
-        r = send_one_fd(runtime->ephemeral_storage_socket[1], fd, MSG_DONTWAIT);
-        if (r < 0)
-                return log_debug_errno(r, "Failed to queue file descriptor on ephemeral storage socket: %m");
-
-        return 1;
-}
-
-static int verity_settings_prepare(
-                VeritySettings *verity,
-                const char *root_image,
-                const void *root_hash,
-                size_t root_hash_size,
-                const char *root_hash_path,
-                const void *root_hash_sig,
-                size_t root_hash_sig_size,
-                const char *root_hash_sig_path,
-                const char *verity_data_path) {
-
-        int r;
-
-        assert(verity);
-
-        if (root_hash) {
-                void *d;
-
-                d = memdup(root_hash, root_hash_size);
-                if (!d)
-                        return -ENOMEM;
-
-                free_and_replace(verity->root_hash, d);
-                verity->root_hash_size = root_hash_size;
-                verity->designator = PARTITION_ROOT;
-        }
-
-        if (root_hash_sig) {
-                void *d;
-
-                d = memdup(root_hash_sig, root_hash_sig_size);
-                if (!d)
-                        return -ENOMEM;
-
-                free_and_replace(verity->root_hash_sig, d);
-                verity->root_hash_sig_size = root_hash_sig_size;
-                verity->designator = PARTITION_ROOT;
-        }
-
-        if (verity_data_path) {
-                r = free_and_strdup(&verity->data_path, verity_data_path);
-                if (r < 0)
-                        return r;
-        }
-
-        r = verity_settings_load(
-                        verity,
-                        root_image,
-                        root_hash_path,
-                        root_hash_sig_path);
-        if (r < 0)
-                return log_debug_errno(r, "Failed to load root hash: %m");
-
-        return 0;
-}
-
-static int apply_mount_namespace(
-                const Unit *u,
-                ExecCommandFlags command_flags,
-                const ExecContext *context,
-                const ExecParameters *params,
-                ExecRuntime *runtime,
-                const char *memory_pressure_path,
-                char **error_path) {
-
-        _cleanup_(verity_settings_done) VeritySettings verity = VERITY_SETTINGS_DEFAULT;
-        _cleanup_strv_free_ char **empty_directories = NULL, **symlinks = NULL,
-                        **read_write_paths_cleanup = NULL;
-        _cleanup_free_ char *creds_path = NULL, *incoming_dir = NULL, *propagate_dir = NULL,
-                        *extension_dir = NULL, *host_os_release_stage = NULL;
-        const char *root_dir = NULL, *root_image = NULL, *tmp_dir = NULL, *var_tmp_dir = NULL;
-        char **read_write_paths;
-        bool needs_sandboxing, setup_os_release_symlink;
-        BindMount *bind_mounts = NULL;
-        size_t n_bind_mounts = 0;
-        int r;
-
-        assert(context);
-
-        CLEANUP_ARRAY(bind_mounts, n_bind_mounts, bind_mount_free_many);
-
-        if (params->flags & EXEC_APPLY_CHROOT) {
-                r = setup_ephemeral(context, runtime);
-                if (r < 0)
-                        return r;
-
-                if (context->root_image)
-                        root_image = (runtime ? runtime->ephemeral_copy : NULL) ?: context->root_image;
-                else
-                        root_dir = (runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory;
-        }
-
-        r = compile_bind_mounts(context, params, &bind_mounts, &n_bind_mounts, &empty_directories);
-        if (r < 0)
-                return r;
-
-        /* We need to make the pressure path writable even if /sys/fs/cgroups is made read-only, as the
-         * service will need to write to it in order to start the notifications. */
-        if (context->protect_control_groups && memory_pressure_path && !streq(memory_pressure_path, "/dev/null")) {
-                read_write_paths_cleanup = strv_copy(context->read_write_paths);
-                if (!read_write_paths_cleanup)
-                        return -ENOMEM;
-
-                r = strv_extend(&read_write_paths_cleanup, memory_pressure_path);
-                if (r < 0)
-                        return r;
-
-                read_write_paths = read_write_paths_cleanup;
-        } else
-                read_write_paths = context->read_write_paths;
-
-        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command_flags & EXEC_COMMAND_FULLY_PRIVILEGED);
-        if (needs_sandboxing) {
-                /* The runtime struct only contains the parent of the private /tmp, which is non-accessible
-                 * to world users. Inside of it there's a /tmp that is sticky, and that's the one we want to
-                 * use here.  This does not apply when we are using /run/systemd/empty as fallback. */
-
-                if (context->private_tmp && runtime && runtime->shared) {
-                        if (streq_ptr(runtime->shared->tmp_dir, RUN_SYSTEMD_EMPTY))
-                                tmp_dir = runtime->shared->tmp_dir;
-                        else if (runtime->shared->tmp_dir)
-                                tmp_dir = strjoina(runtime->shared->tmp_dir, "/tmp");
-
-                        if (streq_ptr(runtime->shared->var_tmp_dir, RUN_SYSTEMD_EMPTY))
-                                var_tmp_dir = runtime->shared->var_tmp_dir;
-                        else if (runtime->shared->var_tmp_dir)
-                                var_tmp_dir = strjoina(runtime->shared->var_tmp_dir, "/tmp");
-                }
-        }
-
-        /* Symlinks (exec dirs, os-release) are set up after other mounts, before they are made read-only. */
-        setup_os_release_symlink = needs_sandboxing && exec_context_get_effective_mount_apivfs(context) && (root_dir || root_image);
-        r = compile_symlinks(context, params, setup_os_release_symlink, &symlinks);
-        if (r < 0)
-                return r;
-
-        if (context->mount_propagation_flag == MS_SHARED)
-                log_unit_debug(u, "shared mount propagation hidden by other fs namespacing unit settings: ignoring");
-
-        if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
-                r = exec_context_get_credential_directory(context, params, u->id, &creds_path);
-                if (r < 0)
-                        return r;
-        }
-
-        if (params->runtime_scope == RUNTIME_SCOPE_SYSTEM) {
-                propagate_dir = path_join("/run/systemd/propagate/", u->id);
-                if (!propagate_dir)
-                        return -ENOMEM;
-
-                incoming_dir = strdup("/run/systemd/incoming");
-                if (!incoming_dir)
-                        return -ENOMEM;
-
-                extension_dir = strdup("/run/systemd/unit-extensions");
-                if (!extension_dir)
-                        return -ENOMEM;
-
-                /* If running under a different root filesystem, propagate the host's os-release. We make a
-                 * copy rather than just bind mounting it, so that it can be updated on soft-reboot. */
-                if (setup_os_release_symlink) {
-                        host_os_release_stage = strdup("/run/systemd/propagate/.os-release-stage");
-                        if (!host_os_release_stage)
-                                return -ENOMEM;
-                }
-        } else {
-                assert(params->runtime_scope == RUNTIME_SCOPE_USER);
-
-                if (asprintf(&extension_dir, "/run/user/" UID_FMT "/systemd/unit-extensions", geteuid()) < 0)
-                        return -ENOMEM;
-
-                if (setup_os_release_symlink) {
-                        if (asprintf(&host_os_release_stage,
-                                     "/run/user/" UID_FMT "/systemd/propagate/.os-release-stage",
-                                     geteuid()) < 0)
-                                return -ENOMEM;
-                }
-        }
-
-        if (root_image) {
-                r = verity_settings_prepare(
-                        &verity,
-                        root_image,
-                        context->root_hash, context->root_hash_size, context->root_hash_path,
-                        context->root_hash_sig, context->root_hash_sig_size, context->root_hash_sig_path,
-                        context->root_verity);
-                if (r < 0)
-                        return r;
-        }
-
-        NamespaceParameters parameters = {
-                .runtime_scope = params->runtime_scope,
-
-                .root_directory = root_dir,
-                .root_image = root_image,
-                .root_image_options = context->root_image_options,
-                .root_image_policy = context->root_image_policy ?: &image_policy_service,
-
-                .read_write_paths = read_write_paths,
-                .read_only_paths = needs_sandboxing ? context->read_only_paths : NULL,
-                .inaccessible_paths = needs_sandboxing ? context->inaccessible_paths : NULL,
-
-                .exec_paths = needs_sandboxing ? context->exec_paths : NULL,
-                .no_exec_paths = needs_sandboxing ? context->no_exec_paths : NULL,
-
-                .empty_directories = empty_directories,
-                .symlinks = symlinks,
-
-                .bind_mounts = bind_mounts,
-                .n_bind_mounts = n_bind_mounts,
-
-                .temporary_filesystems = context->temporary_filesystems,
-                .n_temporary_filesystems = context->n_temporary_filesystems,
-
-                .mount_images = context->mount_images,
-                .n_mount_images = context->n_mount_images,
-                .mount_image_policy = context->mount_image_policy ?: &image_policy_service,
-
-                .tmp_dir = tmp_dir,
-                .var_tmp_dir = var_tmp_dir,
-
-                .creds_path = creds_path,
-                .log_namespace = context->log_namespace,
-                .mount_propagation_flag = context->mount_propagation_flag,
-
-                .verity = &verity,
-
-                .extension_images = context->extension_images,
-                .n_extension_images = context->n_extension_images,
-                .extension_image_policy = context->extension_image_policy ?: &image_policy_sysext,
-                .extension_directories = context->extension_directories,
-
-                .propagate_dir = propagate_dir,
-                .incoming_dir = incoming_dir,
-                .extension_dir = extension_dir,
-                .notify_socket = root_dir || root_image ? params->notify_socket : NULL,
-                .host_os_release_stage = host_os_release_stage,
-
-                /* If DynamicUser=no and RootDirectory= is set then lets pass a relaxed sandbox info,
-                 * otherwise enforce it, don't ignore protected paths and fail if we are enable to apply the
-                 * sandbox inside the mount namespace. */
-                .ignore_protect_paths = !needs_sandboxing && !context->dynamic_user && root_dir,
-
-                .protect_control_groups = needs_sandboxing && context->protect_control_groups,
-                .protect_kernel_tunables = needs_sandboxing && context->protect_kernel_tunables,
-                .protect_kernel_modules = needs_sandboxing && context->protect_kernel_modules,
-                .protect_kernel_logs = needs_sandboxing && context->protect_kernel_logs,
-                .protect_hostname = needs_sandboxing && context->protect_hostname,
-
-                .private_dev = needs_sandboxing && context->private_devices,
-                .private_network = needs_sandboxing && exec_needs_network_namespace(context),
-                .private_ipc = needs_sandboxing && exec_needs_ipc_namespace(context),
-
-                .mount_apivfs = needs_sandboxing && exec_context_get_effective_mount_apivfs(context),
-
-                /* If NNP is on, we can turn on MS_NOSUID, since it won't have any effect anymore. */
-                .mount_nosuid = needs_sandboxing && context->no_new_privileges && !mac_selinux_use(),
-
-                .protect_home = needs_sandboxing && context->protect_home,
-                .protect_system = needs_sandboxing && context->protect_system,
-                .protect_proc = needs_sandboxing && context->protect_proc,
-                .proc_subset = needs_sandboxing && context->proc_subset,
-        };
-
-        r = setup_namespace(&parameters, error_path);
-        /* If we couldn't set up the namespace this is probably due to a missing capability. setup_namespace() reports
-         * that with a special, recognizable error ENOANO. In this case, silently proceed, but only if exclusively
-         * sandboxing options were used, i.e. nothing such as RootDirectory= or BindMount= that would result in a
-         * completely different execution environment. */
-        if (r == -ENOANO) {
-                if (insist_on_sandboxing(
-                                    context,
-                                    root_dir, root_image,
-                                    bind_mounts,
-                                    n_bind_mounts))
-                        return log_unit_debug_errno(u,
-                                                    SYNTHETIC_ERRNO(EOPNOTSUPP),
-                                                    "Failed to set up namespace, and refusing to continue since "
-                                                    "the selected namespacing options alter mount environment non-trivially.\n"
-                                                    "Bind mounts: %zu, temporary filesystems: %zu, root directory: %s, root image: %s, dynamic user: %s",
-                                                    n_bind_mounts,
-                                                    context->n_temporary_filesystems,
-                                                    yes_no(root_dir),
-                                                    yes_no(root_image),
-                                                    yes_no(context->dynamic_user));
-
-                log_unit_debug(u, "Failed to set up namespace, assuming containerized execution and ignoring.");
-                return 0;
-        }
-
-        return r;
-}
-
-static int apply_working_directory(
-                const ExecContext *context,
-                const ExecParameters *params,
-                ExecRuntime *runtime,
-                const char *home,
-                int *exit_status) {
-
-        const char *d, *wd;
-
-        assert(context);
-        assert(exit_status);
-
-        if (context->working_directory_home) {
-
-                if (!home) {
-                        *exit_status = EXIT_CHDIR;
-                        return -ENXIO;
-                }
-
-                wd = home;
-
-        } else
-                wd = empty_to_root(context->working_directory);
-
-        if (params->flags & EXEC_APPLY_CHROOT)
-                d = wd;
-        else
-                d = prefix_roota((runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory, wd);
-
-        if (chdir(d) < 0 && !context->working_directory_missing_ok) {
-                *exit_status = EXIT_CHDIR;
-                return -errno;
-        }
-
-        return 0;
-}
-
-static int apply_root_directory(
-                const ExecContext *context,
-                const ExecParameters *params,
-                ExecRuntime *runtime,
-                const bool needs_mount_ns,
-                int *exit_status) {
-
-        assert(context);
-        assert(exit_status);
-
-        if (params->flags & EXEC_APPLY_CHROOT)
-                if (!needs_mount_ns && context->root_directory)
-                        if (chroot((runtime ? runtime->ephemeral_copy : NULL) ?: context->root_directory) < 0) {
-                                *exit_status = EXIT_CHROOT;
-                                return -errno;
-                        }
-
-        return 0;
-}
-
-static int setup_keyring(
-                const Unit *u,
-                const ExecContext *context,
-                const ExecParameters *p,
-                uid_t uid, gid_t gid) {
-
-        key_serial_t keyring;
-        int r = 0;
-        uid_t saved_uid;
-        gid_t saved_gid;
-
-        assert(u);
-        assert(context);
-        assert(p);
-
-        /* Let's set up a new per-service "session" kernel keyring for each system service. This has the benefit that
-         * each service runs with its own keyring shared among all processes of the service, but with no hook-up beyond
-         * that scope, and in particular no link to the per-UID keyring. If we don't do this the keyring will be
-         * automatically created on-demand and then linked to the per-UID keyring, by the kernel. The kernel's built-in
-         * on-demand behaviour is very appropriate for login users, but probably not so much for system services, where
-         * UIDs are not necessarily specific to a service but reused (at least in the case of UID 0). */
-
-        if (context->keyring_mode == EXEC_KEYRING_INHERIT)
-                return 0;
-
-        /* Acquiring a reference to the user keyring is nasty. We briefly change identity in order to get things set up
-         * properly by the kernel. If we don't do that then we can't create it atomically, and that sucks for parallel
-         * execution. This mimics what pam_keyinit does, too. Setting up session keyring, to be owned by the right user
-         * & group is just as nasty as acquiring a reference to the user keyring. */
-
-        saved_uid = getuid();
-        saved_gid = getgid();
-
-        if (gid_is_valid(gid) && gid != saved_gid) {
-                if (setregid(gid, -1) < 0)
-                        return log_unit_error_errno(u, errno, "Failed to change GID for user keyring: %m");
-        }
-
-        if (uid_is_valid(uid) && uid != saved_uid) {
-                if (setreuid(uid, -1) < 0) {
-                        r = log_unit_error_errno(u, errno, "Failed to change UID for user keyring: %m");
-                        goto out;
-                }
-        }
-
-        keyring = keyctl(KEYCTL_JOIN_SESSION_KEYRING, 0, 0, 0, 0);
-        if (keyring == -1) {
-                if (errno == ENOSYS)
-                        log_unit_debug_errno(u, errno, "Kernel keyring not supported, ignoring.");
-                else if (ERRNO_IS_PRIVILEGE(errno))
-                        log_unit_debug_errno(u, errno, "Kernel keyring access prohibited, ignoring.");
-                else if (errno == EDQUOT)
-                        log_unit_debug_errno(u, errno, "Out of kernel keyrings to allocate, ignoring.");
-                else
-                        r = log_unit_error_errno(u, errno, "Setting up kernel keyring failed: %m");
-
-                goto out;
-        }
-
-        /* When requested link the user keyring into the session keyring. */
-        if (context->keyring_mode == EXEC_KEYRING_SHARED) {
-
-                if (keyctl(KEYCTL_LINK,
-                           KEY_SPEC_USER_KEYRING,
-                           KEY_SPEC_SESSION_KEYRING, 0, 0) < 0) {
-                        r = log_unit_error_errno(u, errno, "Failed to link user keyring into session keyring: %m");
-                        goto out;
-                }
-        }
-
-        /* Restore uid/gid back */
-        if (uid_is_valid(uid) && uid != saved_uid) {
-                if (setreuid(saved_uid, -1) < 0) {
-                        r = log_unit_error_errno(u, errno, "Failed to change UID back for user keyring: %m");
-                        goto out;
-                }
-        }
-
-        if (gid_is_valid(gid) && gid != saved_gid) {
-                if (setregid(saved_gid, -1) < 0)
-                        return log_unit_error_errno(u, errno, "Failed to change GID back for user keyring: %m");
-        }
-
-        /* Populate they keyring with the invocation ID by default, as original saved_uid. */
-        if (!sd_id128_is_null(u->invocation_id)) {
-                key_serial_t key;
-
-                key = add_key("user", "invocation_id", &u->invocation_id, sizeof(u->invocation_id), KEY_SPEC_SESSION_KEYRING);
-                if (key == -1)
-                        log_unit_debug_errno(u, errno, "Failed to add invocation ID to keyring, ignoring: %m");
-                else {
-                        if (keyctl(KEYCTL_SETPERM, key,
-                                   KEY_POS_VIEW|KEY_POS_READ|KEY_POS_SEARCH|
-                                   KEY_USR_VIEW|KEY_USR_READ|KEY_USR_SEARCH, 0, 0) < 0)
-                                r = log_unit_error_errno(u, errno, "Failed to restrict invocation ID permission: %m");
-                }
-        }
-
-out:
-        /* Revert back uid & gid for the last time, and exit */
-        /* no extra logging, as only the first already reported error matters */
-        if (getuid() != saved_uid)
-                (void) setreuid(saved_uid, -1);
-
-        if (getgid() != saved_gid)
-                (void) setregid(saved_gid, -1);
-
-        return r;
-}
-
-static void append_socket_pair(int *array, size_t *n, const int pair[static 2]) {
-        assert(array);
-        assert(n);
-        assert(pair);
-
-        if (pair[0] >= 0)
-                array[(*n)++] = pair[0];
-        if (pair[1] >= 0)
-                array[(*n)++] = pair[1];
-}
-
-static int close_remaining_fds(
-                const ExecParameters *params,
-                const ExecRuntime *runtime,
-                int user_lookup_fd,
-                int socket_fd,
-                const int *fds, size_t n_fds) {
-
-        size_t n_dont_close = 0;
-        int dont_close[n_fds + 14];
-
-        assert(params);
-
-        if (params->stdin_fd >= 0)
-                dont_close[n_dont_close++] = params->stdin_fd;
-        if (params->stdout_fd >= 0)
-                dont_close[n_dont_close++] = params->stdout_fd;
-        if (params->stderr_fd >= 0)
-                dont_close[n_dont_close++] = params->stderr_fd;
-
-        if (socket_fd >= 0)
-                dont_close[n_dont_close++] = socket_fd;
-        if (n_fds > 0) {
-                memcpy(dont_close + n_dont_close, fds, sizeof(int) * n_fds);
-                n_dont_close += n_fds;
-        }
-
-        if (runtime)
-                append_socket_pair(dont_close, &n_dont_close, runtime->ephemeral_storage_socket);
-
-        if (runtime && runtime->shared) {
-                append_socket_pair(dont_close, &n_dont_close, runtime->shared->netns_storage_socket);
-                append_socket_pair(dont_close, &n_dont_close, runtime->shared->ipcns_storage_socket);
-        }
-
-        if (runtime && runtime->dynamic_creds) {
-                if (runtime->dynamic_creds->user)
-                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->user->storage_socket);
-                if (runtime->dynamic_creds->group)
-                        append_socket_pair(dont_close, &n_dont_close, runtime->dynamic_creds->group->storage_socket);
-        }
-
-        if (user_lookup_fd >= 0)
-                dont_close[n_dont_close++] = user_lookup_fd;
-
-        return close_all_fds(dont_close, n_dont_close);
-}
-
-static int send_user_lookup(
-                Unit *unit,
-                int user_lookup_fd,
-                uid_t uid,
-                gid_t gid) {
-
-        assert(unit);
-
-        /* Send the resolved UID/GID to PID 1 after we learnt it. We send a single datagram, containing the UID/GID
-         * data as well as the unit name. Note that we suppress sending this if no user/group to resolve was
-         * specified. */
-
-        if (user_lookup_fd < 0)
-                return 0;
-
-        if (!uid_is_valid(uid) && !gid_is_valid(gid))
-                return 0;
-
-        if (writev(user_lookup_fd,
-               (struct iovec[]) {
-                           IOVEC_MAKE(&uid, sizeof(uid)),
-                           IOVEC_MAKE(&gid, sizeof(gid)),
-                           IOVEC_MAKE_STRING(unit->id) }, 3) < 0)
-                return -errno;
-
-        return 0;
-}
-
-static int acquire_home(const ExecContext *c, uid_t uid, const char** home, char **buf) {
-        int r;
-
-        assert(c);
-        assert(home);
-        assert(buf);
-
-        /* If WorkingDirectory=~ is set, try to acquire a usable home directory. */
-
-        if (*home)
-                return 0;
-
-        if (!c->working_directory_home)
-                return 0;
-
-        r = get_home_dir(buf);
-        if (r < 0)
-                return r;
-
-        *home = *buf;
-        return 1;
-}
-
-static int compile_suggested_paths(const ExecContext *c, const ExecParameters *p, char ***ret) {
-        _cleanup_strv_free_ char ** list = NULL;
-        int r;
-
-        assert(c);
-        assert(p);
-        assert(ret);
-
-        assert(c->dynamic_user);
-
-        /* Compile a list of paths that it might make sense to read the owning UID from to use as initial candidate for
-         * dynamic UID allocation, in order to save us from doing costly recursive chown()s of the special
-         * directories. */
-
-        for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
-                if (t == EXEC_DIRECTORY_CONFIGURATION)
-                        continue;
-
-                if (!p->prefix[t])
-                        continue;
-
-                for (size_t i = 0; i < c->directories[t].n_items; i++) {
-                        char *e;
-
-                        if (exec_directory_is_private(c, t))
-                                e = path_join(p->prefix[t], "private", c->directories[t].items[i].path);
-                        else
-                                e = path_join(p->prefix[t], c->directories[t].items[i].path);
-                        if (!e)
-                                return -ENOMEM;
-
-                        r = strv_consume(&list, e);
-                        if (r < 0)
-                                return r;
-                }
-        }
-
-        *ret = TAKE_PTR(list);
-
-        return 0;
-}
-
-static int exec_parameters_get_cgroup_path(
-                const ExecParameters *params,
-                const CGroupContext *c,
-                char **ret) {
-
-        const char *subgroup = NULL;
-        char *p;
-
-        assert(params);
-        assert(ret);
-
-        if (!params->cgroup_path)
-                return -EINVAL;
-
-        /* If we are called for a unit where cgroup delegation is on, and the payload created its own populated
-         * subcgroup (which we expect it to do, after all it asked for delegation), then we cannot place the control
-         * processes started after the main unit's process in the unit's main cgroup because it is now an inner one,
-         * and inner cgroups may not contain processes. Hence, if delegation is on, and this is a control process,
-         * let's use ".control" as subcgroup instead. Note that we do so only for ExecStartPost=, ExecReload=,
-         * ExecStop=, ExecStopPost=, i.e. for the commands where the main process is already forked. For ExecStartPre=
-         * this is not necessary, the cgroup is still empty. We distinguish these cases with the EXEC_CONTROL_CGROUP
-         * flag, which is only passed for the former statements, not for the latter. */
-
-        if (FLAGS_SET(params->flags, EXEC_CGROUP_DELEGATE) && (FLAGS_SET(params->flags, EXEC_CONTROL_CGROUP) || c->delegate_subgroup)) {
-                if (FLAGS_SET(params->flags, EXEC_IS_CONTROL))
-                        subgroup = ".control";
-                else
-                        subgroup = c->delegate_subgroup;
-        }
-
-        if (subgroup)
-                p = path_join(params->cgroup_path, subgroup);
-        else
-                p = strdup(params->cgroup_path);
-        if (!p)
-                return -ENOMEM;
-
-        *ret = p;
-        return !!subgroup;
-}
-
-static int exec_context_cpu_affinity_from_numa(const ExecContext *c, CPUSet *ret) {
-        _cleanup_(cpu_set_reset) CPUSet s = {};
-        int r;
-
-        assert(c);
-        assert(ret);
-
-        if (!c->numa_policy.nodes.set) {
-                log_debug("Can't derive CPU affinity mask from NUMA mask because NUMA mask is not set, ignoring");
-                return 0;
-        }
-
-        r = numa_to_cpu_set(&c->numa_policy, &s);
-        if (r < 0)
-                return r;
-
-        cpu_set_reset(ret);
-
-        return cpu_set_add_all(ret, &s);
-}
-
-bool exec_context_get_cpu_affinity_from_numa(const ExecContext *c) {
-        assert(c);
-
-        return c->cpu_affinity_from_numa;
-}
-
-static int add_shifted_fd(int *fds, size_t fds_size, size_t *n_fds, int fd, int *ret_fd) {
-        int r;
-
-        assert(fds);
-        assert(n_fds);
-        assert(*n_fds < fds_size);
-        assert(ret_fd);
-
-        if (fd < 0) {
-                *ret_fd = -EBADF;
-                return 0;
-        }
-
-        if (fd < 3 + (int) *n_fds) {
-                /* Let's move the fd up, so that it's outside of the fd range we will use to store
-                 * the fds we pass to the process (or which are closed only during execve). */
-
-                r = fcntl(fd, F_DUPFD_CLOEXEC, 3 + (int) *n_fds);
-                if (r < 0)
-                        return -errno;
-
-                close_and_replace(fd, r);
-        }
-
-        *ret_fd = fds[*n_fds] = fd;
-        (*n_fds) ++;
-        return 1;
-}
-
-static int connect_unix_harder(Unit *u, const OpenFile *of, int ofd) {
-        union sockaddr_union addr = {
-                .un.sun_family = AF_UNIX,
-        };
-        socklen_t sa_len;
-        static const int socket_types[] = { SOCK_DGRAM, SOCK_STREAM, SOCK_SEQPACKET };
-        int r;
-
-        assert(u);
-        assert(of);
-        assert(ofd >= 0);
-
-        r = sockaddr_un_set_path(&addr.un, FORMAT_PROC_FD_PATH(ofd));
-        if (r < 0)
-                return log_unit_error_errno(u, r, "Failed to set sockaddr for %s: %m", of->path);
-
-        sa_len = r;
-
-        for (size_t i = 0; i < ELEMENTSOF(socket_types); i++) {
-                _cleanup_close_ int fd = -EBADF;
-
-                fd = socket(AF_UNIX, socket_types[i] | SOCK_CLOEXEC, 0);
-                if (fd < 0)
-                        return log_unit_error_errno(u, errno, "Failed to create socket for %s: %m", of->path);
-
-                r = RET_NERRNO(connect(fd, &addr.sa, sa_len));
-                if (r == -EPROTOTYPE)
-                        continue;
-                if (r < 0)
-                        return log_unit_error_errno(u, r, "Failed to connect socket for %s: %m", of->path);
-
-                return TAKE_FD(fd);
-        }
-
-        return log_unit_error_errno(u, SYNTHETIC_ERRNO(EPROTOTYPE), "Failed to connect socket for \"%s\".", of->path);
-}
-
-static int get_open_file_fd(Unit *u, const OpenFile *of) {
-        struct stat st;
-        _cleanup_close_ int fd = -EBADF, ofd = -EBADF;
-
-        assert(u);
-        assert(of);
-
-        ofd = open(of->path, O_PATH | O_CLOEXEC);
-        if (ofd < 0)
-                return log_unit_error_errno(u, errno, "Could not open \"%s\": %m", of->path);
-
-        if (fstat(ofd, &st) < 0)
-                return log_unit_error_errno(u, errno, "Failed to stat %s: %m", of->path);
-
-        if (S_ISSOCK(st.st_mode)) {
-                fd = connect_unix_harder(u, of, ofd);
-                if (fd < 0)
-                        return fd;
-
-                if (FLAGS_SET(of->flags, OPENFILE_READ_ONLY) && shutdown(fd, SHUT_WR) < 0)
-                        return log_unit_error_errno(u, errno, "Failed to shutdown send for socket %s: %m",
-                                                    of->path);
-
-                log_unit_debug(u, "socket %s opened (fd=%d)", of->path, fd);
-        } else {
-                int flags = FLAGS_SET(of->flags, OPENFILE_READ_ONLY) ? O_RDONLY : O_RDWR;
-                if (FLAGS_SET(of->flags, OPENFILE_APPEND))
-                        flags |= O_APPEND;
-                else if (FLAGS_SET(of->flags, OPENFILE_TRUNCATE))
-                        flags |= O_TRUNC;
-
-                fd = fd_reopen(ofd, flags | O_CLOEXEC);
-                if (fd < 0)
-                        return log_unit_error_errno(u, fd, "Failed to open file %s: %m", of->path);
-
-                log_unit_debug(u, "file %s opened (fd=%d)", of->path, fd);
-        }
-
-        return TAKE_FD(fd);
-}
-
-static int collect_open_file_fds(
-                Unit *u,
-                OpenFile* open_files,
-                int **fds,
-                char ***fdnames,
-                size_t *n_fds) {
-        int r;
-
-        assert(u);
-        assert(fds);
-        assert(fdnames);
-        assert(n_fds);
-
-        LIST_FOREACH(open_files, of, open_files) {
-                _cleanup_close_ int fd = -EBADF;
-
-                fd = get_open_file_fd(u, of);
-                if (fd < 0) {
-                        if (FLAGS_SET(of->flags, OPENFILE_GRACEFUL)) {
-                                log_unit_debug_errno(u, fd, "Failed to get OpenFile= file descriptor for %s, ignoring: %m", of->path);
-                                continue;
-                        }
-
-                        return fd;
-                }
-
-                if (!GREEDY_REALLOC(*fds, *n_fds + 1))
-                        return -ENOMEM;
-
-                r = strv_extend(fdnames, of->fdname);
-                if (r < 0)
-                        return r;
-
-                (*fds)[*n_fds] = TAKE_FD(fd);
-
-                (*n_fds)++;
-        }
-
-        return 0;
-}
-
-static void log_command_line(Unit *unit, const char *msg, const char *executable, char **argv) {
-        assert(unit);
-        assert(msg);
-        assert(executable);
-
-        if (!DEBUG_LOGGING)
-                return;
-
-        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
-
-        log_unit_struct(unit, LOG_DEBUG,
-                        "EXECUTABLE=%s", executable,
-                        LOG_UNIT_MESSAGE(unit, "%s: %s", msg, strnull(cmdline)),
-                        LOG_UNIT_INVOCATION_ID(unit));
-}
-
-static bool exec_context_need_unprivileged_private_users(
-                const ExecContext *context,
-                const ExecParameters *params) {
-
-        assert(context);
-        assert(params);
-
-        /* These options require PrivateUsers= when used in user units, as we need to be in a user namespace
-         * to have permission to enable them when not running as root. If we have effective CAP_SYS_ADMIN
-         * (system manager) then we have privileges and don't need this. */
-        if (params->runtime_scope != RUNTIME_SCOPE_USER)
-                return false;
-
-        return context->private_users ||
-               context->private_tmp ||
-               context->private_devices ||
-               context->private_network ||
-               context->network_namespace_path ||
-               context->private_ipc ||
-               context->ipc_namespace_path ||
-               context->private_mounts > 0 ||
-               context->mount_apivfs ||
-               context->n_bind_mounts > 0 ||
-               context->n_temporary_filesystems > 0 ||
-               context->root_directory ||
-               !strv_isempty(context->extension_directories) ||
-               context->protect_system != PROTECT_SYSTEM_NO ||
-               context->protect_home != PROTECT_HOME_NO ||
-               context->protect_kernel_tunables ||
-               context->protect_kernel_modules ||
-               context->protect_kernel_logs ||
-               context->protect_control_groups ||
-               context->protect_clock ||
-               context->protect_hostname ||
-               !strv_isempty(context->read_write_paths) ||
-               !strv_isempty(context->read_only_paths) ||
-               !strv_isempty(context->inaccessible_paths) ||
-               !strv_isempty(context->exec_paths) ||
-               !strv_isempty(context->no_exec_paths);
-}
-
-static int exec_child(
-                Unit *unit,
-                const ExecCommand *command,
-                const ExecContext *context,
-                const ExecParameters *params,
-                ExecRuntime *runtime,
-                const CGroupContext *cgroup_context,
-                int socket_fd,
-                const int named_iofds[static 3],
-                int *params_fds,
-                size_t n_socket_fds,
-                size_t n_storage_fds,
-                char **files_env,
-                int user_lookup_fd,
-                int *exit_status) {
-
-        _cleanup_strv_free_ char **our_env = NULL, **pass_env = NULL, **joined_exec_search_path = NULL, **accum_env = NULL, **replaced_argv = NULL;
-        int r, ngids = 0, exec_fd;
-        _cleanup_free_ gid_t *supplementary_gids = NULL;
-        const char *username = NULL, *groupname = NULL;
-        _cleanup_free_ char *home_buffer = NULL, *memory_pressure_path = NULL;
-        const char *home = NULL, *shell = NULL;
-        char **final_argv = NULL;
-        dev_t journal_stream_dev = 0;
-        ino_t journal_stream_ino = 0;
-        bool userns_set_up = false;
-        bool needs_sandboxing,          /* Do we need to set up full sandboxing? (i.e. all namespacing, all MAC stuff, caps, yadda yadda */
-                needs_setuid,           /* Do we need to do the actual setresuid()/setresgid() calls? */
-                needs_mount_namespace,  /* Do we need to set up a mount namespace for this kernel? */
-                needs_ambient_hack;     /* Do we need to apply the ambient capabilities hack? */
-#if HAVE_SELINUX
-        _cleanup_free_ char *mac_selinux_context_net = NULL;
-        bool use_selinux = false;
-#endif
-#if ENABLE_SMACK
-        bool use_smack = false;
-#endif
-#if HAVE_APPARMOR
-        bool use_apparmor = false;
-#endif
-        uid_t saved_uid = getuid();
-        gid_t saved_gid = getgid();
-        uid_t uid = UID_INVALID;
-        gid_t gid = GID_INVALID;
-        size_t n_fds = n_socket_fds + n_storage_fds, /* fds to pass to the child */
-               n_keep_fds; /* total number of fds not to close */
-        int secure_bits;
-        _cleanup_free_ gid_t *gids_after_pam = NULL;
-        int ngids_after_pam = 0;
-        _cleanup_free_ int *fds = NULL;
-        _cleanup_strv_free_ char **fdnames = NULL;
-
-        assert(unit);
-        assert(command);
-        assert(context);
-        assert(params);
-        assert(exit_status);
-
-        /* Explicitly test for CVE-2021-4034 inspired invocations */
-        assert(command->path);
-        assert(!strv_isempty(command->argv));
-
-        rename_process_from_path(command->path);
-
-        /* We reset exactly these signals, since they are the only ones we set to SIG_IGN in the main
-         * daemon. All others we leave untouched because we set them to SIG_DFL or a valid handler initially,
-         * both of which will be demoted to SIG_DFL. */
-        (void) default_signals(SIGNALS_CRASH_HANDLER,
-                               SIGNALS_IGNORE);
-
-        if (context->ignore_sigpipe)
-                (void) ignore_signals(SIGPIPE);
-
-        r = reset_signal_mask();
-        if (r < 0) {
-                *exit_status = EXIT_SIGNAL_MASK;
-                return log_unit_error_errno(unit, r, "Failed to set process signal mask: %m");
-        }
-
-        if (params->idle_pipe)
-                do_idle_pipe_dance(params->idle_pipe);
-
-        /* Close fds we don't need very early to make sure we don't block init reexecution because it cannot bind its
-         * sockets. Among the fds we close are the logging fds, and we want to keep them closed, so that we don't have
-         * any fds open we don't really want open during the transition. In order to make logging work, we switch the
-         * log subsystem into open_when_needed mode, so that it reopens the logs on every single log call. */
-
-        log_forget_fds();
-        log_set_open_when_needed(true);
-        log_settle_target();
-
-        /* In case anything used libc syslog(), close this here, too */
-        closelog();
-
-        fds = newdup(int, params_fds, n_fds);
-        if (!fds) {
-                *exit_status = EXIT_MEMORY;
-                return log_oom();
-        }
-
-        fdnames = strv_copy((char**) params->fd_names);
-        if (!fdnames) {
-                *exit_status = EXIT_MEMORY;
-                return log_oom();
-        }
-
-        r = collect_open_file_fds(unit, params->open_files, &fds, &fdnames, &n_fds);
-        if (r < 0) {
-                *exit_status = EXIT_FDS;
-                return log_unit_error_errno(unit, r, "Failed to get OpenFile= file descriptors: %m");
-        }
-
-        int keep_fds[n_fds + 3];
-        memcpy_safe(keep_fds, fds, n_fds * sizeof(int));
-        n_keep_fds = n_fds;
-
-        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, params->exec_fd, &exec_fd);
-        if (r < 0) {
-                *exit_status = EXIT_FDS;
-                return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
-        }
-
-#if HAVE_LIBBPF
-        if (unit->manager->restrict_fs) {
-                int bpf_map_fd = lsm_bpf_map_restrict_fs_fd(unit);
-                if (bpf_map_fd < 0) {
-                        *exit_status = EXIT_FDS;
-                        return log_unit_error_errno(unit, bpf_map_fd, "Failed to get restrict filesystems BPF map fd: %m");
-                }
-
-                r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, bpf_map_fd, &bpf_map_fd);
-                if (r < 0) {
-                        *exit_status = EXIT_FDS;
-                        return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
-                }
-        }
-#endif
-
-        r = close_remaining_fds(params, runtime, user_lookup_fd, socket_fd, keep_fds, n_keep_fds);
-        if (r < 0) {
-                *exit_status = EXIT_FDS;
-                return log_unit_error_errno(unit, r, "Failed to close unwanted file descriptors: %m");
-        }
-
-        if (!context->same_pgrp &&
-            setsid() < 0) {
-                *exit_status = EXIT_SETSID;
-                return log_unit_error_errno(unit, errno, "Failed to create new process session: %m");
-        }
-
-        exec_context_tty_reset(context, params);
-
-        if (unit_shall_confirm_spawn(unit)) {
-                _cleanup_free_ char *cmdline = NULL;
-
-                cmdline = quote_command_line(command->argv, SHELL_ESCAPE_EMPTY);
-                if (!cmdline) {
-                        *exit_status = EXIT_MEMORY;
-                        return log_oom();
-                }
-
-                r = ask_for_confirmation(context, params->confirm_spawn, unit, cmdline);
-                if (r != CONFIRM_EXECUTE) {
-                        if (r == CONFIRM_PRETEND_SUCCESS) {
-                                *exit_status = EXIT_SUCCESS;
-                                return 0;
-                        }
-
-                        *exit_status = EXIT_CONFIRM;
-                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ECANCELED),
-                                                    "Execution cancelled by the user");
-                }
-        }
-
-        /* We are about to invoke NSS and PAM modules. Let's tell them what we are doing here, maybe they care. This is
-         * used by nss-resolve to disable itself when we are about to start systemd-resolved, to avoid deadlocks. Note
-         * that these env vars do not survive the execve(), which means they really only apply to the PAM and NSS
-         * invocations themselves. Also note that while we'll only invoke NSS modules involved in user management they
-         * might internally call into other NSS modules that are involved in hostname resolution, we never know. */
-        if (setenv("SYSTEMD_ACTIVATION_UNIT", unit->id, true) != 0 ||
-            setenv("SYSTEMD_ACTIVATION_SCOPE", runtime_scope_to_string(params->runtime_scope), true) != 0) {
-                *exit_status = EXIT_MEMORY;
-                return log_unit_error_errno(unit, errno, "Failed to update environment: %m");
-        }
-
-        if (context->dynamic_user && runtime && runtime->dynamic_creds) {
-                _cleanup_strv_free_ char **suggested_paths = NULL;
-
-                /* On top of that, make sure we bypass our own NSS module nss-systemd comprehensively for any NSS
-                 * checks, if DynamicUser=1 is used, as we shouldn't create a feedback loop with ourselves here. */
-                if (putenv((char*) "SYSTEMD_NSS_DYNAMIC_BYPASS=1") != 0) {
-                        *exit_status = EXIT_USER;
-                        return log_unit_error_errno(unit, errno, "Failed to update environment: %m");
-                }
-
-                r = compile_suggested_paths(context, params, &suggested_paths);
-                if (r < 0) {
-                        *exit_status = EXIT_MEMORY;
-                        return log_oom();
-                }
-
-                r = dynamic_creds_realize(runtime->dynamic_creds, suggested_paths, &uid, &gid);
-                if (r < 0) {
-                        *exit_status = EXIT_USER;
-                        if (r == -EILSEQ)
-                                return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
-                                                            "Failed to update dynamic user credentials: User or group with specified name already exists.");
-                        return log_unit_error_errno(unit, r, "Failed to update dynamic user credentials: %m");
-                }
-
-                if (!uid_is_valid(uid)) {
-                        *exit_status = EXIT_USER;
-                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ESRCH), "UID validation failed for \""UID_FMT"\"", uid);
-                }
-
-                if (!gid_is_valid(gid)) {
-                        *exit_status = EXIT_USER;
-                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(ESRCH), "GID validation failed for \""GID_FMT"\"", gid);
-                }
-
-                if (runtime->dynamic_creds->user)
-                        username = runtime->dynamic_creds->user->name;
-
-        } else {
-                if (context->user) {
-                        r = get_fixed_user(context->user, &username, &uid, &gid, &home, &shell);
-                        if (r < 0) {
-                                *exit_status = EXIT_USER;
-                                return log_unit_error_errno(unit, r, "Failed to determine user credentials: %m");
-                        }
-                }
-
-                if (context->group) {
-                        r = get_fixed_group(context->group, &groupname, &gid);
-                        if (r < 0) {
-                                *exit_status = EXIT_GROUP;
-                                return log_unit_error_errno(unit, r, "Failed to determine group credentials: %m");
-                        }
-                }
-        }
-
-        /* Initialize user supplementary groups and get SupplementaryGroups= ones */
-        r = get_supplementary_groups(context, username, groupname, gid,
-                                     &supplementary_gids, &ngids);
-        if (r < 0) {
-                *exit_status = EXIT_GROUP;
-                return log_unit_error_errno(unit, r, "Failed to determine supplementary groups: %m");
-        }
-
-        r = send_user_lookup(unit, user_lookup_fd, uid, gid);
-        if (r < 0) {
-                *exit_status = EXIT_USER;
-                return log_unit_error_errno(unit, r, "Failed to send user credentials to PID1: %m");
-        }
-
-        user_lookup_fd = safe_close(user_lookup_fd);
-
-        r = acquire_home(context, uid, &home, &home_buffer);
-        if (r < 0) {
-                *exit_status = EXIT_CHDIR;
-                return log_unit_error_errno(unit, r, "Failed to determine $HOME for user: %m");
-        }
-
-        /* If a socket is connected to STDIN/STDOUT/STDERR, we must drop O_NONBLOCK */
-        if (socket_fd >= 0)
-                (void) fd_nonblock(socket_fd, false);
-
-        /* Journald will try to look-up our cgroup in order to populate _SYSTEMD_CGROUP and _SYSTEMD_UNIT fields.
-         * Hence we need to migrate to the target cgroup from init.scope before connecting to journald */
-        if (params->cgroup_path) {
-                _cleanup_free_ char *p = NULL;
-
-                r = exec_parameters_get_cgroup_path(params, cgroup_context, &p);
-                if (r < 0) {
-                        *exit_status = EXIT_CGROUP;
-                        return log_unit_error_errno(unit, r, "Failed to acquire cgroup path: %m");
-                }
-
-                r = cg_attach_everywhere(params->cgroup_supported, p, 0, NULL, NULL);
-                if (r == -EUCLEAN) {
-                        *exit_status = EXIT_CGROUP;
-                        return log_unit_error_errno(unit, r, "Failed to attach process to cgroup %s "
-                                                    "because the cgroup or one of its parents or "
-                                                    "siblings is in the threaded mode: %m", p);
-                }
-                if (r < 0) {
-                        *exit_status = EXIT_CGROUP;
-                        return log_unit_error_errno(unit, r, "Failed to attach to cgroup %s: %m", p);
-                }
-        }
-
-        if (context->network_namespace_path && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
-                r = open_shareable_ns_path(runtime->shared->netns_storage_socket, context->network_namespace_path, CLONE_NEWNET);
-                if (r < 0) {
-                        *exit_status = EXIT_NETWORK;
-                        return log_unit_error_errno(unit, r, "Failed to open network namespace path %s: %m", context->network_namespace_path);
-                }
-        }
-
-        if (context->ipc_namespace_path && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
-                r = open_shareable_ns_path(runtime->shared->ipcns_storage_socket, context->ipc_namespace_path, CLONE_NEWIPC);
-                if (r < 0) {
-                        *exit_status = EXIT_NAMESPACE;
-                        return log_unit_error_errno(unit, r, "Failed to open IPC namespace path %s: %m", context->ipc_namespace_path);
-                }
-        }
-
-        r = setup_input(context, params, socket_fd, named_iofds);
-        if (r < 0) {
-                *exit_status = EXIT_STDIN;
-                return log_unit_error_errno(unit, r, "Failed to set up standard input: %m");
-        }
-
-        r = setup_output(unit, context, params, STDOUT_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
-        if (r < 0) {
-                *exit_status = EXIT_STDOUT;
-                return log_unit_error_errno(unit, r, "Failed to set up standard output: %m");
-        }
-
-        r = setup_output(unit, context, params, STDERR_FILENO, socket_fd, named_iofds, basename(command->path), uid, gid, &journal_stream_dev, &journal_stream_ino);
-        if (r < 0) {
-                *exit_status = EXIT_STDERR;
-                return log_unit_error_errno(unit, r, "Failed to set up standard error output: %m");
-        }
-
-        if (context->oom_score_adjust_set) {
-                /* When we can't make this change due to EPERM, then let's silently skip over it. User
-                 * namespaces prohibit write access to this file, and we shouldn't trip up over that. */
-                r = set_oom_score_adjust(context->oom_score_adjust);
-                if (ERRNO_IS_NEG_PRIVILEGE(r))
-                        log_unit_debug_errno(unit, r,
-                                             "Failed to adjust OOM setting, assuming containerized execution, ignoring: %m");
-                else if (r < 0) {
-                        *exit_status = EXIT_OOM_ADJUST;
-                        return log_unit_error_errno(unit, r, "Failed to adjust OOM setting: %m");
-                }
-        }
-
-        if (context->coredump_filter_set) {
-                r = set_coredump_filter(context->coredump_filter);
-                if (ERRNO_IS_NEG_PRIVILEGE(r))
-                        log_unit_debug_errno(unit, r, "Failed to adjust coredump_filter, ignoring: %m");
-                else if (r < 0) {
-                        *exit_status = EXIT_LIMITS;
-                        return log_unit_error_errno(unit, r, "Failed to adjust coredump_filter: %m");
-                }
-        }
-
-        if (context->nice_set) {
-                r = setpriority_closest(context->nice);
-                if (r < 0) {
-                        *exit_status = EXIT_NICE;
-                        return log_unit_error_errno(unit, r, "Failed to set up process scheduling priority (nice level): %m");
-                }
-        }
-
-        if (context->cpu_sched_set) {
-                struct sched_param param = {
-                        .sched_priority = context->cpu_sched_priority,
-                };
-
-                r = sched_setscheduler(0,
-                                       context->cpu_sched_policy |
-                                       (context->cpu_sched_reset_on_fork ?
-                                        SCHED_RESET_ON_FORK : 0),
-                                       &param);
-                if (r < 0) {
-                        *exit_status = EXIT_SETSCHEDULER;
-                        return log_unit_error_errno(unit, errno, "Failed to set up CPU scheduling: %m");
-                }
-        }
-
-        if (context->cpu_affinity_from_numa || context->cpu_set.set) {
-                _cleanup_(cpu_set_reset) CPUSet converted_cpu_set = {};
-                const CPUSet *cpu_set;
-
-                if (context->cpu_affinity_from_numa) {
-                        r = exec_context_cpu_affinity_from_numa(context, &converted_cpu_set);
-                        if (r < 0) {
-                                *exit_status = EXIT_CPUAFFINITY;
-                                return log_unit_error_errno(unit, r, "Failed to derive CPU affinity mask from NUMA mask: %m");
-                        }
-
-                        cpu_set = &converted_cpu_set;
-                } else
-                        cpu_set = &context->cpu_set;
-
-                if (sched_setaffinity(0, cpu_set->allocated, cpu_set->set) < 0) {
-                        *exit_status = EXIT_CPUAFFINITY;
-                        return log_unit_error_errno(unit, errno, "Failed to set up CPU affinity: %m");
-                }
-        }
-
-        if (mpol_is_valid(numa_policy_get_type(&context->numa_policy))) {
-                r = apply_numa_policy(&context->numa_policy);
-                if (ERRNO_IS_NEG_NOT_SUPPORTED(r))
-                        log_unit_debug_errno(unit, r, "NUMA support not available, ignoring.");
-                else if (r < 0) {
-                        *exit_status = EXIT_NUMA_POLICY;
-                        return log_unit_error_errno(unit, r, "Failed to set NUMA memory policy: %m");
-                }
-        }
-
-        if (context->ioprio_set)
-                if (ioprio_set(IOPRIO_WHO_PROCESS, 0, context->ioprio) < 0) {
-                        *exit_status = EXIT_IOPRIO;
-                        return log_unit_error_errno(unit, errno, "Failed to set up IO scheduling priority: %m");
-                }
-
-        if (context->timer_slack_nsec != NSEC_INFINITY)
-                if (prctl(PR_SET_TIMERSLACK, context->timer_slack_nsec) < 0) {
-                        *exit_status = EXIT_TIMERSLACK;
-                        return log_unit_error_errno(unit, errno, "Failed to set up timer slack: %m");
-                }
-
-        if (context->personality != PERSONALITY_INVALID) {
-                r = safe_personality(context->personality);
-                if (r < 0) {
-                        *exit_status = EXIT_PERSONALITY;
-                        return log_unit_error_errno(unit, r, "Failed to set up execution domain (personality): %m");
-                }
-        }
-
-        if (context->utmp_id) {
-                const char *line = context->tty_path ?
-                        (path_startswith(context->tty_path, "/dev/") ?: context->tty_path) :
-                        NULL;
-                utmp_put_init_process(context->utmp_id, getpid_cached(), getsid(0),
-                                      line,
-                                      context->utmp_mode == EXEC_UTMP_INIT  ? INIT_PROCESS :
-                                      context->utmp_mode == EXEC_UTMP_LOGIN ? LOGIN_PROCESS :
-                                      USER_PROCESS,
-                                      username);
-        }
-
-        if (uid_is_valid(uid)) {
-                r = chown_terminal(STDIN_FILENO, uid);
-                if (r < 0) {
-                        *exit_status = EXIT_STDIN;
-                        return log_unit_error_errno(unit, r, "Failed to change ownership of terminal: %m");
-                }
-        }
-
-        if (params->cgroup_path) {
-                /* If delegation is enabled we'll pass ownership of the cgroup to the user of the new process. On cgroup v1
-                 * this is only about systemd's own hierarchy, i.e. not the controller hierarchies, simply because that's not
-                 * safe. On cgroup v2 there's only one hierarchy anyway, and delegation is safe there, hence in that case only
-                 * touch a single hierarchy too. */
-
-                if (params->flags & EXEC_CGROUP_DELEGATE) {
-                        _cleanup_free_ char *p = NULL;
-
-                        r = cg_set_access(SYSTEMD_CGROUP_CONTROLLER, params->cgroup_path, uid, gid);
-                        if (r < 0) {
-                                *exit_status = EXIT_CGROUP;
-                                return log_unit_error_errno(unit, r, "Failed to adjust control group access: %m");
-                        }
-
-                        r = exec_parameters_get_cgroup_path(params, cgroup_context, &p);
-                        if (r < 0) {
-                                *exit_status = EXIT_CGROUP;
-                                return log_unit_error_errno(unit, r, "Failed to acquire cgroup path: %m");
-                        }
-                        if (r > 0) {
-                                r = cg_set_access_recursive(SYSTEMD_CGROUP_CONTROLLER, p, uid, gid);
-                                if (r < 0) {
-                                        *exit_status = EXIT_CGROUP;
-                                        return log_unit_error_errno(unit, r, "Failed to adjust control subgroup access: %m");
-                                }
-                        }
-                }
-
-                if (cgroup_context && cg_unified() > 0 && is_pressure_supported() > 0) {
-                        if (cgroup_context_want_memory_pressure(cgroup_context)) {
-                                r = cg_get_path("memory", params->cgroup_path, "memory.pressure", &memory_pressure_path);
-                                if (r < 0) {
-                                        *exit_status = EXIT_MEMORY;
-                                        return log_oom();
-                                }
-
-                                r = chmod_and_chown(memory_pressure_path, 0644, uid, gid);
-                                if (r < 0) {
-                                        log_unit_full_errno(unit, r == -ENOENT || ERRNO_IS_PRIVILEGE(r) ? LOG_DEBUG : LOG_WARNING, r,
-                                                            "Failed to adjust ownership of '%s', ignoring: %m", memory_pressure_path);
-                                        memory_pressure_path = mfree(memory_pressure_path);
-                                }
-                        } else if (cgroup_context->memory_pressure_watch == CGROUP_PRESSURE_WATCH_OFF) {
-                                memory_pressure_path = strdup("/dev/null"); /* /dev/null is explicit indicator for turning of memory pressure watch */
-                                if (!memory_pressure_path) {
-                                        *exit_status = EXIT_MEMORY;
-                                        return log_oom();
-                                }
-                        }
-                }
-        }
-
-        needs_mount_namespace = exec_needs_mount_namespace(context, params, runtime);
-
-        for (ExecDirectoryType dt = 0; dt < _EXEC_DIRECTORY_TYPE_MAX; dt++) {
-                r = setup_exec_directory(unit, context, params, uid, gid, dt, needs_mount_namespace, exit_status);
-                if (r < 0)
-                        return log_unit_error_errno(unit, r, "Failed to set up special execution directory in %s: %m", params->prefix[dt]);
-        }
-
-        if (FLAGS_SET(params->flags, EXEC_WRITE_CREDENTIALS)) {
-                r = exec_setup_credentials(context, params, unit->id, uid, gid);
-                if (r < 0) {
-                        *exit_status = EXIT_CREDENTIALS;
-                        return log_unit_error_errno(unit, r, "Failed to set up credentials: %m");
-                }
-        }
-
-        r = build_environment(
-                        unit,
-                        context,
-                        params,
-                        cgroup_context,
-                        n_fds,
-                        fdnames,
-                        home,
-                        username,
-                        shell,
-                        journal_stream_dev,
-                        journal_stream_ino,
-                        memory_pressure_path,
-                        &our_env);
-        if (r < 0) {
-                *exit_status = EXIT_MEMORY;
-                return log_oom();
-        }
-
-        r = build_pass_environment(context, &pass_env);
-        if (r < 0) {
-                *exit_status = EXIT_MEMORY;
-                return log_oom();
-        }
-
-        /* The $PATH variable is set to the default path in params->environment. However, this is overridden
-         * if user-specified fields have $PATH set. The intention is to also override $PATH if the unit does
-         * not specify PATH but the unit has ExecSearchPath. */
-        if (!strv_isempty(context->exec_search_path)) {
-                _cleanup_free_ char *joined = NULL;
-
-                joined = strv_join(context->exec_search_path, ":");
-                if (!joined) {
-                        *exit_status = EXIT_MEMORY;
-                        return log_oom();
-                }
-
-                r = strv_env_assign(&joined_exec_search_path, "PATH", joined);
-                if (r < 0) {
-                        *exit_status = EXIT_MEMORY;
-                        return log_oom();
-                }
-        }
-
-        accum_env = strv_env_merge(params->environment,
-                                   our_env,
-                                   joined_exec_search_path,
-                                   pass_env,
-                                   context->environment,
-                                   files_env);
-        if (!accum_env) {
-                *exit_status = EXIT_MEMORY;
-                return log_oom();
-        }
-        accum_env = strv_env_clean(accum_env);
-
-        (void) umask(context->umask);
-
-        r = setup_keyring(unit, context, params, uid, gid);
-        if (r < 0) {
-                *exit_status = EXIT_KEYRING;
-                return log_unit_error_errno(unit, r, "Failed to set up kernel keyring: %m");
-        }
-
-        /* We need sandboxing if the caller asked us to apply it and the command isn't explicitly excepted
-         * from it. */
-        needs_sandboxing = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & EXEC_COMMAND_FULLY_PRIVILEGED);
-
-        /* We need the ambient capability hack, if the caller asked us to apply it and the command is marked
-         * for it, and the kernel doesn't actually support ambient caps. */
-        needs_ambient_hack = (params->flags & EXEC_APPLY_SANDBOXING) && (command->flags & EXEC_COMMAND_AMBIENT_MAGIC) && !ambient_capabilities_supported();
-
-        /* We need setresuid() if the caller asked us to apply sandboxing and the command isn't explicitly
-         * excepted from either whole sandboxing or just setresuid() itself, and the ambient hack is not
-         * desired. */
-        if (needs_ambient_hack)
-                needs_setuid = false;
-        else
-                needs_setuid = (params->flags & EXEC_APPLY_SANDBOXING) && !(command->flags & (EXEC_COMMAND_FULLY_PRIVILEGED|EXEC_COMMAND_NO_SETUID));
-
-        uint64_t capability_ambient_set = context->capability_ambient_set;
-
-        if (needs_sandboxing) {
-                /* MAC enablement checks need to be done before a new mount ns is created, as they rely on
-                 * /sys being present. The actual MAC context application will happen later, as late as
-                 * possible, to avoid impacting our own code paths. */
-
-#if HAVE_SELINUX
-                use_selinux = mac_selinux_use();
-#endif
-#if ENABLE_SMACK
-                use_smack = mac_smack_use();
-#endif
-#if HAVE_APPARMOR
-                use_apparmor = mac_apparmor_use();
-#endif
-        }
-
-        if (needs_sandboxing) {
-                int which_failed;
-
-                /* Let's set the resource limits before we call into PAM, so that pam_limits wins over what
-                 * is set here. (See below.) */
-
-                r = setrlimit_closest_all((const struct rlimit* const *) context->rlimit, &which_failed);
-                if (r < 0) {
-                        *exit_status = EXIT_LIMITS;
-                        return log_unit_error_errno(unit, r, "Failed to adjust resource limit RLIMIT_%s: %m", rlimit_to_string(which_failed));
-                }
-        }
-
-        if (needs_setuid && context->pam_name && username) {
-                /* Let's call into PAM after we set up our own idea of resource limits to that pam_limits
-                 * wins here. (See above.) */
-
-                /* All fds passed in the fds array will be closed in the pam child process. */
-                r = setup_pam(context->pam_name, username, uid, gid, context->tty_path, &accum_env, fds, n_fds);
-                if (r < 0) {
-                        *exit_status = EXIT_PAM;
-                        return log_unit_error_errno(unit, r, "Failed to set up PAM session: %m");
-                }
-
-                if (ambient_capabilities_supported()) {
-                        uint64_t ambient_after_pam;
-
-                        /* PAM modules might have set some ambient caps. Query them here and merge them into
-                         * the caps we want to set in the end, so that we don't end up unsetting them. */
-                        r = capability_get_ambient(&ambient_after_pam);
-                        if (r < 0) {
-                                *exit_status = EXIT_CAPABILITIES;
-                                return log_unit_error_errno(unit, r, "Failed to query ambient caps: %m");
-                        }
-
-                        capability_ambient_set |= ambient_after_pam;
-                }
-
-                ngids_after_pam = getgroups_alloc(&gids_after_pam);
-                if (ngids_after_pam < 0) {
-                        *exit_status = EXIT_MEMORY;
-                        return log_unit_error_errno(unit, ngids_after_pam, "Failed to obtain groups after setting up PAM: %m");
-                }
-        }
-
-        if (needs_sandboxing && exec_context_need_unprivileged_private_users(context, params)) {
-                /* If we're unprivileged, set up the user namespace first to enable use of the other namespaces.
-                 * Users with CAP_SYS_ADMIN can set up user namespaces last because they will be able to
-                 * set up the all of the other namespaces (i.e. network, mount, UTS) without a user namespace. */
-
-                r = setup_private_users(saved_uid, saved_gid, uid, gid);
-                /* If it was requested explicitly and we can't set it up, fail early. Otherwise, continue and let
-                 * the actual requested operations fail (or silently continue). */
-                if (r < 0 && context->private_users) {
-                        *exit_status = EXIT_USER;
-                        return log_unit_error_errno(unit, r, "Failed to set up user namespacing for unprivileged user: %m");
-                }
-                if (r < 0)
-                        log_unit_info_errno(unit, r, "Failed to set up user namespacing for unprivileged user, ignoring: %m");
-                else
-                        userns_set_up = true;
-        }
-
-        if (exec_needs_network_namespace(context) && runtime && runtime->shared && runtime->shared->netns_storage_socket[0] >= 0) {
-
-                /* Try to enable network namespacing if network namespacing is available and we have
-                 * CAP_NET_ADMIN. We need CAP_NET_ADMIN to be able to configure the loopback device in the
-                 * new network namespace. And if we don't have that, then we could only create a network
-                 * namespace without the ability to set up "lo". Hence gracefully skip things then. */
-                if (ns_type_supported(NAMESPACE_NET) && have_effective_cap(CAP_NET_ADMIN) > 0) {
-                        r = setup_shareable_ns(runtime->shared->netns_storage_socket, CLONE_NEWNET);
-                        if (ERRNO_IS_NEG_PRIVILEGE(r))
-                                log_unit_notice_errno(unit, r,
-                                                      "PrivateNetwork=yes is configured, but network namespace setup not permitted, proceeding without: %m");
-                        else if (r < 0) {
-                                *exit_status = EXIT_NETWORK;
-                                return log_unit_error_errno(unit, r, "Failed to set up network namespacing: %m");
-                        }
-                } else if (context->network_namespace_path) {
-                        *exit_status = EXIT_NETWORK;
-                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
-                                                    "NetworkNamespacePath= is not supported, refusing.");
-                } else
-                        log_unit_notice(unit, "PrivateNetwork=yes is configured, but the kernel does not support or we lack privileges for network namespace, proceeding without.");
-        }
-
-        if (exec_needs_ipc_namespace(context) && runtime && runtime->shared && runtime->shared->ipcns_storage_socket[0] >= 0) {
-
-                if (ns_type_supported(NAMESPACE_IPC)) {
-                        r = setup_shareable_ns(runtime->shared->ipcns_storage_socket, CLONE_NEWIPC);
-                        if (r == -EPERM)
-                                log_unit_warning_errno(unit, r,
-                                                       "PrivateIPC=yes is configured, but IPC namespace setup failed, ignoring: %m");
-                        else if (r < 0) {
-                                *exit_status = EXIT_NAMESPACE;
-                                return log_unit_error_errno(unit, r, "Failed to set up IPC namespacing: %m");
-                        }
-                } else if (context->ipc_namespace_path) {
-                        *exit_status = EXIT_NAMESPACE;
-                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EOPNOTSUPP),
-                                                    "IPCNamespacePath= is not supported, refusing.");
-                } else
-                        log_unit_warning(unit, "PrivateIPC=yes is configured, but the kernel does not support IPC namespaces, ignoring.");
-        }
-
-        if (needs_mount_namespace) {
-                _cleanup_free_ char *error_path = NULL;
-
-                r = apply_mount_namespace(unit, command->flags, context, params, runtime, memory_pressure_path, &error_path);
-                if (r < 0) {
-                        *exit_status = EXIT_NAMESPACE;
-                        return log_unit_error_errno(unit, r, "Failed to set up mount namespacing%s%s: %m",
-                                                    error_path ? ": " : "", strempty(error_path));
-                }
-        }
-
-        if (needs_sandboxing) {
-                r = apply_protect_hostname(unit, context, exit_status);
-                if (r < 0)
-                        return r;
-        }
-
-        if (context->memory_ksm >= 0)
-                if (prctl(PR_SET_MEMORY_MERGE, context->memory_ksm) < 0) {
-                        if (ERRNO_IS_NOT_SUPPORTED(errno))
-                                log_unit_debug_errno(unit, errno, "KSM support not available, ignoring.");
-                        else {
-                                *exit_status = EXIT_KSM;
-                                return log_unit_error_errno(unit, errno, "Failed to set KSM: %m");
-                        }
-                }
-
-        /* Drop groups as early as possible.
-         * This needs to be done after PrivateDevices=y setup as device nodes should be owned by the host's root.
-         * For non-root in a userns, devices will be owned by the user/group before the group change, and nobody. */
-        if (needs_setuid) {
-                _cleanup_free_ gid_t *gids_to_enforce = NULL;
-                int ngids_to_enforce = 0;
-
-                ngids_to_enforce = merge_gid_lists(supplementary_gids,
-                                                   ngids,
-                                                   gids_after_pam,
-                                                   ngids_after_pam,
-                                                   &gids_to_enforce);
-                if (ngids_to_enforce < 0) {
-                        *exit_status = EXIT_MEMORY;
-                        return log_unit_error_errno(unit,
-                                                    ngids_to_enforce,
-                                                    "Failed to merge group lists. Group membership might be incorrect: %m");
-                }
-
-                r = enforce_groups(gid, gids_to_enforce, ngids_to_enforce);
-                if (r < 0) {
-                        *exit_status = EXIT_GROUP;
-                        return log_unit_error_errno(unit, r, "Changing group credentials failed: %m");
-                }
-        }
-
-        /* If the user namespace was not set up above, try to do it now.
-         * It's preferred to set up the user namespace later (after all other namespaces) so as not to be
-         * restricted by rules pertaining to combining user namespaces with other namespaces (e.g. in the
-         * case of mount namespaces being less privileged when the mount point list is copied from a
-         * different user namespace). */
-
-        if (needs_sandboxing && context->private_users && !userns_set_up) {
-                r = setup_private_users(saved_uid, saved_gid, uid, gid);
-                if (r < 0) {
-                        *exit_status = EXIT_USER;
-                        return log_unit_error_errno(unit, r, "Failed to set up user namespacing: %m");
-                }
-        }
-
-        /* Now that the mount namespace has been set up and privileges adjusted, let's look for the thing we
-         * shall execute. */
-
-        _cleanup_free_ char *executable = NULL;
-        _cleanup_close_ int executable_fd = -EBADF;
-        r = find_executable_full(command->path, /* root= */ NULL, context->exec_search_path, false, &executable, &executable_fd);
-        if (r < 0) {
-                if (r != -ENOMEM && (command->flags & EXEC_COMMAND_IGNORE_FAILURE)) {
-                        log_unit_struct_errno(unit, LOG_INFO, r,
-                                              "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
-                                              LOG_UNIT_INVOCATION_ID(unit),
-                                              LOG_UNIT_MESSAGE(unit, "Executable %s missing, skipping: %m",
-                                                               command->path),
-                                              "EXECUTABLE=%s", command->path);
-                        *exit_status = EXIT_SUCCESS;
-                        return 0;
-                }
-
-                *exit_status = EXIT_EXEC;
-                return log_unit_struct_errno(unit, LOG_INFO, r,
-                                             "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
-                                             LOG_UNIT_INVOCATION_ID(unit),
-                                             LOG_UNIT_MESSAGE(unit, "Failed to locate executable %s: %m",
-                                                              command->path),
-                                             "EXECUTABLE=%s", command->path);
-        }
-
-        r = add_shifted_fd(keep_fds, ELEMENTSOF(keep_fds), &n_keep_fds, executable_fd, &executable_fd);
-        if (r < 0) {
-                *exit_status = EXIT_FDS;
-                return log_unit_error_errno(unit, r, "Failed to shift fd and set FD_CLOEXEC: %m");
-        }
-
-#if HAVE_SELINUX
-        if (needs_sandboxing && use_selinux && params->selinux_context_net) {
-                int fd = -EBADF;
-
-                if (socket_fd >= 0)
-                        fd = socket_fd;
-                else if (params->n_socket_fds == 1)
-                        /* If stdin is not connected to a socket but we are triggered by exactly one socket unit then we
-                         * use context from that fd to compute the label. */
-                        fd = params->fds[0];
-
-                if (fd >= 0) {
-                        r = mac_selinux_get_child_mls_label(fd, executable, context->selinux_context, &mac_selinux_context_net);
-                        if (r < 0) {
-                                if (!context->selinux_context_ignore) {
-                                        *exit_status = EXIT_SELINUX_CONTEXT;
-                                        return log_unit_error_errno(unit, r, "Failed to determine SELinux context: %m");
-                                }
-                                log_unit_debug_errno(unit, r, "Failed to determine SELinux context, ignoring: %m");
-                        }
-                }
-        }
-#endif
-
-        /* We repeat the fd closing here, to make sure that nothing is leaked from the PAM modules. Note that
-         * we are more aggressive this time, since we don't need socket_fd and the netns and ipcns fds any
-         * more. We do keep exec_fd however, if we have it, since we need to keep it open until the final
-         * execve(). */
-
-        r = close_all_fds(keep_fds, n_keep_fds);
-        if (r >= 0)
-                r = shift_fds(fds, n_fds);
-        if (r >= 0)
-                r = flags_fds(fds, n_socket_fds, n_fds, context->non_blocking);
-        if (r < 0) {
-                *exit_status = EXIT_FDS;
-                return log_unit_error_errno(unit, r, "Failed to adjust passed file descriptors: %m");
-        }
-
-        /* At this point, the fds we want to pass to the program are all ready and set up, with O_CLOEXEC turned off
-         * and at the right fd numbers. The are no other fds open, with one exception: the exec_fd if it is defined,
-         * and it has O_CLOEXEC set, after all we want it to be closed by the execve(), so that our parent knows we
-         * came this far. */
-
-        secure_bits = context->secure_bits;
-
-        if (needs_sandboxing) {
-                uint64_t bset;
-
-                /* Set the RTPRIO resource limit to 0, but only if nothing else was explicitly requested.
-                 * (Note this is placed after the general resource limit initialization, see above, in order
-                 * to take precedence.) */
-                if (context->restrict_realtime && !context->rlimit[RLIMIT_RTPRIO]) {
-                        if (setrlimit(RLIMIT_RTPRIO, &RLIMIT_MAKE_CONST(0)) < 0) {
-                                *exit_status = EXIT_LIMITS;
-                                return log_unit_error_errno(unit, errno, "Failed to adjust RLIMIT_RTPRIO resource limit: %m");
-                        }
-                }
-
-#if ENABLE_SMACK
-                /* LSM Smack needs the capability CAP_MAC_ADMIN to change the current execution security context of the
-                 * process. This is the latest place before dropping capabilities. Other MAC context are set later. */
-                if (use_smack) {
-                        r = setup_smack(unit->manager, context, executable_fd);
-                        if (r < 0 && !context->smack_process_label_ignore) {
-                                *exit_status = EXIT_SMACK_PROCESS_LABEL;
-                                return log_unit_error_errno(unit, r, "Failed to set SMACK process label: %m");
-                        }
-                }
-#endif
-
-                bset = context->capability_bounding_set;
-                /* If the ambient caps hack is enabled (which means the kernel can't do them, and the user asked for
-                 * our magic fallback), then let's add some extra caps, so that the service can drop privs of its own,
-                 * instead of us doing that */
-                if (needs_ambient_hack)
-                        bset |= (UINT64_C(1) << CAP_SETPCAP) |
-                                (UINT64_C(1) << CAP_SETUID) |
-                                (UINT64_C(1) << CAP_SETGID);
-
-                if (!cap_test_all(bset)) {
-                        r = capability_bounding_set_drop(bset, /* right_now= */ false);
-                        if (r < 0) {
-                                *exit_status = EXIT_CAPABILITIES;
-                                return log_unit_error_errno(unit, r, "Failed to drop capabilities: %m");
-                        }
-                }
-
-                /* Ambient capabilities are cleared during setresuid() (in enforce_user()) even with
-                 * keep-caps set.
-                 *
-                 * To be able to raise the ambient capabilities after setresuid() they have to be added to
-                 * the inherited set and keep caps has to be set (done in enforce_user()).  After setresuid()
-                 * the ambient capabilities can be raised as they are present in the permitted and
-                 * inhertiable set. However it is possible that someone wants to set ambient capabilities
-                 * without changing the user, so we also set the ambient capabilities here.
-                 *
-                 * The requested ambient capabilities are raised in the inheritable set if the second
-                 * argument is true. */
-                if (!needs_ambient_hack) {
-                        r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ true);
-                        if (r < 0) {
-                                *exit_status = EXIT_CAPABILITIES;
-                                return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (before UID change): %m");
-                        }
-                }
-        }
-
-        /* chroot to root directory first, before we lose the ability to chroot */
-        r = apply_root_directory(context, params, runtime, needs_mount_namespace, exit_status);
-        if (r < 0)
-                return log_unit_error_errno(unit, r, "Chrooting to the requested root directory failed: %m");
-
-        if (needs_setuid) {
-                if (uid_is_valid(uid)) {
-                        r = enforce_user(context, uid, capability_ambient_set);
-                        if (r < 0) {
-                                *exit_status = EXIT_USER;
-                                return log_unit_error_errno(unit, r, "Failed to change UID to " UID_FMT ": %m", uid);
-                        }
-
-                        if (!needs_ambient_hack && capability_ambient_set != 0) {
-
-                                /* Raise the ambient capabilities after user change. */
-                                r = capability_ambient_set_apply(capability_ambient_set, /* also_inherit= */ false);
-                                if (r < 0) {
-                                        *exit_status = EXIT_CAPABILITIES;
-                                        return log_unit_error_errno(unit, r, "Failed to apply ambient capabilities (after UID change): %m");
-                                }
-                        }
-                }
-        }
-
-        /* Apply working directory here, because the working directory might be on NFS and only the user running
-         * this service might have the correct privilege to change to the working directory */
-        r = apply_working_directory(context, params, runtime, home, exit_status);
-        if (r < 0)
-                return log_unit_error_errno(unit, r, "Changing to the requested working directory failed: %m");
-
-        if (needs_sandboxing) {
-                /* Apply other MAC contexts late, but before seccomp syscall filtering, as those should really be last to
-                 * influence our own codepaths as little as possible. Moreover, applying MAC contexts usually requires
-                 * syscalls that are subject to seccomp filtering, hence should probably be applied before the syscalls
-                 * are restricted. */
-
-#if HAVE_SELINUX
-                if (use_selinux) {
-                        char *exec_context = mac_selinux_context_net ?: context->selinux_context;
-
-                        if (exec_context) {
-                                r = setexeccon(exec_context);
-                                if (r < 0) {
-                                        if (!context->selinux_context_ignore) {
-                                                *exit_status = EXIT_SELINUX_CONTEXT;
-                                                return log_unit_error_errno(unit, r, "Failed to change SELinux context to %s: %m", exec_context);
-                                        }
-                                        log_unit_debug_errno(unit, r, "Failed to change SELinux context to %s, ignoring: %m", exec_context);
-                                }
-                        }
-                }
-#endif
 
-#if HAVE_APPARMOR
-                if (use_apparmor && context->apparmor_profile) {
-                        r = aa_change_onexec(context->apparmor_profile);
-                        if (r < 0 && !context->apparmor_profile_ignore) {
-                                *exit_status = EXIT_APPARMOR_PROFILE;
-                                return log_unit_error_errno(unit, errno, "Failed to prepare AppArmor profile change to %s: %m", context->apparmor_profile);
-                        }
-                }
-#endif
+        return context->private_ipc || context->ipc_namespace_path;
+}
 
-                /* PR_GET_SECUREBITS is not privileged, while PR_SET_SECUREBITS is. So to suppress potential
-                 * EPERMs we'll try not to call PR_SET_SECUREBITS unless necessary. Setting securebits
-                 * requires CAP_SETPCAP. */
-                if (prctl(PR_GET_SECUREBITS) != secure_bits) {
-                        /* CAP_SETPCAP is required to set securebits. This capability is raised into the
-                         * effective set here.
-                         *
-                         * The effective set is overwritten during execve() with the following values:
-                         *
-                         * - ambient set (for non-root processes)
-                         *
-                         * - (inheritable | bounding) set for root processes)
-                         *
-                         * Hence there is no security impact to raise it in the effective set before execve
-                         */
-                        r = capability_gain_cap_setpcap(/* return_caps= */ NULL);
-                        if (r < 0) {
-                                *exit_status = EXIT_CAPABILITIES;
-                                return log_unit_error_errno(unit, r, "Failed to gain CAP_SETPCAP for setting secure bits");
-                        }
-                        if (prctl(PR_SET_SECUREBITS, secure_bits) < 0) {
-                                *exit_status = EXIT_SECUREBITS;
-                                return log_unit_error_errno(unit, errno, "Failed to set process secure bits: %m");
-                        }
-                }
+bool exec_needs_mount_namespace(
+                const ExecContext *context,
+                const ExecParameters *params,
+                const ExecRuntime *runtime) {
 
-                if (context_has_no_new_privileges(context))
-                        if (prctl(PR_SET_NO_NEW_PRIVS, 1, 0, 0, 0) < 0) {
-                                *exit_status = EXIT_NO_NEW_PRIVILEGES;
-                                return log_unit_error_errno(unit, errno, "Failed to disable new privileges: %m");
-                        }
+        assert(context);
 
-#if HAVE_SECCOMP
-                r = apply_address_families(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_ADDRESS_FAMILIES;
-                        return log_unit_error_errno(unit, r, "Failed to restrict address families: %m");
-                }
+        if (context->root_image)
+                return true;
 
-                r = apply_memory_deny_write_execute(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to disable writing to executable memory: %m");
-                }
+        if (!strv_isempty(context->read_write_paths) ||
+            !strv_isempty(context->read_only_paths) ||
+            !strv_isempty(context->inaccessible_paths) ||
+            !strv_isempty(context->exec_paths) ||
+            !strv_isempty(context->no_exec_paths))
+                return true;
 
-                r = apply_restrict_realtime(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to apply realtime restrictions: %m");
-                }
+        if (context->n_bind_mounts > 0)
+                return true;
 
-                r = apply_restrict_suid_sgid(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to apply SUID/SGID restrictions: %m");
-                }
+        if (context->n_temporary_filesystems > 0)
+                return true;
 
-                r = apply_restrict_namespaces(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to apply namespace restrictions: %m");
-                }
+        if (context->n_mount_images > 0)
+                return true;
 
-                r = apply_protect_sysctl(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to apply sysctl restrictions: %m");
-                }
+        if (context->n_extension_images > 0)
+                return true;
 
-                r = apply_protect_kernel_modules(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to apply module loading restrictions: %m");
-                }
+        if (!strv_isempty(context->extension_directories))
+                return true;
 
-                r = apply_protect_kernel_logs(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to apply kernel log restrictions: %m");
-                }
+        if (!IN_SET(context->mount_propagation_flag, 0, MS_SHARED))
+                return true;
 
-                r = apply_protect_clock(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to apply clock restrictions: %m");
-                }
+        if (context->private_tmp && runtime && runtime->shared && (runtime->shared->tmp_dir || runtime->shared->var_tmp_dir))
+                return true;
 
-                r = apply_private_devices(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to set up private devices: %m");
-                }
+        if (context->private_devices ||
+            context->private_mounts > 0 ||
+            (context->private_mounts < 0 && exec_needs_network_namespace(context)) ||
+            context->protect_system != PROTECT_SYSTEM_NO ||
+            context->protect_home != PROTECT_HOME_NO ||
+            context->protect_kernel_tunables ||
+            context->protect_kernel_modules ||
+            context->protect_kernel_logs ||
+            context->protect_control_groups ||
+            context->protect_proc != PROTECT_PROC_DEFAULT ||
+            context->proc_subset != PROC_SUBSET_ALL ||
+            exec_needs_ipc_namespace(context))
+                return true;
 
-                r = apply_syscall_archs(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to apply syscall architecture restrictions: %m");
-                }
+        if (context->root_directory) {
+                if (exec_context_get_effective_mount_apivfs(context))
+                        return true;
 
-                r = apply_lock_personality(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to lock personalities: %m");
-                }
+                for (ExecDirectoryType t = 0; t < _EXEC_DIRECTORY_TYPE_MAX; t++) {
+                        if (params && !params->prefix[t])
+                                continue;
 
-                r = apply_syscall_log(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to apply system call log filters: %m");
+                        if (context->directories[t].n_items > 0)
+                                return true;
                 }
+        }
 
-                /* This really should remain the last step before the execve(), to make sure our own code is unaffected
-                 * by the filter as little as possible. */
-                r = apply_syscall_filter(unit, context, needs_ambient_hack);
-                if (r < 0) {
-                        *exit_status = EXIT_SECCOMP;
-                        return log_unit_error_errno(unit, r, "Failed to apply system call filters: %m");
-                }
-#endif
+        if (context->dynamic_user &&
+            (context->directories[EXEC_DIRECTORY_STATE].n_items > 0 ||
+             context->directories[EXEC_DIRECTORY_CACHE].n_items > 0 ||
+             context->directories[EXEC_DIRECTORY_LOGS].n_items > 0))
+                return true;
 
-#if HAVE_LIBBPF
-                r = apply_restrict_filesystems(unit, context);
-                if (r < 0) {
-                        *exit_status = EXIT_BPF;
-                        return log_unit_error_errno(unit, r, "Failed to restrict filesystems: %m");
-                }
-#endif
+        if (context->log_namespace)
+                return true;
 
-        }
+        return false;
+}
 
-        if (!strv_isempty(context->unset_environment)) {
-                char **ee = NULL;
+bool exec_directory_is_private(const ExecContext *context, ExecDirectoryType type) {
+        assert(context);
 
-                ee = strv_env_delete(accum_env, 1, context->unset_environment);
-                if (!ee) {
-                        *exit_status = EXIT_MEMORY;
-                        return log_oom();
-                }
+        if (!context->dynamic_user)
+                return false;
 
-                strv_free_and_replace(accum_env, ee);
-        }
+        if (type == EXEC_DIRECTORY_CONFIGURATION)
+                return false;
 
-        if (!FLAGS_SET(command->flags, EXEC_COMMAND_NO_ENV_EXPAND)) {
-                _cleanup_strv_free_ char **unset_variables = NULL, **bad_variables = NULL;
+        if (type == EXEC_DIRECTORY_RUNTIME && context->runtime_directory_preserve_mode == EXEC_PRESERVE_NO)
+                return false;
 
-                r = replace_env_argv(command->argv, accum_env, &replaced_argv, &unset_variables, &bad_variables);
-                if (r < 0) {
-                        *exit_status = EXIT_MEMORY;
-                        return log_unit_error_errno(unit, r, "Failed to replace environment variables: %m");
-                }
-                final_argv = replaced_argv;
+        return true;
+}
 
-                if (!strv_isempty(unset_variables)) {
-                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
-                        log_unit_warning(unit, "Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
-                }
+int exec_params_get_cgroup_path(
+                const ExecParameters *params,
+                const CGroupContext *c,
+                char **ret) {
 
-                if (!strv_isempty(bad_variables)) {
-                        _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
-                        log_unit_warning(unit, "Invalid environment variable name evaluates to an empty string: %s", strna(jb));;
-                }
-        } else
-                final_argv = command->argv;
+        const char *subgroup = NULL;
+        char *p;
 
-        log_command_line(unit, "Executing", executable, final_argv);
+        assert(params);
+        assert(ret);
 
-        if (exec_fd >= 0) {
-                uint8_t hot = 1;
+        if (!params->cgroup_path)
+                return -EINVAL;
 
-                /* We have finished with all our initializations. Let's now let the manager know that. From this point
-                 * on, if the manager sees POLLHUP on the exec_fd, then execve() was successful. */
+        /* If we are called for a unit where cgroup delegation is on, and the payload created its own populated
+         * subcgroup (which we expect it to do, after all it asked for delegation), then we cannot place the control
+         * processes started after the main unit's process in the unit's main cgroup because it is now an inner one,
+         * and inner cgroups may not contain processes. Hence, if delegation is on, and this is a control process,
+         * let's use ".control" as subcgroup instead. Note that we do so only for ExecStartPost=, ExecReload=,
+         * ExecStop=, ExecStopPost=, i.e. for the commands where the main process is already forked. For ExecStartPre=
+         * this is not necessary, the cgroup is still empty. We distinguish these cases with the EXEC_CONTROL_CGROUP
+         * flag, which is only passed for the former statements, not for the latter. */
 
-                if (write(exec_fd, &hot, sizeof(hot)) < 0) {
-                        *exit_status = EXIT_EXEC;
-                        return log_unit_error_errno(unit, errno, "Failed to enable exec_fd: %m");
-                }
+        if (FLAGS_SET(params->flags, EXEC_CGROUP_DELEGATE) && (FLAGS_SET(params->flags, EXEC_CONTROL_CGROUP) || c->delegate_subgroup)) {
+                if (FLAGS_SET(params->flags, EXEC_IS_CONTROL))
+                        subgroup = ".control";
+                else
+                        subgroup = c->delegate_subgroup;
         }
 
-        r = fexecve_or_execve(executable_fd, executable, final_argv, accum_env);
+        if (subgroup)
+                p = path_join(params->cgroup_path, subgroup);
+        else
+                p = strdup(params->cgroup_path);
+        if (!p)
+                return -ENOMEM;
+
+        *ret = p;
+        return !!subgroup;
+}
 
-        if (exec_fd >= 0) {
-                uint8_t hot = 0;
+bool exec_context_get_cpu_affinity_from_numa(const ExecContext *c) {
+        assert(c);
 
-                /* The execve() failed. This means the exec_fd is still open. Which means we need to tell the manager
-                 * that POLLHUP on it no longer means execve() succeeded. */
+        return c->cpu_affinity_from_numa;
+}
 
-                if (write(exec_fd, &hot, sizeof(hot)) < 0) {
-                        *exit_status = EXIT_EXEC;
-                        return log_unit_error_errno(unit, errno, "Failed to disable exec_fd: %m");
-                }
-        }
+static void log_command_line(Unit *unit, const char *msg, const char *executable, char **argv) {
+        assert(unit);
+        assert(msg);
+        assert(executable);
+
+        if (!DEBUG_LOGGING)
+                return;
+
+        _cleanup_free_ char *cmdline = quote_command_line(argv, SHELL_ESCAPE_EMPTY);
 
-        *exit_status = EXIT_EXEC;
-        return log_unit_error_errno(unit, r, "Failed to execute %s: %m", executable);
+        log_unit_struct(unit, LOG_DEBUG,
+                        "EXECUTABLE=%s", executable,
+                        LOG_UNIT_MESSAGE(unit, "%s: %s", msg, strnull(cmdline)),
+                        LOG_UNIT_INVOCATION_ID(unit));
 }
 
 static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***l);
-static int exec_context_named_iofds(const ExecContext *c, const ExecParameters *p, int named_iofds[static 3]);
 
 int exec_spawn(Unit *unit,
                ExecCommand *command,
                const ExecContext *context,
-               const ExecParameters *params,
+               ExecParameters *params,
                ExecRuntime *runtime,
                const CGroupContext *cgroup_context,
                pid_t *ret) {
 
-        int socket_fd, r, named_iofds[3] = { -1, -1, -1 }, *fds = NULL;
-        _cleanup_free_ char *subcgroup_path = NULL;
-        _cleanup_strv_free_ char **files_env = NULL;
-        size_t n_storage_fds = 0, n_socket_fds = 0;
+        char serialization_fd_number[DECIMAL_STR_MAX(int) + 1];
+        _cleanup_free_ char *subcgroup_path = NULL, *log_level = NULL, *executor_path = NULL;
+        _cleanup_fdset_free_ FDSet *fdset = NULL;
+        _cleanup_fclose_ FILE *f = NULL;
         pid_t pid;
+        int r;
 
         assert(unit);
+        assert(unit->manager);
+        assert(unit->manager->executor_fd >= 0);
         assert(command);
         assert(context);
         assert(ret);
         assert(params);
         assert(params->fds || (params->n_socket_fds + params->n_storage_fds <= 0));
+        assert(!params->files_env); /* We fill this field, ensure it comes NULL-initialized to us */
 
         LOG_CONTEXT_PUSH_UNIT(unit);
 
-        if (context->std_input == EXEC_INPUT_SOCKET ||
-            context->std_output == EXEC_OUTPUT_SOCKET ||
-            context->std_error == EXEC_OUTPUT_SOCKET) {
-
-                if (params->n_socket_fds > 1)
-                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got more than one socket.");
-
-                if (params->n_socket_fds == 0)
-                        return log_unit_error_errno(unit, SYNTHETIC_ERRNO(EINVAL), "Got no socket.");
-
-                socket_fd = params->fds[0];
-        } else {
-                socket_fd = -EBADF;
-                fds = params->fds;
-                n_socket_fds = params->n_socket_fds;
-                n_storage_fds = params->n_storage_fds;
-        }
-
-        r = exec_context_named_iofds(context, params, named_iofds);
-        if (r < 0)
-                return log_unit_error_errno(unit, r, "Failed to load a named file descriptor: %m");
-
-        r = exec_context_load_environment(unit, context, &files_env);
+        r = exec_context_load_environment(unit, context, &params->files_env);
         if (r < 0)
                 return log_unit_error_errno(unit, r, "Failed to load environment files: %m");
 
@@ -5194,7 +373,7 @@ int exec_spawn(Unit *unit,
         log_command_line(unit, "About to execute", command->path, command->argv);
 
         if (params->cgroup_path) {
-                r = exec_parameters_get_cgroup_path(params, cgroup_context, &subcgroup_path);
+                r = exec_params_get_cgroup_path(params, cgroup_context, &subcgroup_path);
                 if (r < 0)
                         return log_unit_error_errno(unit, r, "Failed to acquire subcgroup path: %m");
                 if (r > 0) {
@@ -5207,43 +386,56 @@ int exec_spawn(Unit *unit,
                 }
         }
 
-        pid = fork();
-        if (pid < 0)
-                return log_unit_error_errno(unit, errno, "Failed to fork: %m");
-
-        if (pid == 0) {
-                int exit_status;
-
-                r = exec_child(unit,
-                               command,
-                               context,
-                               params,
-                               runtime,
-                               cgroup_context,
-                               socket_fd,
-                               named_iofds,
-                               fds,
-                               n_socket_fds,
-                               n_storage_fds,
-                               files_env,
-                               unit->manager->user_lookup_fds[1],
-                               &exit_status);
+        /* In order to avoid copy-on-write traps and OOM-kills when pid1's memory.current is above the
+         * child's memory.max, serialize all the state needed to start the unit, and pass it to the
+         * systemd-executor binary. clone() with CLONE_VM + CLONE_VFORK will pause the parent until the exec
+         * and ensure all memory is shared. The child immediately execs the new binary so the delay should
+         * be minimal. Once glibc provides a clone3 wrapper we can switch to that, and clone directly in the
+         * target cgroup. */
 
-                if (r < 0) {
-                        const char *status = ASSERT_PTR(
-                                        exit_status_to_string(exit_status, EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD));
-
-                        log_unit_struct_errno(unit, LOG_ERR, r,
-                                              "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
-                                              LOG_UNIT_INVOCATION_ID(unit),
-                                              LOG_UNIT_MESSAGE(unit, "Failed at step %s spawning %s: %m",
-                                                               status, command->path),
-                                              "EXECUTABLE=%s", command->path);
-                } else
-                        assert(exit_status == EXIT_SUCCESS);
-
-                _exit(exit_status);
-        }
+        r = open_serialization_file("sd-executor-state", &f);
+        if (r < 0)
+                return log_unit_error_errno(unit, r, "Failed to open serialization stream: %m");
+
+        fdset = fdset_new();
+        if (!fdset)
+                return log_oom();
+
+        r = exec_serialize_invocation(f, fdset, context, command, params, runtime, cgroup_context);
+        if (r < 0)
+                return log_unit_error_errno(unit, r, "Failed to serialize parameters: %m");
+
+        if (fseeko(f, 0, SEEK_SET) == (off_t) -1)
+                return log_unit_error_errno(unit, errno, "Failed to reseek on serialization stream: %m");
+
+        r = fd_cloexec(fileno(f), false);
+        if (r < 0)
+                return log_unit_error_errno(unit, r, "Failed to set O_CLOEXEC on serialization fd: %m");
+
+        r = fdset_cloexec(fdset, false);
+        if (r < 0)
+                return log_unit_error_errno(unit, r, "Failed to set O_CLOEXEC on serialized fds: %m");
+
+        r = log_level_to_string_alloc(log_get_max_level(), &log_level);
+        if (r < 0)
+                return log_unit_error_errno(unit, r, "Failed to convert log level to string: %m");
+
+        r = fd_get_path(unit->manager->executor_fd, &executor_path);
+        if (r < 0)
+                return log_unit_error_errno(unit, r, "Failed to get executor path from fd: %m");
+
+        xsprintf(serialization_fd_number, "%i", fileno(f));
+
+        /* The executor binary is pinned, to avoid compatibility problems during upgrades. */
+        r = posix_spawn_wrapper(FORMAT_PROC_FD_PATH(unit->manager->executor_fd),
+                        STRV_MAKE(executor_path,
+                                  "--deserialize", serialization_fd_number,
+                                  "--log-level", log_level,
+                                  "--log-target", log_target_to_string(manager_get_executor_log_target(unit->manager))),
+                        environ,
+                        &pid);
+        if (r < 0)
+                return log_unit_error_errno(unit, r, "Failed to spawn executor: %m");
 
         log_unit_debug(unit, "Forked %s as "PID_FMT, command->path, pid);
 
@@ -5262,6 +454,9 @@ int exec_spawn(Unit *unit,
 void exec_context_init(ExecContext *c) {
         assert(c);
 
+        /* When initializing a bool member to 'true', make sure to serialize in execute-serialize.c using
+         * serialize_bool() instead of serialize_bool_elide(). */
+
         *c = (ExecContext) {
                 .umask = 0022,
                 .ioprio = IOPRIO_DEFAULT_CLASS_AND_PRIO,
@@ -5442,7 +637,7 @@ int exec_context_destroy_mount_ns_dir(Unit *u) {
         return 0;
 }
 
-static void exec_command_done(ExecCommand *c) {
+void exec_command_done(ExecCommand *c) {
         assert(c);
 
         c->path = mfree(c->path);
@@ -5520,57 +715,6 @@ const char* exec_context_fdname(const ExecContext *c, int fd_index) {
         }
 }
 
-static int exec_context_named_iofds(
-                const ExecContext *c,
-                const ExecParameters *p,
-                int named_iofds[static 3]) {
-
-        size_t targets;
-        const char* stdio_fdname[3];
-        size_t n_fds;
-
-        assert(c);
-        assert(p);
-        assert(named_iofds);
-
-        targets = (c->std_input == EXEC_INPUT_NAMED_FD) +
-                  (c->std_output == EXEC_OUTPUT_NAMED_FD) +
-                  (c->std_error == EXEC_OUTPUT_NAMED_FD);
-
-        for (size_t i = 0; i < 3; i++)
-                stdio_fdname[i] = exec_context_fdname(c, i);
-
-        n_fds = p->n_storage_fds + p->n_socket_fds;
-
-        for (size_t i = 0; i < n_fds  && targets > 0; i++)
-                if (named_iofds[STDIN_FILENO] < 0 &&
-                    c->std_input == EXEC_INPUT_NAMED_FD &&
-                    stdio_fdname[STDIN_FILENO] &&
-                    streq(p->fd_names[i], stdio_fdname[STDIN_FILENO])) {
-
-                        named_iofds[STDIN_FILENO] = p->fds[i];
-                        targets--;
-
-                } else if (named_iofds[STDOUT_FILENO] < 0 &&
-                           c->std_output == EXEC_OUTPUT_NAMED_FD &&
-                           stdio_fdname[STDOUT_FILENO] &&
-                           streq(p->fd_names[i], stdio_fdname[STDOUT_FILENO])) {
-
-                        named_iofds[STDOUT_FILENO] = p->fds[i];
-                        targets--;
-
-                } else if (named_iofds[STDERR_FILENO] < 0 &&
-                           c->std_error == EXEC_OUTPUT_NAMED_FD &&
-                           stdio_fdname[STDERR_FILENO] &&
-                           streq(p->fd_names[i], stdio_fdname[STDERR_FILENO])) {
-
-                        named_iofds[STDERR_FILENO] = p->fds[i];
-                        targets--;
-                }
-
-        return targets == 0 ? 0 : -ENOENT;
-}
-
 static int exec_context_load_environment(const Unit *unit, const ExecContext *c, char ***ret) {
         _cleanup_strv_free_ char **v = NULL;
         int r;
@@ -5697,6 +841,48 @@ static void strv_dump(FILE* f, const char *prefix, const char *name, char **strv
         }
 }
 
+void exec_params_dump(const ExecParameters *p, FILE* f, const char *prefix) {
+        assert(p);
+        assert(f);
+
+        prefix = strempty(prefix);
+
+        fprintf(f,
+                "%sRuntimeScope: %s\n"
+                "%sExecFlags: %u\n"
+                "%sSELinuxContextNetwork: %s\n"
+                "%sCgroupSupportedMask: %u\n"
+                "%sCgroupPath: %s\n"
+                "%sCrededentialsDirectory: %s\n"
+                "%sEncryptedCredentialsDirectory: %s\n"
+                "%sConfirmSpawn: %s\n"
+                "%sShallConfirmSpawn: %s\n"
+                "%sWatchdogUSec: " USEC_FMT "\n"
+                "%sNotifySocket: %s\n"
+                "%sFallbackSmackProcessLabel: %s\n",
+                prefix, runtime_scope_to_string(p->runtime_scope),
+                prefix, p->flags,
+                prefix, yes_no(p->selinux_context_net),
+                prefix, p->cgroup_supported,
+                prefix, p->cgroup_path,
+                prefix, strempty(p->received_credentials_directory),
+                prefix, strempty(p->received_encrypted_credentials_directory),
+                prefix, strempty(p->confirm_spawn),
+                prefix, yes_no(p->shall_confirm_spawn),
+                prefix, p->watchdog_usec,
+                prefix, strempty(p->notify_socket),
+                prefix, strempty(p->fallback_smack_process_label));
+
+        strv_dump(f, prefix, "FdNames", p->fd_names);
+        strv_dump(f, prefix, "Environment", p->environment);
+        strv_dump(f, prefix, "Prefix", p->prefix);
+
+        LIST_FOREACH(open_files, file, p->open_files)
+                fprintf(f, "%sOpenFile: %s %s", prefix, file->path, open_file_flags_to_string(file->flags));
+
+        strv_dump(f, prefix, "FilesEnv", p->files_env);
+}
+
 void exec_context_dump(const ExecContext *c, FILE* f, const char *prefix) {
         int r;
 
@@ -6516,9 +1702,9 @@ static char *destroy_tree(char *path) {
         return mfree(path);
 }
 
-static ExecSharedRuntime* exec_shared_runtime_free(ExecSharedRuntime *rt) {
+void exec_shared_runtime_done(ExecSharedRuntime *rt) {
         if (!rt)
-                return NULL;
+                return;
 
         if (rt->manager)
                 (void) hashmap_remove(rt->manager->exec_shared_runtime_by_id, rt->id);
@@ -6528,6 +1714,11 @@ static ExecSharedRuntime* exec_shared_runtime_free(ExecSharedRuntime *rt) {
         rt->var_tmp_dir = mfree(rt->var_tmp_dir);
         safe_close_pair(rt->netns_storage_socket);
         safe_close_pair(rt->ipcns_storage_socket);
+}
+
+static ExecSharedRuntime* exec_shared_runtime_free(ExecSharedRuntime *rt) {
+        exec_shared_runtime_done(rt);
+
         return mfree(rt);
 }
 
@@ -6767,7 +1958,7 @@ int exec_shared_runtime_serialize(const Manager *m, FILE *f, FDSet *fds) {
 
 int exec_shared_runtime_deserialize_compat(Unit *u, const char *key, const char *value, FDSet *fds) {
         _cleanup_(exec_shared_runtime_freep) ExecSharedRuntime *rt_create = NULL;
-        ExecSharedRuntime *rt;
+        ExecSharedRuntime *rt = NULL;
         int r;
 
         /* This is for the migration from old (v237 or earlier) deserialization text.
@@ -6786,10 +1977,12 @@ int exec_shared_runtime_deserialize_compat(Unit *u, const char *key, const char
                 return 0;
         }
 
-        if (hashmap_ensure_allocated(&u->manager->exec_shared_runtime_by_id, &string_hash_ops) < 0)
-                return log_oom();
+        if (u->manager) {
+                if (hashmap_ensure_allocated(&u->manager->exec_shared_runtime_by_id, &string_hash_ops) < 0)
+                        return log_oom();
 
-        rt = hashmap_get(u->manager->exec_shared_runtime_by_id, u->id);
+                rt = hashmap_get(u->manager->exec_shared_runtime_by_id, u->id);
+        }
         if (!rt) {
                 if (exec_shared_runtime_allocate(&rt_create, u->id) < 0)
                         return log_oom();
@@ -6831,7 +2024,7 @@ int exec_shared_runtime_deserialize_compat(Unit *u, const char *key, const char
                 return 0;
 
         /* If the object is newly created, then put it to the hashmap which manages ExecSharedRuntime objects. */
-        if (rt_create) {
+        if (rt_create && u->manager) {
                 r = hashmap_put(u->manager->exec_shared_runtime_by_id, rt_create->id, rt_create);
                 if (r < 0) {
                         log_unit_debug_errno(u, r, "Failed to put runtime parameter to manager's storage: %m");
@@ -7051,14 +2244,59 @@ ExecRuntime* exec_runtime_destroy(ExecRuntime *rt) {
         return exec_runtime_free(rt);
 }
 
+void exec_runtime_clear(ExecRuntime *rt) {
+        if (!rt)
+                return;
+
+        safe_close_pair(rt->ephemeral_storage_socket);
+        rt->ephemeral_copy = mfree(rt->ephemeral_copy);
+}
+
 void exec_params_clear(ExecParameters *p) {
         if (!p)
                 return;
 
         p->environment = strv_free(p->environment);
         p->fd_names = strv_free(p->fd_names);
+        p->files_env = strv_free(p->files_env);
         p->fds = mfree(p->fds);
         p->exec_fd = safe_close(p->exec_fd);
+        p->user_lookup_fd = -EBADF;
+        p->bpf_outer_map_fd = -EBADF;
+        p->unit_id = mfree(p->unit_id);
+        p->invocation_id = SD_ID128_NULL;
+        p->invocation_id_string[0] = '\0';
+        p->confirm_spawn = mfree(p->confirm_spawn);
+}
+
+void exec_params_serialized_done(ExecParameters *p) {
+        if (!p)
+                return;
+
+        for (size_t i = 0; p->fds && i < p->n_socket_fds + p->n_storage_fds; i++)
+                p->fds[i] = safe_close(p->fds[i]);
+
+        p->cgroup_path = mfree(p->cgroup_path);
+
+        p->prefix = strv_free(p->prefix);
+        p->received_credentials_directory = mfree(p->received_credentials_directory);
+        p->received_encrypted_credentials_directory = mfree(p->received_encrypted_credentials_directory);
+
+        for (size_t i = 0; p->idle_pipe && i < 4; i++)
+                p->idle_pipe[i] = safe_close(p->idle_pipe[i]);
+        p->idle_pipe = mfree(p->idle_pipe);
+
+        p->stdin_fd = safe_close(p->stdin_fd);
+        p->stdout_fd = safe_close(p->stdout_fd);
+        p->stderr_fd = safe_close(p->stderr_fd);
+
+        p->notify_socket = mfree(p->notify_socket);
+
+        open_file_free_many(&p->open_files);
+
+        p->fallback_smack_process_label = mfree(p->fallback_smack_process_label);
+
+        exec_params_clear(p);
 }
 
 void exec_directory_done(ExecDirectory *d) {
@@ -7251,18 +2489,6 @@ static const char* const exec_resource_type_table[_EXEC_DIRECTORY_TYPE_MAX] = {
 
 DEFINE_STRING_TABLE_LOOKUP(exec_resource_type, ExecDirectoryType);
 
-/* And this table also maps ExecDirectoryType, to the environment variable we pass the selected directory to
- * the service payload in. */
-static const char* const exec_directory_env_name_table[_EXEC_DIRECTORY_TYPE_MAX] = {
-        [EXEC_DIRECTORY_RUNTIME] = "RUNTIME_DIRECTORY",
-        [EXEC_DIRECTORY_STATE] = "STATE_DIRECTORY",
-        [EXEC_DIRECTORY_CACHE] = "CACHE_DIRECTORY",
-        [EXEC_DIRECTORY_LOGS] = "LOGS_DIRECTORY",
-        [EXEC_DIRECTORY_CONFIGURATION] = "CONFIGURATION_DIRECTORY",
-};
-
-DEFINE_PRIVATE_STRING_TABLE_LOOKUP_TO_STRING(exec_directory_env_name, ExecDirectoryType);
-
 static const char* const exec_keyring_mode_table[_EXEC_KEYRING_MODE_MAX] = {
         [EXEC_KEYRING_INHERIT] = "inherit",
         [EXEC_KEYRING_PRIVATE] = "private",
index a68ea37d830450dc7d9db36a06e83ecb747ea13d..81e968487096edc96c4dd57fae0f561af3b6dcdb 100644 (file)
@@ -100,7 +100,7 @@ struct ExecStatus {
 struct ExecCommand {
         char *path;
         char **argv;
-        ExecStatus exec_status;
+        ExecStatus exec_status; /* Note that this is not serialized to sd-executor */
         ExecCommandFlags flags;
         LIST_FIELDS(ExecCommand, command); /* useful for chaining commands */
 };
@@ -420,13 +420,15 @@ struct ExecParameters {
         bool selinux_context_net:1;
 
         CGroupMask cgroup_supported;
-        const char *cgroup_path;
+        char *cgroup_path;
+        uint64_t cgroup_id;
 
         char **prefix;
-        const char *received_credentials_directory;
-        const char *received_encrypted_credentials_directory;
+        char *received_credentials_directory;
+        char *received_encrypted_credentials_directory;
 
-        const char *confirm_spawn;
+        char *confirm_spawn;
+        bool shall_confirm_spawn;
 
         usec_t watchdog_usec;
 
@@ -439,22 +441,45 @@ struct ExecParameters {
         /* An fd that is closed by the execve(), and thus will result in EOF when the execve() is done */
         int exec_fd;
 
-        const char *notify_socket;
+        char *notify_socket;
 
         LIST_HEAD(OpenFile, open_files);
+
+        char *fallback_smack_process_label;
+
+        char **files_env;
+        int user_lookup_fd;
+        int bpf_outer_map_fd;
+
+        /* Used for logging in the executor functions */
+        char *unit_id;
+        sd_id128_t invocation_id;
+        char invocation_id_string[SD_ID128_STRING_MAX];
 };
 
+#define EXEC_PARAMETERS_INIT(_flags)        \
+        (ExecParameters) {                  \
+                .flags = (_flags),          \
+                .stdin_fd         = -EBADF, \
+                .stdout_fd        = -EBADF, \
+                .stderr_fd        = -EBADF, \
+                .exec_fd          = -EBADF, \
+                .bpf_outer_map_fd = -EBADF, \
+                .user_lookup_fd   = -EBADF, \
+        };
+
 #include "unit.h"
 #include "dynamic-user.h"
 
 int exec_spawn(Unit *unit,
                ExecCommand *command,
                const ExecContext *context,
-               const ExecParameters *exec_params,
+               ExecParameters *exec_params,
                ExecRuntime *runtime,
                const CGroupContext *cgroup_context,
                pid_t *ret);
 
+void exec_command_done(ExecCommand *c);
 void exec_command_done_array(ExecCommand *c, size_t n);
 ExecCommand* exec_command_free_list(ExecCommand *c);
 void exec_command_free_array(ExecCommand **c, size_t n);
@@ -487,6 +512,10 @@ void exec_context_revert_tty(ExecContext *c);
 int exec_context_get_clean_directories(ExecContext *c, char **prefix, ExecCleanMask mask, char ***ret);
 int exec_context_get_clean_mask(ExecContext *c, ExecCleanMask *ret);
 
+const char *exec_context_tty_path(const ExecContext *context);
+int exec_context_tty_size(const ExecContext *context, unsigned *ret_rows, unsigned *ret_cols);
+void exec_context_tty_reset(const ExecContext *context, const ExecParameters *p);
+
 void exec_status_start(ExecStatus *s, pid_t pid);
 void exec_status_exit(ExecStatus *s, const ExecContext *context, pid_t pid, int code, int status);
 void exec_status_dump(const ExecStatus *s, FILE *f, const char *prefix);
@@ -500,20 +529,26 @@ DEFINE_TRIVIAL_CLEANUP_FUNC(ExecSharedRuntime*, exec_shared_runtime_unref);
 int exec_shared_runtime_serialize(const Manager *m, FILE *f, FDSet *fds);
 int exec_shared_runtime_deserialize_compat(Unit *u, const char *key, const char *value, FDSet *fds);
 int exec_shared_runtime_deserialize_one(Manager *m, const char *value, FDSet *fds);
+void exec_shared_runtime_done(ExecSharedRuntime *rt);
 void exec_shared_runtime_vacuum(Manager *m);
 
 int exec_runtime_make(const Unit *unit, const ExecContext *context, ExecSharedRuntime *shared, DynamicCreds *creds, ExecRuntime **ret);
 ExecRuntime* exec_runtime_free(ExecRuntime *rt);
 DEFINE_TRIVIAL_CLEANUP_FUNC(ExecRuntime*, exec_runtime_free);
 ExecRuntime* exec_runtime_destroy(ExecRuntime *rt);
+void exec_runtime_clear(ExecRuntime *rt);
 
+int exec_params_get_cgroup_path(const ExecParameters *params, const CGroupContext *c, char **ret);
 void exec_params_clear(ExecParameters *p);
+void exec_params_dump(const ExecParameters *p, FILE* f, const char *prefix);
+void exec_params_serialized_done(ExecParameters *p);
 
 bool exec_context_get_cpu_affinity_from_numa(const ExecContext *c);
 
 void exec_directory_done(ExecDirectory *d);
 int exec_directory_add(ExecDirectory *d, const char *path, const char *symlink);
 void exec_directory_sort(ExecDirectory *d);
+bool exec_directory_is_private(const ExecContext *context, ExecDirectoryType type);
 
 ExecCleanMask exec_clean_mask_from_string(const char *s);
 
@@ -543,3 +578,104 @@ ExecDirectoryType exec_resource_type_from_string(const char *s) _pure_;
 
 bool exec_needs_mount_namespace(const ExecContext *context, const ExecParameters *params, const ExecRuntime *runtime);
 bool exec_needs_network_namespace(const ExecContext *context);
+bool exec_needs_ipc_namespace(const ExecContext *context);
+
+/* These logging macros do the same logging as those in unit.h, but using ExecContext and ExecParameters
+ * instead of the unit object, so that it can be used in the sd-executor context (where the unit object is
+ * not available). */
+
+#define LOG_EXEC_ID_FIELD(ep) \
+        ((ep)->runtime_scope == RUNTIME_SCOPE_USER ? "USER_UNIT=" : "UNIT=")
+#define LOG_EXEC_ID_FIELD_FORMAT(ep) \
+        ((ep)->runtime_scope == RUNTIME_SCOPE_USER ? "USER_UNIT=%s" : "UNIT=%s")
+#define LOG_EXEC_INVOCATION_ID_FIELD(ep) \
+        ((ep)->runtime_scope == RUNTIME_SCOPE_USER ? "USER_INVOCATION_ID=" : "INVOCATION_ID=")
+#define LOG_EXEC_INVOCATION_ID_FIELD_FORMAT(ep) \
+        ((ep)->runtime_scope == RUNTIME_SCOPE_USER ? "USER_INVOCATION_ID=%s" : "INVOCATION_ID=%s")
+
+#define log_exec_full_errno_zerook(ec, ep, level, error, ...)             \
+        ({                                                                \
+                const ExecContext *_c = (ec);                             \
+                const ExecParameters *_p = (ep);                          \
+                const int _l = (level);                                   \
+                bool _do_log = !(log_get_max_level() < LOG_PRI(_l) ||     \
+                        !(_c->log_level_max < 0 ||                        \
+                        _c->log_level_max >= LOG_PRI(_l)));               \
+                LOG_CONTEXT_PUSH_IOV(_c->log_extra_fields,                \
+                                     _c->n_log_extra_fields);             \
+                !_do_log ? -ERRNO_VALUE(error) :                          \
+                        log_object_internal(_l, error, PROJECT_FILE,      \
+                        __LINE__, __func__,                               \
+                        LOG_EXEC_ID_FIELD(_p),                            \
+                        _p->unit_id,                                      \
+                        LOG_EXEC_INVOCATION_ID_FIELD(_p),                 \
+                        _p->invocation_id_string, ##__VA_ARGS__);         \
+        })
+
+#define log_exec_full_errno(ec, ep, level, error, ...)                            \
+        ({                                                                        \
+                int _error = (error);                                             \
+                ASSERT_NON_ZERO(_error);                                          \
+                log_exec_full_errno_zerook(ec, ep, level, _error, ##__VA_ARGS__); \
+        })
+
+#define log_exec_full(ec, ep, level, ...) (void) log_exec_full_errno_zerook(ec, ep, level, 0, __VA_ARGS__)
+
+#define log_exec_debug(ec, ep, ...)   log_exec_full(ec, ep, LOG_DEBUG, __VA_ARGS__)
+#define log_exec_info(ec, ep, ...)    log_exec_full(ec, ep, LOG_INFO, __VA_ARGS__)
+#define log_exec_notice(ec, ep, ...)  log_exec_full(ec, ep, LOG_NOTICE, __VA_ARGS__)
+#define log_exec_warning(ec, ep, ...) log_exec_full(ec, ep, LOG_WARNING, __VA_ARGS__)
+#define log_exec_error(ec, ep, ...)   log_exec_full(ec, ep, LOG_ERR, __VA_ARGS__)
+
+#define log_exec_debug_errno(ec, ep, error, ...)   log_exec_full_errno(ec, ep, LOG_DEBUG, error, __VA_ARGS__)
+#define log_exec_info_errno(ec, ep, error, ...)    log_exec_full_errno(ec, ep, LOG_INFO, error, __VA_ARGS__)
+#define log_exec_notice_errno(ec, ep, error, ...)  log_exec_full_errno(ec, ep, LOG_NOTICE, error, __VA_ARGS__)
+#define log_exec_warning_errno(ec, ep, error, ...) log_exec_full_errno(ec, ep, LOG_WARNING, error, __VA_ARGS__)
+#define log_exec_error_errno(ec, ep, error, ...)   log_exec_full_errno(ec, ep, LOG_ERR, error, __VA_ARGS__)
+
+#define log_exec_struct_errno(ec, ep, level, error, ...)                                                      \
+        ({                                                                                                    \
+                const ExecContext *_c = (ec);                                                                 \
+                const ExecParameters *_p = (ep);                                                              \
+                const int _l = (level);                                                                       \
+                bool _do_log = !(_c->log_level_max < 0 ||                                                     \
+                                 _c->log_level_max >= LOG_PRI(_l));                                           \
+                LOG_CONTEXT_PUSH_IOV(_c->log_extra_fields,                                                    \
+                                     _c->n_log_extra_fields);                                                 \
+                _do_log ?                                                                                     \
+                        log_struct_errno(_l, error, __VA_ARGS__, LOG_EXEC_ID_FIELD_FORMAT(_p), _p->unit_id) : \
+                        -ERRNO_VALUE(error);                            \
+        })
+
+#define log_exec_struct(ec, ep, level, ...) log_exec_struct_errno(ec, ep, level, 0, __VA_ARGS__)
+
+#define log_exec_struct_iovec_errno(ec, ep, level, error, iovec, n_iovec)   \
+        ({                                                                  \
+                const ExecContext *_c = (ec);                               \
+                const ExecParameters *_p = (ep);                            \
+                const int _l = (level);                                     \
+                bool _do_log = !(_c->log_level_max < 0 ||                   \
+                                 _c->log_level_max >= LOG_PRI(_l));         \
+                LOG_CONTEXT_PUSH_IOV(_c->log_extra_fields,                  \
+                                     _c->n_log_extra_fields);               \
+                _do_log ?                                                   \
+                        log_struct_iovec_errno(_l, error, iovec, n_iovec) : \
+                        -ERRNO_VALUE(error);                                \
+        })
+
+#define log_exec_struct_iovec(ec, ep, level, iovec, n_iovec) log_exec_struct_iovec_errno(ec, ep, level, 0, iovec, n_iovec)
+
+/* Like LOG_MESSAGE(), but with the unit name prefixed. */
+#define LOG_EXEC_MESSAGE(ep, fmt, ...) LOG_MESSAGE("%s: " fmt, (ep)->unit_id, ##__VA_ARGS__)
+#define LOG_EXEC_ID(ep) LOG_EXEC_ID_FIELD_FORMAT(ep), (ep)->unit_id
+#define LOG_EXEC_INVOCATION_ID(ep) LOG_EXEC_INVOCATION_ID_FIELD_FORMAT(ep), (ep)->invocation_id_string
+
+#define _LOG_CONTEXT_PUSH_EXEC(ec, ep, p, c)                                                  \
+        const ExecContext *c = (ec);                                                          \
+        const ExecParameters *p = (ep);                                                       \
+        LOG_CONTEXT_PUSH_KEY_VALUE(LOG_EXEC_ID_FIELD(p), p->unit_id);                              \
+        LOG_CONTEXT_PUSH_KEY_VALUE(LOG_EXEC_INVOCATION_ID_FIELD(p), p->invocation_id_string); \
+        LOG_CONTEXT_PUSH_IOV(c->log_extra_fields, c->n_log_extra_fields)
+
+#define LOG_CONTEXT_PUSH_EXEC(ec, ep) \
+        _LOG_CONTEXT_PUSH_EXEC(ec, ep, UNIQ_T(p, UNIQ), UNIQ_T(c, UNIQ))
diff --git a/src/core/executor.c b/src/core/executor.c
new file mode 100644 (file)
index 0000000..93ebad4
--- /dev/null
@@ -0,0 +1,252 @@
+/* SPDX-License-Identifier: LGPL-2.1-or-later */
+
+#include <getopt.h>
+#include <unistd.h>
+
+#include "sd-messages.h"
+
+#include "alloc-util.h"
+#include "build.h"
+#include "exec-invoke.h"
+#include "execute-serialize.h"
+#include "execute.h"
+#include "exit-status.h"
+#include "fdset.h"
+#include "fd-util.h"
+#include "fileio.h"
+#include "getopt-defs.h"
+#include "parse-util.h"
+#include "pretty-print.h"
+#include "static-destruct.h"
+
+static FILE* arg_serialization = NULL;
+
+STATIC_DESTRUCTOR_REGISTER(arg_serialization, fclosep);
+
+static int help(void) {
+        _cleanup_free_ char *link = NULL;
+        int r;
+
+        r = terminal_urlify_man("systemd", "1", &link);
+        if (r < 0)
+                return log_oom();
+
+        printf("%s [OPTIONS...]\n\n"
+               "%sSandbox and execute processes.%s\n\n"
+               "  -h --help                Show this help and exit\n"
+               "     --version             Print version string and exit\n"
+               "     --log-target=TARGET   Set log target (console, journal,\n"
+               "                                           journal-or-kmsg,\n"
+               "                                           kmsg, null)\n"
+               "     --log-level=LEVEL     Set log level (debug, info, notice,\n"
+               "                                          warning, err, crit,\n"
+               "                                          alert, emerg)\n"
+               "     --log-color=BOOL      Highlight important messages\n"
+               "     --log-location=BOOL   Include code location in messages\n"
+               "     --log-time=BOOL       Prefix messages with current time\n"
+               "     --deserialize=FD      Deserialize process config from FD\n"
+               "\nSee the %s for details.\n",
+               program_invocation_short_name,
+               ansi_highlight(),
+               ansi_normal(),
+               link);
+
+        return 0;
+}
+
+static int parse_argv(int argc, char *argv[]) {
+        enum {
+                COMMON_GETOPT_ARGS,
+                ARG_VERSION,
+                ARG_DESERIALIZE,
+        };
+
+        static const struct option options[] = {
+                { "log-level",      required_argument, NULL, ARG_LOG_LEVEL      },
+                { "log-target",     required_argument, NULL, ARG_LOG_TARGET     },
+                { "log-color",      required_argument, NULL, ARG_LOG_COLOR      },
+                { "log-location",   required_argument, NULL, ARG_LOG_LOCATION   },
+                { "log-time",       required_argument, NULL, ARG_LOG_TIME       },
+                { "help",           no_argument,       NULL, 'h'                },
+                { "version",        no_argument,       NULL, ARG_VERSION        },
+                { "deserialize",    required_argument, NULL, ARG_DESERIALIZE    },
+                {}
+        };
+
+        int c, r;
+
+        assert(argc >= 0);
+        assert(argv);
+
+        while ((c = getopt_long(argc, argv, "h", options, NULL)) >= 0)
+                switch (c) {
+                case 'h':
+                        return help();
+
+                case ARG_VERSION:
+                        return version();
+
+                case ARG_LOG_LEVEL:
+                        r = log_set_max_level_from_string(optarg);
+                        if (r < 0)
+                                return log_error_errno(r, "Failed to parse log level \"%s\": %m", optarg);
+
+                        break;
+
+                case ARG_LOG_TARGET:
+                        r = log_set_target_from_string(optarg);
+                        if (r < 0)
+                                return log_error_errno(r, "Failed to parse log target \"%s\": %m", optarg);
+
+                        break;
+
+                case ARG_LOG_COLOR:
+                        r = log_show_color_from_string(optarg);
+                        if (r < 0)
+                                return log_error_errno(
+                                                r,
+                                                "Failed to parse log color setting \"%s\": %m",
+                                                optarg);
+
+                        break;
+
+                case ARG_LOG_LOCATION:
+                        r = log_show_location_from_string(optarg);
+                        if (r < 0)
+                                return log_error_errno(
+                                                r,
+                                                "Failed to parse log location setting \"%s\": %m",
+                                                optarg);
+
+                        break;
+
+                case ARG_LOG_TIME:
+                        r = log_show_time_from_string(optarg);
+                        if (r < 0)
+                                return log_error_errno(
+                                                r,
+                                                "Failed to parse log time setting \"%s\": %m",
+                                                optarg);
+
+                        break;
+
+                case ARG_DESERIALIZE: {
+                        FILE *f;
+                        int fd;
+
+                        fd = parse_fd(optarg);
+                        if (fd < 0)
+                                return log_error_errno(
+                                                fd,
+                                                "Failed to parse serialization fd \"%s\": %m",
+                                                optarg);
+
+                        r = fd_cloexec(fd, /* cloexec= */ true);
+                        if (r < 0)
+                                return log_error_errno(
+                                                r,
+                                                "Failed to set serialization fd \"%s\" to close-on-exec: %m",
+                                                optarg);
+
+                        f = fdopen(fd, "r");
+                        if (!f)
+                                return log_error_errno(errno, "Failed to open serialization fd %d: %m", fd);
+
+                        safe_fclose(arg_serialization);
+                        arg_serialization = f;
+
+                        break;
+                }
+
+                case '?':
+                        return -EINVAL;
+
+                default:
+                        assert_not_reached();
+                }
+
+        if (!arg_serialization)
+                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
+                                       "No serialization fd specified.");
+
+        return 1 /* work to do */;
+}
+
+int main(int argc, char *argv[]) {
+        _cleanup_fdset_free_ FDSet *fdset = NULL;
+        int exit_status = EXIT_SUCCESS, r;
+        _cleanup_(cgroup_context_done) CGroupContext cgroup_context = {};
+        _cleanup_(exec_context_done) ExecContext context = {};
+        _cleanup_(exec_command_done) ExecCommand command = {};
+        _cleanup_(exec_params_serialized_done) ExecParameters params = EXEC_PARAMETERS_INIT(/* flags= */ 0);
+        _cleanup_(exec_shared_runtime_done) ExecSharedRuntime shared = {
+                .netns_storage_socket = PIPE_EBADF,
+                .ipcns_storage_socket = PIPE_EBADF,
+        };
+        _cleanup_(dynamic_creds_done) DynamicCreds dynamic_creds = {};
+        _cleanup_(exec_runtime_clear) ExecRuntime runtime = {
+                .ephemeral_storage_socket = PIPE_EBADF,
+                .shared = &shared,
+                .dynamic_creds = &dynamic_creds,
+        };
+
+        exec_context_init(&context);
+        cgroup_context_init(&cgroup_context);
+
+        /* We might be starting the journal itself, we'll be told by the caller what to do */
+        log_set_always_reopen_console(true);
+        log_set_prohibit_ipc(true);
+        log_setup();
+
+        r = fdset_new_fill(/* filter_cloexec= */ 0, &fdset);
+        if (r < 0)
+                return log_error_errno(r, "Failed to create fd set: %m");
+
+        r = parse_argv(argc, argv);
+        if (r <= 0)
+                return r;
+
+        /* Now try again if we were told it's fine to use a different target */
+        if (log_get_target() != LOG_TARGET_KMSG) {
+                log_set_prohibit_ipc(false);
+                log_open();
+        }
+
+        r = fdset_remove(fdset, fileno(arg_serialization));
+        if (r < 0)
+                return log_error_errno(r, "Failed to remove serialization fd from fd set: %m");
+
+        r = exec_deserialize_invocation(arg_serialization,
+                                        fdset,
+                                        &context,
+                                        &command,
+                                        &params,
+                                        &runtime,
+                                        &cgroup_context);
+        if (r < 0)
+                return log_error_errno(r, "Failed to deserialize: %m");
+
+        arg_serialization = safe_fclose(arg_serialization);
+        fdset = fdset_free(fdset);
+
+        r = exec_invoke(&command,
+                        &context,
+                        &params,
+                        &runtime,
+                        &cgroup_context,
+                        &exit_status);
+        if (r < 0) {
+                const char *status = ASSERT_PTR(
+                                exit_status_to_string(exit_status, EXIT_STATUS_LIBC | EXIT_STATUS_SYSTEMD));
+
+                log_exec_struct_errno(&context, &params, LOG_ERR, r,
+                                      "MESSAGE_ID=" SD_MESSAGE_SPAWN_FAILED_STR,
+                                      LOG_EXEC_INVOCATION_ID(&params),
+                                      LOG_EXEC_MESSAGE(&params, "Failed at step %s spawning %s: %m",
+                                                       status, command.path),
+                                      "EXECUTABLE=%s", command.path);
+        } else
+                assert(exit_status == EXIT_SUCCESS); /* When 'skip' is chosen in the confirm spawn prompt */
+
+        return exit_status;
+}
index cbc89f5737344899371f0f57164bd6547f2747d9..0e4bfa4484918b918e2c417a4f50256071087d66 100644 (file)
@@ -24,7 +24,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
                 log_set_target(LOG_TARGET_NULL);
         }
 
-        assert_se(manager_new(RUNTIME_SCOPE_SYSTEM, MANAGER_TEST_RUN_MINIMAL, &m) >= 0);
+        assert_se(manager_new(RUNTIME_SCOPE_SYSTEM, MANAGER_TEST_RUN_MINIMAL|MANAGER_TEST_DONT_OPEN_EXECUTOR, &m) >= 0);
         /* Set log overrides as well to make it harder for a serialization file
          * to switch log levels/targets during fuzzing */
         manager_override_log_level(m, log_get_max_level());
index a11d6b53b5e4181e37f5d75792e9243d713b28da..7b738062b509d83edbdf7e193fd515d77308d176 100644 (file)
@@ -65,7 +65,7 @@ int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) {
         if (!getenv("SYSTEMD_LOG_LEVEL"))
                 log_set_max_level(LOG_CRIT);
 
-        assert_se(manager_new(RUNTIME_SCOPE_SYSTEM, MANAGER_TEST_RUN_MINIMAL, &m) >= 0);
+        assert_se(manager_new(RUNTIME_SCOPE_SYSTEM, MANAGER_TEST_RUN_MINIMAL|MANAGER_TEST_DONT_OPEN_EXECUTOR, &m) >= 0);
 
         name = strjoina("a.", unit_type_to_string(t));
         assert_se(unit_new_for_name(m, unit_vtable[t]->object_size, name, &u) >= 0);
index 76261a2d8840b3d0e56b47437f17bed4e21c04f7..04393cf11da75ee205050b513f17f7b05469f83a 100644 (file)
 #include "varlink-internal.h"
 
 int manager_open_serialization(Manager *m, FILE **ret_f) {
-        _cleanup_close_ int fd = -EBADF;
-        FILE *f;
-
         assert(ret_f);
 
-        fd = open_serialization_fd("systemd-state");
-        if (fd < 0)
-                return fd;
-
-        f = take_fdopen(&fd, "w+");
-        if (!f)
-                return -errno;
-
-        *ret_f = f;
-        return 0;
+        return open_serialization_file("systemd-state", ret_f);
 }
 
 static bool manager_timestamp_shall_serialize(ManagerTimestamp t) {
@@ -195,7 +183,7 @@ int manager_serialize(
                 if (u->id != t)
                         continue;
 
-                r = unit_serialize(u, f, fds, switching_root);
+                r = unit_serialize_state(u, f, fds, switching_root);
                 if (r < 0)
                         return r;
         }
@@ -222,7 +210,7 @@ static int manager_deserialize_one_unit(Manager *m, const char *name, FILE *f, F
                 return log_notice_errno(r, "Failed to load unit \"%s\", skipping deserialization: %m", name);
         }
 
-        r = unit_deserialize(u, f, fds);
+        r = unit_deserialize_state(u, f, fds);
         if (r < 0) {
                 if (r == -ENOMEM)
                         return r;
@@ -251,7 +239,7 @@ static int manager_deserialize_units(Manager *m, FILE *f, FDSet *fds) {
                 if (r == -ENOMEM)
                         return r;
                 if (r < 0) {
-                        r = unit_deserialize_skip(f);
+                        r = unit_deserialize_state_skip(f);
                         if (r < 0)
                                 return r;
                 }
@@ -507,7 +495,7 @@ int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
                         }
 
                 } else if ((val = startswith(l, "dynamic-user=")))
-                        dynamic_user_deserialize_one(m, val, fds);
+                        dynamic_user_deserialize_one(m, val, fds, NULL);
                 else if ((val = startswith(l, "destroy-ipc-uid=")))
                         manager_deserialize_uid_refs_one(m, val);
                 else if ((val = startswith(l, "destroy-ipc-gid=")))
@@ -520,21 +508,12 @@ int manager_deserialize(Manager *m, FILE *f, FDSet *fds) {
                                 return -ENOMEM;
                 } else if ((val = startswith(l, "varlink-server-socket-address="))) {
                         if (!m->varlink_server && MANAGER_IS_SYSTEM(m)) {
-                                _cleanup_(varlink_server_unrefp) VarlinkServer *s = NULL;
-
-                                r = manager_setup_varlink_server(m, &s);
+                                r = manager_varlink_init(m);
                                 if (r < 0) {
                                         log_warning_errno(r, "Failed to setup varlink server, ignoring: %m");
                                         continue;
                                 }
 
-                                r = varlink_server_attach_event(s, m->event, SD_EVENT_PRIORITY_NORMAL);
-                                if (r < 0) {
-                                        log_warning_errno(r, "Failed to attach varlink connection to event loop, ignoring: %m");
-                                        continue;
-                                }
-
-                                m->varlink_server = TAKE_PTR(s);
                                 deserialize_varlink_sockets = true;
                         }
 
index 9af6fd4184b1992145935b8965277383235cb71e..9307a13a79ffd71785ea3e22b7c77be86f14833a 100644 (file)
@@ -144,6 +144,15 @@ static usec_t manager_watch_jobs_next_time(Manager *m) {
         return usec_add(now(CLOCK_MONOTONIC), timeout);
 }
 
+static bool manager_is_confirm_spawn_disabled(Manager *m) {
+        assert(m);
+
+        if (!m->confirm_spawn)
+                return true;
+
+        return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
+}
+
 static void manager_watch_jobs_in_progress(Manager *m) {
         usec_t next;
         int r;
@@ -912,6 +921,8 @@ int manager_new(RuntimeScope runtime_scope, ManagerTestRunFlags test_run_flags,
                         .interval = 10 * USEC_PER_MINUTE,
                         .burst = 10,
                 },
+
+                .executor_fd = -EBADF,
         };
 
         unit_defaults_init(&m->defaults, runtime_scope);
@@ -1030,6 +1041,42 @@ int manager_new(RuntimeScope runtime_scope, ManagerTestRunFlags test_run_flags,
 
                 if (r < 0 && r != -EEXIST)
                         return r;
+
+                m->executor_fd = open(SYSTEMD_EXECUTOR_BINARY_PATH, O_CLOEXEC|O_PATH);
+                if (m->executor_fd < 0)
+                        return log_warning_errno(errno,
+                                                 "Failed to open executor binary '%s': %m",
+                                                 SYSTEMD_EXECUTOR_BINARY_PATH);
+        } else if (!FLAGS_SET(test_run_flags, MANAGER_TEST_DONT_OPEN_EXECUTOR)) {
+                _cleanup_free_ char *self_exe = NULL, *executor_path = NULL;
+                _cleanup_close_ int self_dir_fd = -EBADF;
+                int level = LOG_DEBUG;
+
+                /* Prefer sd-executor from the same directory as the test, e.g.: when running unit tests from the
+                * build directory. Fallback to working directory and then the installation path. */
+                r = readlink_and_make_absolute("/proc/self/exe", &self_exe);
+                if (r < 0)
+                        return r;
+
+                self_dir_fd = open_parent(self_exe, O_CLOEXEC|O_DIRECTORY, 0);
+                if (self_dir_fd < 0)
+                        return -errno;
+
+                m->executor_fd = openat(self_dir_fd, "systemd-executor", O_CLOEXEC|O_PATH);
+                if (m->executor_fd < 0 && errno == ENOENT)
+                        m->executor_fd = openat(AT_FDCWD, "systemd-executor", O_CLOEXEC|O_PATH);
+                if (m->executor_fd < 0 && errno == ENOENT) {
+                        m->executor_fd = open(SYSTEMD_EXECUTOR_BINARY_PATH, O_CLOEXEC|O_PATH);
+                        level = LOG_WARNING; /* Tests should normally use local builds */
+                }
+                if (m->executor_fd < 0)
+                        return -errno;
+
+                r = fd_get_path(m->executor_fd, &executor_path);
+                if (r < 0)
+                        return r;
+
+                log_full(level, "Using systemd-executor binary from '%s'", executor_path);
         }
 
         /* Note that we do not set up the notify fd here. We do that after deserialization,
@@ -1692,6 +1739,8 @@ Manager* manager_free(Manager *m) {
         lsm_bpf_destroy(m->restrict_fs);
 #endif
 
+        safe_close(m->executor_fd);
+
         return mfree(m);
 }
 
@@ -4430,13 +4479,6 @@ void manager_disable_confirm_spawn(void) {
         (void) touch("/run/systemd/confirm_spawn_disabled");
 }
 
-bool manager_is_confirm_spawn_disabled(Manager *m) {
-        if (!m->confirm_spawn)
-                return true;
-
-        return access("/run/systemd/confirm_spawn_disabled", F_OK) >= 0;
-}
-
 static bool manager_should_show_status(Manager *m, StatusType type) {
         assert(m);
 
@@ -4954,6 +4996,17 @@ void unit_defaults_done(UnitDefaults *defaults) {
         rlimit_free_all(defaults->rlimit);
 }
 
+LogTarget manager_get_executor_log_target(Manager *m) {
+        assert(m);
+
+        /* If journald is not available tell sd-executor to go to kmsg, as it might be starting journald */
+
+        if (manager_journal_is_running(m))
+                return log_get_target();
+
+        return LOG_TARGET_KMSG;
+}
+
 static const char *const manager_state_table[_MANAGER_STATE_MAX] = {
         [MANAGER_INITIALIZING] = "initializing",
         [MANAGER_STARTING]     = "starting",
index 4fa54bb3c1a8418ceb673d72446dcfe81f312abe..6321a353a5a1525ac82d2f7ce724abdb4e98cb67 100644 (file)
@@ -145,6 +145,7 @@ typedef enum ManagerTestRunFlags {
         MANAGER_TEST_RUN_ENV_GENERATORS      = 1 << 2,  /* also run env generators  */
         MANAGER_TEST_RUN_GENERATORS          = 1 << 3,  /* also run unit generators */
         MANAGER_TEST_RUN_IGNORE_DEPENDENCIES = 1 << 4,  /* run while ignoring dependencies */
+        MANAGER_TEST_DONT_OPEN_EXECUTOR      = 1 << 5,  /* avoid trying to load sd-executor */
         MANAGER_TEST_FULL = MANAGER_TEST_RUN_BASIC | MANAGER_TEST_RUN_ENV_GENERATORS | MANAGER_TEST_RUN_GENERATORS,
 } ManagerTestRunFlags;
 
@@ -496,6 +497,10 @@ struct Manager {
 
         /* For NFTSet= */
         FirewallContext *fw_ctx;
+
+        /* Pin the systemd-executor binary, so that it never changes until re-exec, ensuring we don't have
+         * serialization/deserialization compatibility issues during upgrades. */
+        int executor_fd;
 };
 
 static inline usec_t manager_default_timeout_abort_usec(Manager *m) {
@@ -616,7 +621,6 @@ const char *manager_state_to_string(ManagerState m) _const_;
 ManagerState manager_state_from_string(const char *s) _pure_;
 
 const char *manager_get_confirm_spawn(Manager *m);
-bool manager_is_confirm_spawn_disabled(Manager *m);
 void manager_disable_confirm_spawn(void);
 
 const char *manager_timestamp_to_string(ManagerTimestamp m) _const_;
@@ -629,6 +633,8 @@ void manager_override_watchdog(Manager *m, WatchdogType t, usec_t timeout);
 int manager_set_watchdog_pretimeout_governor(Manager *m, const char *governor);
 int manager_override_watchdog_pretimeout_governor(Manager *m, const char *governor);
 
+LogTarget manager_get_executor_log_target(Manager *m);
+
 const char* oom_policy_to_string(OOMPolicy i) _const_;
 OOMPolicy oom_policy_from_string(const char *s) _pure_;
 
index e5b92ce4d909831dbb22f66dc9716e9389ac09c1..44af28a3f32df4e81b40f4c00ae8cb756697fe51 100644 (file)
@@ -36,6 +36,7 @@ libcore_sources = files(
         'emergency-action.c',
         'exec-credential.c',
         'execute.c',
+        'execute-serialize.c',
         'generator-setup.c',
         'ima-setup.c',
         'import-creds.c',
@@ -143,6 +144,11 @@ systemd_sources = files(
         'crash-handler.c',
 )
 
+systemd_executor_sources = files(
+        'executor.c',
+        'exec-invoke.c',
+)
+
 executables += [
         libexec_template + {
                 'name' : 'systemd',
@@ -155,6 +161,22 @@ executables += [
                 ],
                 'dependencies' : libseccomp,
         },
+        libexec_template + {
+                'name' : 'systemd-executor',
+                'public' : true,
+                'sources' : systemd_executor_sources,
+                'include_directories' : core_includes,
+                'link_with' : [
+                        libcore,
+                        libshared,
+                ],
+                'dependencies' : [
+                        libapparmor,
+                        libpam,
+                        libseccomp,
+                        libselinux,
+                ],
+        },
         fuzz_template + {
                 'sources' : files('fuzz-unit-file.c'),
                 'link_with' : [
index 6424c56ed32ba4ef21fb9e813cef16fe32303655..fe04b3d74c9d5dffed87fb9cf55c1c3fed76189f 100644 (file)
@@ -889,13 +889,8 @@ static void mount_dump(Unit *u, FILE *f, const char *prefix) {
 
 static int mount_spawn(Mount *m, ExecCommand *c, PidRef *ret_pid) {
 
-        _cleanup_(exec_params_clear) ExecParameters exec_params = {
-                .flags     = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN,
-                .stdin_fd  = -EBADF,
-                .stdout_fd = -EBADF,
-                .stderr_fd = -EBADF,
-                .exec_fd   = -EBADF,
-        };
+        _cleanup_(exec_params_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(
+                        EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN);
         _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
         pid_t pid;
         int r;
index 00b1a17b4f3b1ae3450ccde62d6cf6c453d092a0..9165a481f53c297e3f7e6f8a63aa10cfa4436b5e 100644 (file)
@@ -1269,9 +1269,8 @@ static int mount_image(
                 const ImagePolicy *image_policy) {
 
         _cleanup_free_ char *host_os_release_id = NULL, *host_os_release_version_id = NULL,
-                            *host_os_release_level = NULL, *extension_name = NULL;
-        _cleanup_strv_free_ char **extension_release = NULL;
-        ImageClass class = IMAGE_SYSEXT;
+                            *host_os_release_sysext_level = NULL, *host_os_release_confext_level = NULL,
+                            *extension_name = NULL;
         int r;
 
         assert(m);
@@ -1281,20 +1280,12 @@ static int mount_image(
                 return log_debug_errno(r, "Failed to extract extension name from %s: %m", mount_entry_source(m));
 
         if (m->mode == EXTENSION_IMAGES) {
-                r = load_extension_release_pairs(mount_entry_source(m), IMAGE_SYSEXT, extension_name, /* relax_extension_release_check= */ false, &extension_release);
-                if (r == -ENOENT) {
-                        r = load_extension_release_pairs(mount_entry_source(m), IMAGE_CONFEXT, extension_name, /* relax_extension_release_check= */ false, &extension_release);
-                        if (r >= 0)
-                                class = IMAGE_CONFEXT;
-                }
-                if (r == -ENOENT)
-                        return r;
-
                 r = parse_os_release(
                                 empty_to_root(root_directory),
                                 "ID", &host_os_release_id,
                                 "VERSION_ID", &host_os_release_version_id,
-                                image_class_info[class].level_env, &host_os_release_level,
+                                image_class_info[IMAGE_SYSEXT].level_env, &host_os_release_sysext_level,
+                                image_class_info[IMAGE_CONFEXT].level_env, &host_os_release_confext_level,
                                 NULL);
                 if (r < 0)
                         return log_debug_errno(r, "Failed to acquire 'os-release' data of OS tree '%s': %m", empty_to_root(root_directory));
@@ -1310,20 +1301,23 @@ static int mount_image(
                         image_policy,
                         host_os_release_id,
                         host_os_release_version_id,
-                        host_os_release_level,
+                        host_os_release_sysext_level,
+                        host_os_release_confext_level,
                         /* required_sysext_scope= */ NULL,
                         /* ret_image= */ NULL);
         if (r == -ENOENT && m->ignore)
                 return 0;
         if (r == -ESTALE && host_os_release_id)
                 return log_error_errno(r,
-                                       "Failed to mount image %s, extension-release metadata does not match the lower layer's: ID=%s%s%s%s%s",
+                                       "Failed to mount image %s, extension-release metadata does not match the lower layer's: ID=%s%s%s%s%s%s%s",
                                        mount_entry_source(m),
                                        host_os_release_id,
                                        host_os_release_version_id ? " VERSION_ID=" : "",
                                        strempty(host_os_release_version_id),
-                                       host_os_release_level ? image_class_info[class].level_env_print : "",
-                                       strempty(host_os_release_level));
+                                       host_os_release_sysext_level ? image_class_info[IMAGE_SYSEXT].level_env_print : "",
+                                       strempty(host_os_release_sysext_level),
+                                       host_os_release_confext_level ? image_class_info[IMAGE_CONFEXT].level_env_print : "",
+                                       strempty(host_os_release_confext_level));
         if (r < 0)
                 return log_debug_errno(r, "Failed to mount image %s on %s: %m", mount_entry_source(m), mount_entry_path(m));
 
@@ -1465,8 +1459,8 @@ static int apply_one_mount(
                         if (r >= 0)
                                 class = IMAGE_CONFEXT;
                 }
-                if (r == -ENOENT)
-                        return r;
+                if (r < 0)
+                        return log_debug_errno(r, "Failed to acquire 'extension-release' data of extension tree %s: %m", mount_entry_source(m));
 
                 r = parse_os_release(
                                 empty_to_root(root_directory),
index 73a678b0cc1d3baad7dfda8970734a40796968f1..b4bd343bc9486160b12ea0b98b9234d59e2966e9 100644 (file)
@@ -1602,13 +1602,7 @@ static int service_spawn_internal(
                 ExecFlags flags,
                 PidRef *ret_pid) {
 
-        _cleanup_(exec_params_clear) ExecParameters exec_params = {
-                .flags     = flags,
-                .stdin_fd  = -EBADF,
-                .stdout_fd = -EBADF,
-                .stderr_fd = -EBADF,
-                .exec_fd   = -EBADF,
-        };
+        _cleanup_(exec_params_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(flags);
         _cleanup_(sd_event_source_unrefp) sd_event_source *exec_fd_source = NULL;
         _cleanup_strv_free_ char **final_env = NULL, **our_env = NULL;
         _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
index 1bbcadc3ba3008b84bcdcedd87cb9f708fb7dcaf..dff4bc42d79a00eed258ef78e29b12fddc9be078 100644 (file)
@@ -1913,13 +1913,8 @@ static int socket_coldplug(Unit *u) {
 
 static int socket_spawn(Socket *s, ExecCommand *c, PidRef *ret_pid) {
 
-        _cleanup_(exec_params_clear) ExecParameters exec_params = {
-                .flags     = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN,
-                .stdin_fd  = -EBADF,
-                .stdout_fd = -EBADF,
-                .stderr_fd = -EBADF,
-                .exec_fd   = -EBADF,
-        };
+        _cleanup_(exec_params_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(
+                        EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN);
         _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
         pid_t pid;
         int r;
index 008c5bbc247a180b6656d6094c85e84306256b46..d0bce8c44bd7fafe5dface80eff48cda9af5d093 100644 (file)
@@ -632,13 +632,8 @@ static void swap_dump(Unit *u, FILE *f, const char *prefix) {
 
 static int swap_spawn(Swap *s, ExecCommand *c, PidRef *ret_pid) {
 
-        _cleanup_(exec_params_clear) ExecParameters exec_params = {
-                .flags     = EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN,
-                .stdin_fd  = -EBADF,
-                .stdout_fd = -EBADF,
-                .stderr_fd = -EBADF,
-                .exec_fd   = -EBADF,
-        };
+        _cleanup_(exec_params_clear) ExecParameters exec_params = EXEC_PARAMETERS_INIT(
+                        EXEC_APPLY_SANDBOXING|EXEC_APPLY_CHROOT|EXEC_APPLY_TTY_STDIN);
         _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
         pid_t pid;
         int r;
index 28510026159066cc24eed8dea607b2fe626ad2e5..cd7f2ee86b64e9a2fe5f14505ad9a12fc55d1851 100644 (file)
@@ -90,7 +90,7 @@ static const char *const io_accounting_metric_field_last[_CGROUP_IO_ACCOUNTING_M
         [CGROUP_IO_WRITE_OPERATIONS] = "io-accounting-write-operations-last",
 };
 
-int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool switching_root) {
+int unit_serialize_state(Unit *u, FILE *f, FDSet *fds, bool switching_root) {
         int r;
 
         assert(u);
@@ -264,7 +264,7 @@ static int unit_deserialize_job(Unit *u, FILE *f) {
                 _deserialize_matched;                                   \
         })
 
-int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
+int unit_deserialize_state(Unit *u, FILE *f, FDSet *fds) {
         int r;
 
         assert(u);
@@ -552,7 +552,7 @@ int unit_deserialize(Unit *u, FILE *f, FDSet *fds) {
         return 0;
 }
 
-int unit_deserialize_skip(FILE *f) {
+int unit_deserialize_state_skip(FILE *f) {
         int r;
         assert(f);
 
index 599d883dece33b8ace6461fa98536e0ff2f5fbe5..ab8a8e3be904138bbc03a599ce28341649a595bc 100644 (file)
@@ -6,8 +6,11 @@
 #include "unit.h"
 #include "fdset.h"
 
-int unit_serialize(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs);
-int unit_deserialize(Unit *u, FILE *f, FDSet *fds);
-int unit_deserialize_skip(FILE *f);
+/* These functions serialize state for our own usage, i.e.: across a reload/reexec, rather than for being
+ * passed to a child process. */
+
+int unit_serialize_state(Unit *u, FILE *f, FDSet *fds, bool serialize_jobs);
+int unit_deserialize_state(Unit *u, FILE *f, FDSet *fds);
+int unit_deserialize_state_skip(FILE *f);
 
 void unit_dump(Unit *u, FILE *f, const char *prefix);
index 5623e949217cad770730c93989984803b9af3102..aa809843f731d4257f34fedac37ff499675dadee 100644 (file)
@@ -1854,18 +1854,6 @@ int unit_test_start_limit(Unit *u) {
         return -ECANCELED;
 }
 
-bool unit_shall_confirm_spawn(Unit *u) {
-        assert(u);
-
-        if (manager_is_confirm_spawn_disabled(u->manager))
-                return false;
-
-        /* For some reasons units remaining in the same process group
-         * as PID 1 fail to acquire the console even if it's not used
-         * by any process. So skip the confirmation question for them. */
-        return !unit_get_exec_context(u)->same_pgrp;
-}
-
 static bool unit_verify_deps(Unit *u) {
         Unit *other;
 
@@ -5369,6 +5357,7 @@ int unit_acquire_invocation_id(Unit *u) {
 }
 
 int unit_set_exec_params(Unit *u, ExecParameters *p) {
+        const char *confirm_spawn;
         int r;
 
         assert(u);
@@ -5381,7 +5370,13 @@ int unit_set_exec_params(Unit *u, ExecParameters *p) {
 
         p->runtime_scope = u->manager->runtime_scope;
 
-        p->confirm_spawn = manager_get_confirm_spawn(u->manager);
+        confirm_spawn = manager_get_confirm_spawn(u->manager);
+        if (confirm_spawn) {
+                p->confirm_spawn = strdup(confirm_spawn);
+                if (!p->confirm_spawn)
+                        return -ENOMEM;
+        }
+
         p->cgroup_supported = u->manager->cgroup_supported;
         p->prefix = u->manager->prefix;
         SET_FLAG(p->flags, EXEC_PASS_LOG_UNIT|EXEC_CHOWN_DIRECTORIES, MANAGER_IS_SYSTEM(u->manager));
@@ -5393,6 +5388,27 @@ int unit_set_exec_params(Unit *u, ExecParameters *p) {
         p->received_credentials_directory = u->manager->received_credentials_directory;
         p->received_encrypted_credentials_directory = u->manager->received_encrypted_credentials_directory;
 
+        p->shall_confirm_spawn = !!u->manager->confirm_spawn;
+
+        p->fallback_smack_process_label = u->manager->defaults.smack_process_label;
+
+        if (u->manager->restrict_fs && p->bpf_outer_map_fd < 0) {
+                int fd = lsm_bpf_map_restrict_fs_fd(u);
+                if (fd < 0)
+                        return fd;
+
+                p->bpf_outer_map_fd = fd;
+        }
+
+        p->user_lookup_fd = u->manager->user_lookup_fds[1];
+
+        p->cgroup_id = u->cgroup_id;
+        p->invocation_id = u->invocation_id;
+        sd_id128_to_string(p->invocation_id, p->invocation_id_string);
+        p->unit_id = strdup(u->id);
+        if (!p->unit_id)
+                return -ENOMEM;
+
         return 0;
 }
 
index 434981755af1dac1a95808f5d4bf18e10a89098c..b5d7eb5f26126145cd35f1deaafac70bc1eec191 100644 (file)
@@ -1024,8 +1024,6 @@ void unit_notify_user_lookup(Unit *u, uid_t uid, gid_t gid);
 int unit_set_invocation_id(Unit *u, sd_id128_t id);
 int unit_acquire_invocation_id(Unit *u);
 
-bool unit_shall_confirm_spawn(Unit *u);
-
 int unit_set_exec_params(Unit *s, ExecParameters *p);
 
 int unit_fork_helper_process(Unit *u, const char *name, PidRef *ret);
index 8063f020f832fe79ca2761d836d3eca3ced42fcc..fa9aeafb98ec28be38e47ed620fab904a96bbf78 100644 (file)
 #include <stddef.h>
 #include <stdint.h>
 
+/* Temporarily disable some warnings */
+#define DISABLE_WARNING_DEPRECATED_DECLARATIONS                         \
+        _Pragma("GCC diagnostic push");                                 \
+        _Pragma("GCC diagnostic ignored \"-Wdeprecated-declarations\"")
+
+#define DISABLE_WARNING_FORMAT_NONLITERAL                               \
+        _Pragma("GCC diagnostic push");                                 \
+        _Pragma("GCC diagnostic ignored \"-Wformat-nonliteral\"")
+
+#define DISABLE_WARNING_MISSING_PROTOTYPES                              \
+        _Pragma("GCC diagnostic push");                                 \
+        _Pragma("GCC diagnostic ignored \"-Wmissing-prototypes\"")
+
+#define DISABLE_WARNING_NONNULL                                         \
+        _Pragma("GCC diagnostic push");                                 \
+        _Pragma("GCC diagnostic ignored \"-Wnonnull\"")
+
+#define DISABLE_WARNING_SHADOW                                          \
+        _Pragma("GCC diagnostic push");                                 \
+        _Pragma("GCC diagnostic ignored \"-Wshadow\"")
+
+#define DISABLE_WARNING_INCOMPATIBLE_POINTER_TYPES                      \
+        _Pragma("GCC diagnostic push");                                 \
+        _Pragma("GCC diagnostic ignored \"-Wincompatible-pointer-types\"")
+
+#define DISABLE_WARNING_TYPE_LIMITS                                     \
+        _Pragma("GCC diagnostic push");                                 \
+        _Pragma("GCC diagnostic ignored \"-Wtype-limits\"")
+
+#define DISABLE_WARNING_ADDRESS                                         \
+        _Pragma("GCC diagnostic push");                                 \
+        _Pragma("GCC diagnostic ignored \"-Waddress\"")
+
+#define REENABLE_WARNING                                                \
+        _Pragma("GCC diagnostic pop")
+
 #define _align_(x) __attribute__((__aligned__(x)))
 #define _alignas_(x) __attribute__((__aligned__(alignof(x))))
 #define _alignptr_ __attribute__((__aligned__(sizeof(void *))))
@@ -384,6 +420,42 @@ static inline size_t ALIGN_TO(size_t l, size_t ali) {
 #define FLAGS_SET(v, flags) \
         ((~(v) & (flags)) == 0)
 
+/* A wrapper for 'func' to return void.
+ * Only useful when a void-returning function is required by some API. */
+#define DEFINE_TRIVIAL_DESTRUCTOR(name, type, func)             \
+        static inline void name(type *p) {                      \
+                func(p);                                        \
+        }
+
+/* When func() returns the void value (NULL, -1, …) of the appropriate type */
+#define DEFINE_TRIVIAL_CLEANUP_FUNC(type, func)                 \
+        static inline void func##p(type *p) {                   \
+                if (*p)                                         \
+                        *p = func(*p);                          \
+        }
+
+/* When func() doesn't return the appropriate type, set variable to empty afterwards.
+ * The func() may be provided by a dynamically loaded shared library, hence add an assertion. */
+#define DEFINE_TRIVIAL_CLEANUP_FUNC_FULL(type, func, empty)     \
+        static inline void func##p(type *p) {                   \
+                if (*p != (empty)) {                            \
+                        DISABLE_WARNING_ADDRESS;                \
+                        assert(func);                           \
+                        REENABLE_WARNING;                       \
+                        func(*p);                               \
+                        *p = (empty);                           \
+                }                                               \
+        }
+
+/* When func() doesn't return the appropriate type, and is also a macro, set variable to empty afterwards. */
+#define DEFINE_TRIVIAL_CLEANUP_FUNC_FULL_MACRO(type, func, empty)       \
+        static inline void func##p(type *p) {                           \
+                if (*p != (empty)) {                                    \
+                        func(*p);                                       \
+                        *p = (empty);                                   \
+                }                                                       \
+        }
+
 /* Declare a flexible array usable in a union.
  * This is essentially a work-around for a pointless constraint in C99
  * and might go away in some future version of the standard.
index 4aac6234d0f62e8da92ccd3790a5fab9861ccbf2..6d0987eedd1b013481c7eeed7c06d144bc2beef8 100644 (file)
@@ -1,7 +1,5 @@
 /* SPDX-License-Identifier: LGPL-2.1-or-later */
 
-#include <sys/utsname.h>
-
 #include "alloc-util.h"
 #include "device-nodes.h"
 #include "fstab-util.h"
@@ -110,33 +108,29 @@ static int get_kernel_hibernate_location(KernelHibernateLocation **ret) {
 
 #if ENABLE_EFI
 static bool validate_efi_hibernate_location(EFIHibernateLocation *e) {
-        _cleanup_free_ char *id = NULL, *image_id = NULL, *version_id = NULL, *image_version = NULL;
-        struct utsname uts = {};
+        _cleanup_free_ char *id = NULL, *image_id = NULL;
         int r;
 
         assert(e);
 
-        if (uname(&uts) < 0)
-                log_warning_errno(errno, "Failed to get kernel info, ignoring: %m");
-
         r = parse_os_release(NULL,
                              "ID", &id,
-                             "IMAGE_ID", &image_id,
-                             "VERSION_ID", &version_id,
-                             "IMAGE_VERSION", &image_version);
+                             "IMAGE_ID", &image_id);
         if (r < 0)
-                log_warning_errno(r, "Failed to parse os-release, ignoring: %m");
-
-        if (!streq(uts.release, strempty(e->kernel_version)) ||
-            !streq_ptr(id, e->id) ||
-            !streq_ptr(image_id, e->image_id) ||
-            !streq_ptr(version_id, e->version_id) ||
-            !streq_ptr(image_version, e->image_version)) {
+                log_warning_errno(r, "Failed to parse os-release: %m");
 
-                log_notice("HibernateLocation system info doesn't match with current running system, not resuming from it.");
+        if (!streq_ptr(id, e->id) ||
+            !streq_ptr(image_id, e->image_id)) {
+                log_notice("HibernateLocation system identifier doesn't match currently running system, not resuming from it.");
                 return false;
         }
 
+        /*
+         * Note that we accept kernel version mismatches. Linux writes the old kernel to disk as part of the
+         * hibernation image, and thus resuming means the short-lived kernel that reads the image from the
+         * disk will be replaced by the original kernel and effectively removed from memory as part of that.
+         */
+
         return true;
 }
 
@@ -183,6 +177,15 @@ static int get_efi_hibernate_location(EFIHibernateLocation **ret) {
         if (r < 0)
                 return r;
 
+        log_info("Reported hibernation image:%s%s%s%s%s%s%s%s%s%s UUID="SD_ID128_UUID_FORMAT_STR" offset=%"PRIu64,
+                 e->id ? " ID=" : "",                       strempty(e->id),
+                 e->image_id ? " IMAGE_ID=" : "",           strempty(e->image_id),
+                 e->version_id ? " VERSION_ID=" : "",       strempty(e->version_id),
+                 e->image_version ? " IMAGE_VERSION=" : "", strempty(e->image_version),
+                 e->kernel_version ? " kernel=" : "",       strempty(e->kernel_version),
+                 SD_ID128_FORMAT_VAL(e->uuid),
+                 e->offset);
+
         if (!validate_efi_hibernate_location(e))
                 goto skip;
 
index 01146467d1a8ccfd82538ca81d12e49483cae760..21ef694ba1ff3d206b1718013b6157cf53ee30c2 100755 (executable)
@@ -124,27 +124,60 @@ def we_are_wanted() -> bool:
     return True
 
 
-def config_file_location() -> Optional[Path]:
+def input_file_location(
+        filename: str,
+        *search_directories: str) -> Optional[Path]:
+
     if root := os.getenv('KERNEL_INSTALL_CONF_ROOT'):
-        p = Path(root) / 'uki.conf'
-    else:
-        p = Path('/etc/kernel/uki.conf')
-    if p.exists():
-        return p
+        search_directories = (root,)
+    elif not search_directories:
+        # This is the default search path.
+        search_directories = ('/etc/kernel',
+                              '/usr/lib/kernel')
+
+    for dir in search_directories:
+        p = Path(dir) / filename
+        if p.exists():
+            return p
     return None
 
 
-def kernel_cmdline_base() -> list[str]:
-    if root := os.getenv('KERNEL_INSTALL_CONF_ROOT'):
-        return Path(root).joinpath('cmdline').read_text().split()
+def uki_conf_location() -> Optional[Path]:
+    return input_file_location('uki.conf',
+                               '/etc/kernel')
+
+
+def devicetree_config_location() -> Optional[Path]:
+    return input_file_location('devicetree')
+
+
+def devicetree_file_location(opts) -> Optional[Path]:
+    # This mirrors the logic in 90-loaderentry.install. Keep in sync.
+    configfile = devicetree_config_location()
+    if configfile is None:
+        return None
 
-    for cmdline in ('/etc/kernel/cmdline',
-                    '/usr/lib/kernel/cmdline'):
-        try:
-            return Path(cmdline).read_text().split()
-        except FileNotFoundError:
-            continue
+    devicetree = configfile.read_text().strip()
+    if not devicetree:
+        raise ValueError(f'{configfile!r} is empty')
 
+    path = input_file_location(
+        devicetree,
+        f'/usr/lib/firmware/{opts.kernel_version}/device-tree',
+        f'/usr/lib/linux-image-{opts.kernel_version}',
+        f'/usr/lib/modules/{opts.kernel_version}/dtb',
+    )
+    if path is None:
+        raise FileNotFoundError(f'DeviceTree file {devicetree} not found')
+    return path
+
+
+def kernel_cmdline_base() -> list[str]:
+    path = input_file_location('cmdline')
+    if path:
+        return path.read_text().split()
+
+    # If we read /proc/cmdline, we need to do some additional filtering.
     options = Path('/proc/cmdline').read_text().split()
     return [opt for opt in options
             if not opt.startswith(('BOOT_IMAGE=', 'initrd='))]
@@ -193,13 +226,16 @@ def call_ukify(opts):
     # argument set to prepopulate the namespace with the defaults.
     opts2 = ukify['create_parser']().parse_args(['build'])
 
-    opts2.config = config_file_location()
+    opts2.config = uki_conf_location()
     opts2.uname = opts.kernel_version
     opts2.linux = opts.kernel_image
     opts2.initrd = initrd_list(opts)
     # Note that 'uki.efi' is the name required by 90-uki-copy.install.
     opts2.output = opts.staging_area / 'uki.efi'
 
+    if devicetree := devicetree_file_location(opts):
+        opts2.devicetree = devicetree
+
     opts2.cmdline = kernel_cmdline(opts)
     if BOOT_STUB:
         opts2.stub = BOOT_STUB
index dc7c371e5a195292095f7c7bc8c29707289ab760..a52dd812e434ec9e12fc7ab4e71a87275ce64f9a 100755 (executable)
@@ -126,12 +126,12 @@ elif [ -f /usr/lib/kernel/devicetree ]; then
 fi
 if [ -n "$DEVICETREE" ]; then
     for prefix in \
-        "/boot/dtb-$KERNEL_VERSION" \
-        "/boot/dtbs/$KERNEL_VERSION" \
-        "/lib/firmware/$KERNEL_VERSION/device-tree" \
-        "/lib/linux-image-$KERNEL_VERSION" \
-        "/lib/modules/$KERNEL_VERSION/dtb"
+        "$KERNEL_INSTALL_CONF_ROOT" \
+        "/usr/lib/firmware/$KERNEL_VERSION/device-tree" \
+        "/usr/lib/linux-image-$KERNEL_VERSION" \
+        "/usr/lib/modules/$KERNEL_VERSION/dtb"
     do
+        [ -n "$prefix" ] || continue
         [ -f "$prefix/$DEVICETREE" ] || continue
         DEVICETREE_SRC="$prefix/$DEVICETREE"
         break
index ad9462c7fb496542984ec23ee45a369c28fb6739..30bee06b533ffb191b054d72e863a97c84e43342 100755 (executable)
@@ -39,6 +39,11 @@ BOOT_ROOT="$D/badboot"
 MACHINE_ID=badbadbadbadbadbad6abadbadbadbad
 EOF
 
+# Create a 'devicetree' config file that points to a fake dtb file
+echo 'subdir/whatever.dtb' >"$D/sources/devicetree"
+mkdir "$D/sources/subdir"
+echo 'DTBDTBDTBDTB' >"$D/sources/subdir/whatever.dtb"
+
 export KERNEL_INSTALL_CONF_ROOT="$D/sources"
 # We "install" multiple plugins, but control which ones will be active via install.conf.
 export KERNEL_INSTALL_PLUGINS="${ukify_install} ${loaderentry_install} ${uki_copy_install}"
@@ -60,9 +65,11 @@ grep -qE '^version +1.1.1' "$entry"
 grep -qE '^options +opt1 opt2' "$entry"
 grep -qE '^linux .*/the-token/1.1.1/linux' "$entry"
 grep -qE '^initrd .*/the-token/1.1.1/initrd' "$entry"
+grep -qE '^devicetree .*/the-token/1.1.1/whatever.dtb' "$entry"
 
 grep -qE 'image' "$BOOT_ROOT/the-token/1.1.1/linux"
 grep -qE 'initrd' "$BOOT_ROOT/the-token/1.1.1/initrd"
+grep -qE 'DTBDTB' "$BOOT_ROOT/the-token/1.1.1/whatever.dtb"
 
 "$kernel_install" inspect
 "$kernel_install" inspect "$D/sources/linux"
@@ -95,9 +102,11 @@ grep -qE '^version +1.1.2' "$entry"
 grep -qE '^options +opt1 opt2' "$entry"
 grep -qE '^linux .*/the-token/1.1.2/linux' "$entry"
 ( ! grep -qE '^initrd' "$entry" )
+grep -qE '^devicetree .*/the-token/1.1.2/whatever.dtb' "$entry"
 
 grep -qE 'image' "$BOOT_ROOT/the-token/1.1.2/linux"
 test ! -e "$BOOT_ROOT/the-token/1.1.2/initrd"
+grep -qE 'DTBDTB' "$BOOT_ROOT/the-token/1.1.2/whatever.dtb"
 
 # Check installation with boot counting
 echo '56' >"$D/sources/tries"
@@ -120,6 +129,7 @@ if [ -f "$ukify" ]; then
 layout=uki
 uki_generator=ukify
 EOF
+
     "$kernel_install" -v add 1.1.3 "$D/sources/linux" "$D/sources/initrd"
     uki="${BOOT_ROOT}/EFI/Linux/the-token-1.1.3+56.efi"
     test -f "$uki"
@@ -129,6 +139,13 @@ EOF
         "$bootctl" kernel-inspect "$uki" | grep -qE 'Version: +1\.1\.3$'
         "$bootctl" kernel-inspect "$uki" | grep -qE 'Cmdline: +opt1 opt2$'
     fi
+
+    "$ukify" inspect "$uki" | grep -qE '^.sbat'
+    "$ukify" inspect "$uki" | grep -qE '^.cmdline'
+    "$ukify" inspect "$uki" | grep -qE '^.uname'
+    "$ukify" inspect "$uki" | grep -qE '^.initrd'
+    "$ukify" inspect "$uki" | grep -qE '^.linux'
+    "$ukify" inspect "$uki" | grep -qE '^.dtb'
 fi
 
 # Test bootctl
index 7c20e52209bef1a47bc74bd8730eed3f615cf672..54facc9c658e30ece89f2e64b3a7b64f3410cb42 100644 (file)
@@ -35,6 +35,7 @@ struct sd_dhcp_lease {
         usec_t t2;
         usec_t lifetime;
         triple_timestamp timestamp;
+        usec_t ipv6_only_preferred_usec;
 
         /* each 0 if unset */
         be32_t address;
index dd330ae83938829a5600ac3447ccfe914f449913..4bf2296ee38686c1a6fd07ce597b4752395c879a 100644 (file)
 
 #include "macro.h"
 #include "sparse-endian.h"
+#include "time-util.h"
+
+/* RFC 8925 - IPv6-Only Preferred Option for DHCPv4 3.4.
+ * MIN_V6ONLY_WAIT: The lower boundary for V6ONLY_WAIT. Value: 300 seconds */
+#define MIN_V6ONLY_WAIT_USEC (300U * USEC_PER_SEC)
 
 struct DHCPMessage {
         uint8_t op;
index a2dae1cd4a8f1b722770a76a5eb7a3d78ac9883d..ae61cd84799ac6377d8d973ebaf6389e5acdd08f 100644 (file)
@@ -83,6 +83,7 @@ struct sd_dhcp_server {
 
         usec_t max_lease_time;
         usec_t default_lease_time;
+        usec_t ipv6_only_preferred_usec;
 
         sd_dhcp_server_callback_t callback;
         void *callback_userdata;
@@ -105,6 +106,8 @@ typedef struct DHCPRequest {
         usec_t lifetime;
         const uint8_t *agent_info_option;
         char *hostname;
+        const uint8_t *parameter_request_list;
+        size_t parameter_request_list_len;
 } DHCPRequest;
 
 extern const struct hash_ops dhcp_lease_hash_ops;
index facb2b2424aafe8bd984142cae682edbb32aac61..7ecd20799354d5b6f474ee9bc0188ce9ffab68ac 100644 (file)
@@ -116,6 +116,7 @@ struct sd_dhcp_client {
         sd_event_source *timeout_t1;
         sd_event_source *timeout_t2;
         sd_event_source *timeout_expire;
+        sd_event_source *timeout_ipv6_only_mode;
         sd_dhcp_client_callback_t callback;
         void *userdata;
         sd_dhcp_client_callback_t state_callback;
@@ -125,6 +126,7 @@ struct sd_dhcp_client {
         int ip_service_type;
         int socket_priority;
         bool socket_priority_set;
+        bool ipv6_acquired;
 };
 
 static const uint8_t default_req_opts[] = {
@@ -280,6 +282,12 @@ int sd_dhcp_client_set_request_option(sd_dhcp_client *client, uint8_t option) {
         return set_ensure_put(&client->req_opts, NULL, UINT8_TO_PTR(option));
 }
 
+static int client_request_contains(sd_dhcp_client *client, uint8_t option) {
+        assert(client);
+
+        return set_contains(client->req_opts, UINT8_TO_PTR(option));
+}
+
 int sd_dhcp_client_set_request_address(
                 sd_dhcp_client *client,
                 const struct in_addr *last_addr) {
@@ -778,6 +786,7 @@ static int client_initialize(sd_dhcp_client *client) {
         (void) event_source_disable(client->timeout_t1);
         (void) event_source_disable(client->timeout_t2);
         (void) event_source_disable(client->timeout_expire);
+        (void) event_source_disable(client->timeout_ipv6_only_mode);
 
         client->attempt = 0;
 
@@ -1424,6 +1433,8 @@ static int client_initialize_time_events(sd_dhcp_client *client) {
         assert(client);
         assert(client->event);
 
+        (void) event_source_disable(client->timeout_ipv6_only_mode);
+
         if (client->start_delay > 0) {
                 assert_se(sd_event_now(client->event, CLOCK_BOOTTIME, &usec) >= 0);
                 usec = usec_add(usec, client->start_delay);
@@ -1613,6 +1624,16 @@ static int client_parse_message(
                 return log_dhcp_client_errno(client, SYNTHETIC_ERRNO(ENOMSG),
                                              "received lease lacks subnet mask, and a fallback one cannot be generated, ignoring.");
 
+        /* RFC 8925 section 3.2
+         * If the client did not include the IPv6-Only Preferred option code in the Parameter Request List in
+         * the DHCPDISCOVER or DHCPREQUEST message, it MUST ignore the IPv6-Only Preferred option in any
+         * messages received from the server. */
+        if (lease->ipv6_only_preferred_usec > 0 &&
+            !client_request_contains(client, SD_DHCP_OPTION_IPV6_ONLY_PREFERRED)) {
+                log_dhcp_client(client, "Received message with unrequested IPv6-only preferred option, ignoring the option.");
+                lease->ipv6_only_preferred_usec = 0;
+        }
+
         *ret = TAKE_PTR(lease);
         return 0;
 }
@@ -1639,13 +1660,26 @@ static int client_handle_offer(sd_dhcp_client *client, DHCPMessage *message, siz
 
 static int client_enter_requesting(sd_dhcp_client *client) {
         assert(client);
+        assert(client->lease);
+
+        if (client->lease->ipv6_only_preferred_usec > 0) {
+                if (client->ipv6_acquired) {
+                        log_dhcp_client(client,
+                                        "Received an OFFER with IPv6-only preferred option, and the host already acquired IPv6 connectivity, stopping DHCPv4 client.");
+                        return sd_dhcp_client_stop(client);
+                }
+
+                log_dhcp_client(client,
+                                "Received an OFFER with IPv6-only preferred option, delaying to send REQUEST with %s.",
+                                FORMAT_TIMESPAN(client->lease->ipv6_only_preferred_usec, USEC_PER_SEC));
+        }
 
         client_set_state(client, DHCP_STATE_REQUESTING);
         client->attempt = 0;
 
         return event_reset_time_relative(client->event, &client->timeout_resend,
                                          CLOCK_BOOTTIME,
-                                         0, 0,
+                                         client->lease->ipv6_only_preferred_usec, 0,
                                          client_timeout_resend, client,
                                          client->event_priority, "dhcp4-resend-timer",
                                          /* force_reset = */ true);
@@ -1814,7 +1848,7 @@ static int client_set_lease_timeouts(sd_dhcp_client *client) {
         return 0;
 }
 
-static int client_enter_bound(sd_dhcp_client *client, int notify_event) {
+static int client_enter_bound_now(sd_dhcp_client *client, int notify_event) {
         int r;
 
         assert(client);
@@ -1822,9 +1856,6 @@ static int client_enter_bound(sd_dhcp_client *client, int notify_event) {
         if (IN_SET(client->state, DHCP_STATE_REQUESTING, DHCP_STATE_REBOOTING))
                 notify_event = SD_DHCP_CLIENT_EVENT_IP_ACQUIRE;
 
-        client->start_delay = 0;
-        (void) event_source_disable(client->timeout_resend);
-
         client_set_state(client, DHCP_STATE_BOUND);
         client->attempt = 0;
 
@@ -1853,6 +1884,47 @@ static int client_enter_bound(sd_dhcp_client *client, int notify_event) {
         return 0;
 }
 
+static int client_timeout_ipv6_only_mode(sd_event_source *s, uint64_t usec, void *userdata) {
+        sd_dhcp_client *client = ASSERT_PTR(userdata);
+        DHCP_CLIENT_DONT_DESTROY(client);
+        int r;
+
+        r = client_enter_bound_now(client, SD_DHCP_CLIENT_EVENT_IP_ACQUIRE);
+        if (r < 0)
+                client_stop(client, r);
+
+        return 0;
+}
+
+static int client_enter_bound(sd_dhcp_client *client, int notify_event) {
+        assert(client);
+        assert(client->lease);
+
+        client->start_delay = 0;
+        (void) event_source_disable(client->timeout_resend);
+
+        if (client->state == DHCP_STATE_REBOOTING && client->lease->ipv6_only_preferred_usec > 0) {
+                if (client->ipv6_acquired) {
+                        log_dhcp_client(client,
+                                        "Received an ACK with IPv6-only preferred option, and the host already acquired IPv6 connectivity, stopping DHCPv4 client.");
+                        return sd_dhcp_client_stop(client);
+                }
+
+                log_dhcp_client(client,
+                                "Received an ACK with IPv6-only preferred option, delaying to enter bound state with %s.",
+                                FORMAT_TIMESPAN(client->lease->ipv6_only_preferred_usec, USEC_PER_SEC));
+
+                return event_reset_time_relative(client->event, &client->timeout_ipv6_only_mode,
+                                                 CLOCK_BOOTTIME,
+                                                 client->lease->ipv6_only_preferred_usec, 0,
+                                                 client_timeout_ipv6_only_mode, client,
+                                                 client->event_priority, "dhcp4-ipv6-only-mode",
+                                                 /* force_reset = */ true);
+        }
+
+        return client_enter_bound_now(client, notify_event);
+}
+
 static int client_handle_message(sd_dhcp_client *client, DHCPMessage *message, int len) {
         DHCP_CLIENT_DONT_DESTROY(client);
         int r;
@@ -2108,6 +2180,9 @@ int sd_dhcp_client_start(sd_dhcp_client *client) {
 
         assert_return(client, -EINVAL);
 
+        /* Note, do not reset the flag in client_initialize(), as it is also called on expire. */
+        client->ipv6_acquired = false;
+
         r = client_initialize(client);
         if (r < 0)
                 return r;
@@ -2224,6 +2299,20 @@ int sd_dhcp_client_stop(sd_dhcp_client *client) {
         return 0;
 }
 
+int sd_dhcp_client_set_ipv6_connectivity(sd_dhcp_client *client, int have) {
+        if (!client)
+                return 0;
+
+        /* We have already received a message with IPv6-Only preferred option, and are waiting for IPv6
+         * connectivity or timeout, let's stop the client. */
+        if (have && sd_event_source_get_enabled(client->timeout_ipv6_only_mode, NULL) > 0)
+                return sd_dhcp_client_stop(client);
+
+        /* Otherwise, save that the host already has IPv6 connectivity. */
+        client->ipv6_acquired = have;
+        return 0;
+}
+
 int sd_dhcp_client_attach_event(sd_dhcp_client *client, sd_event *event, int64_t priority) {
         int r;
 
index db8ac7947ae6301bcf8f1f7a80f5dfd2fe1ba691..d82ab938f73beeccf7777641e44171bdf46509b6 100644 (file)
@@ -884,6 +884,16 @@ int dhcp_lease_parse_options(uint8_t code, uint8_t len, const void *option, void
                         log_debug_errno(r, "Failed to parse 6rd option, ignoring: %m");
                 break;
 
+        case SD_DHCP_OPTION_IPV6_ONLY_PREFERRED:
+                r = lease_parse_be32_seconds(option, len, /* max_as_infinity = */ false, &lease->ipv6_only_preferred_usec);
+                if (r < 0)
+                        log_debug_errno(r, "Failed to parse IPv6 only preferred option, ignoring: %m");
+
+                else if (lease->ipv6_only_preferred_usec < MIN_V6ONLY_WAIT_USEC &&
+                         !network_test_mode_enabled())
+                        lease->ipv6_only_preferred_usec = MIN_V6ONLY_WAIT_USEC;
+                break;
+
         case SD_DHCP_OPTION_PRIVATE_BASE ... SD_DHCP_OPTION_PRIVATE_LAST:
                 r = dhcp_lease_insert_private_option(lease, code, option, len);
                 if (r < 0)
index a917406ceca984b417719f09ffa1fcdbf6ac2e39..a2385ccb893fa65dfe65f03d50f27f59035cb17d 100644 (file)
@@ -113,7 +113,8 @@ int sd_dhcp_server_configure_pool(
 }
 
 int sd_dhcp_server_is_running(sd_dhcp_server *server) {
-        assert_return(server, false);
+        if (!server)
+                return false;
 
         return !!server->receive_message;
 }
@@ -330,6 +331,15 @@ int sd_dhcp_server_stop(sd_dhcp_server *server) {
         return 0;
 }
 
+static bool dhcp_request_contains(DHCPRequest *req, uint8_t option) {
+        assert(req);
+
+        if (!req->parameter_request_list)
+                return false;
+
+        return memchr(req->parameter_request_list, option, req->parameter_request_list_len);
+}
+
 static int dhcp_server_send_unicast_raw(
                 sd_dhcp_server *server,
                 uint8_t hlen,
@@ -649,6 +659,21 @@ static int server_send_offer_or_ack(
                         return r;
         }
 
+        /* RFC 8925 section 3.3. DHCPv4 Server Behavior
+         * The server MUST NOT include the IPv6-Only Preferred option in the DHCPOFFER or DHCPACK message if
+         * the option was not present in the Parameter Request List sent by the client. */
+        if (dhcp_request_contains(req, SD_DHCP_OPTION_IPV6_ONLY_PREFERRED) &&
+            server->ipv6_only_preferred_usec > 0) {
+                be32_t sec = usec_to_be32_sec(server->ipv6_only_preferred_usec);
+
+                r = dhcp_option_append(
+                                &packet->dhcp, req->max_optlen, &offset, 0,
+                                SD_DHCP_OPTION_IPV6_ONLY_PREFERRED,
+                                sizeof(sec), &sec);
+                if (r < 0)
+                        return r;
+        }
+
         ORDERED_SET_FOREACH(j, server->extra_options) {
                 r = dhcp_option_append(&packet->dhcp, req->max_optlen, &offset, 0,
                                        j->option, j->length, j->data);
@@ -778,6 +803,10 @@ static int parse_request(uint8_t code, uint8_t len, const void *option, void *us
                         return 0;
                 }
 
+                break;
+        case SD_DHCP_OPTION_PARAMETER_REQUEST_LIST:
+                req->parameter_request_list = option;
+                req->parameter_request_list_len = len;
                 break;
         }
 
@@ -1501,6 +1530,19 @@ int sd_dhcp_server_set_default_lease_time(sd_dhcp_server *server, uint64_t t) {
         return 0;
 }
 
+int sd_dhcp_server_set_ipv6_only_preferred_usec(sd_dhcp_server *server, uint64_t t) {
+        assert_return(server, -EINVAL);
+
+        /* When 0 is set, disables the IPv6 only mode. */
+
+        /* Refuse too short timespan unless test mode is enabled. */
+        if (t > 0 && t < MIN_V6ONLY_WAIT_USEC && !network_test_mode_enabled())
+                 return -EINVAL;
+
+        server->ipv6_only_preferred_usec = t;
+        return 0;
+}
+
 int sd_dhcp_server_set_servers(
                 sd_dhcp_server *server,
                 sd_dhcp_lease_server_type_t what,
index 56a8831f0fec07c6c8591a695bd327e66ec31df2..4113920ee045bd56e1bb7333eed6d0b79682bb07 100644 (file)
@@ -832,4 +832,5 @@ global:
 LIBSYSTEMD_255 {
 global:
         sd_id128_get_app_specific;
+        sd_device_enumerator_add_match_property_required;
 } LIBSYSTEMD_254;
index 766fadd22c536b9a069b27e58976ba5706ea79d8..15c5c42ade757f634bcf10cd6b1527c70e17c689 100644 (file)
@@ -40,6 +40,7 @@ struct sd_device_enumerator {
         Hashmap *match_sysattr;
         Hashmap *nomatch_sysattr;
         Hashmap *match_property;
+        Hashmap *match_property_required;
         Set *match_sysname;
         Set *nomatch_sysname;
         Set *match_tag;
@@ -95,6 +96,7 @@ static sd_device_enumerator *device_enumerator_free(sd_device_enumerator *enumer
         hashmap_free(enumerator->match_sysattr);
         hashmap_free(enumerator->nomatch_sysattr);
         hashmap_free(enumerator->match_property);
+        hashmap_free(enumerator->match_property_required);
         set_free(enumerator->match_sysname);
         set_free(enumerator->nomatch_sysname);
         set_free(enumerator->match_tag);
@@ -180,6 +182,21 @@ _public_ int sd_device_enumerator_add_match_property(sd_device_enumerator *enume
         return 1;
 }
 
+_public_ int sd_device_enumerator_add_match_property_required(sd_device_enumerator *enumerator, const char *property, const char *value) {
+        int r;
+
+        assert_return(enumerator, -EINVAL);
+        assert_return(property, -EINVAL);
+
+        r = update_match_strv(&enumerator->match_property_required, property, value, /* clear_on_null = */ false);
+        if (r <= 0)
+                return r;
+
+        enumerator->scan_uptodate = false;
+
+        return 1;
+}
+
 static int device_enumerator_add_match_sysname(sd_device_enumerator *enumerator, const char *sysname, bool match) {
         int r;
 
@@ -459,28 +476,38 @@ int device_enumerator_add_device(sd_device_enumerator *enumerator, sd_device *de
         return 1;
 }
 
-static bool match_property(sd_device_enumerator *enumerator, sd_device *device) {
+static bool match_property(Hashmap *properties, sd_device *device, bool match_all) {
         const char *property_pattern;
         char * const *value_patterns;
 
-        assert(enumerator);
         assert(device);
 
         /* Unlike device_match_sysattr(), this accepts device that has at least one matching property. */
 
-        if (hashmap_isempty(enumerator->match_property))
+        if (hashmap_isempty(properties))
                 return true;
 
-        HASHMAP_FOREACH_KEY(value_patterns, property_pattern, enumerator->match_property)
+        HASHMAP_FOREACH_KEY(value_patterns, property_pattern, properties) {
+                bool match = false;
+
                 FOREACH_DEVICE_PROPERTY(device, property, value) {
                         if (fnmatch(property_pattern, property, 0) != 0)
                                 continue;
 
-                        if (strv_fnmatch(value_patterns, value))
-                                return true;
+                        match = strv_fnmatch(value_patterns, value);
+                        if (match) {
+                                if (!match_all)
+                                        return true;
+
+                                break;
+                        }
                 }
 
-        return false;
+                if (!match && match_all)
+                        return false;
+        }
+
+        return match_all;
 }
 
 static bool match_tag(sd_device_enumerator *enumerator, sd_device *device) {
@@ -599,7 +626,10 @@ static int test_matches(
         if (r <= 0)
                 return r;
 
-        if (!match_property(enumerator, device))
+        if (!match_property(enumerator->match_property, device, /* match_all = */ false))
+                return false;
+
+        if (!match_property(enumerator->match_property_required, device, /* match_all = */ true))
                 return false;
 
         if (!device_match_sysattr(device, enumerator->match_sysattr, enumerator->nomatch_sysattr))
index 43376a203602445ffa6a8fbefd4fb0d3e1e54770..bce99b55186a2392d2511d0444577228ca76200f 100644 (file)
@@ -399,6 +399,32 @@ TEST(sd_device_enumerator_add_match_property) {
         assert_se(ifindex == 1);
 }
 
+TEST(sd_device_enumerator_add_match_property_required) {
+        _cleanup_(sd_device_enumerator_unrefp) sd_device_enumerator *e = NULL;
+        sd_device *dev;
+        int ifindex;
+
+        assert_se(sd_device_enumerator_new(&e) >= 0);
+        assert_se(sd_device_enumerator_allow_uninitialized(e) >= 0);
+        assert_se(sd_device_enumerator_add_match_subsystem(e, "net", true) >= 0);
+        assert_se(sd_device_enumerator_add_match_sysattr(e, "ifindex", "1", true) >= 0);
+        assert_se(sd_device_enumerator_add_match_property_required(e, "IFINDE*", "1*") >= 0);
+
+        /* Only one required match which should be satisfied. */
+        dev = sd_device_enumerator_get_device_first(e);
+        assert_se(dev);
+        assert_se(sd_device_get_ifindex(dev, &ifindex) >= 0);
+        assert_se(ifindex == 1);
+
+        /* Now let's add a bunch of garbage properties which should not be satisfied. */
+        assert_se(sd_device_enumerator_add_match_property_required(e, "IFINDE*", "hoge") >= 0);
+        assert_se(sd_device_enumerator_add_match_property_required(e, "IFINDE*", NULL) >= 0);
+        assert_se(sd_device_enumerator_add_match_property_required(e, "AAAAA", "BBBB") >= 0);
+        assert_se(sd_device_enumerator_add_match_property_required(e, "FOOOO", NULL) >= 0);
+
+        assert_se(!sd_device_enumerator_get_device_first(e));
+}
+
 static void check_parent_match(sd_device_enumerator *e, sd_device *dev) {
         const char *syspath;
         bool found = false;
index e2e448b44f5e6e8fa2c14ed96ae33fdcbc36e083..c1a8cd884a81528af0c3219bff855a501cc6d359 100644 (file)
@@ -1669,7 +1669,7 @@ int manager_rtnl_process_address(sd_netlink *rtnl, sd_netlink_message *message,
         uint16_t type;
         Address *address = NULL;
         Request *req = NULL;
-        bool is_new = false;
+        bool is_new = false, update_dhcp4;
         int ifindex, r;
 
         assert(rtnl);
@@ -1778,6 +1778,8 @@ int manager_rtnl_process_address(sd_netlink *rtnl, sd_netlink_message *message,
                 assert_not_reached();
         }
 
+        update_dhcp4 = tmp->family == AF_INET6;
+
         /* Then, find the managed Address and Request objects corresponding to the received address. */
         (void) address_get(link, tmp, &address);
         (void) address_get_request(link, tmp, &req);
@@ -1793,7 +1795,7 @@ int manager_rtnl_process_address(sd_netlink *rtnl, sd_netlink_message *message,
                 if (req)
                         address_enter_removed(req->userdata);
 
-                return 0;
+                goto finalize;
         }
 
         if (!address) {
@@ -1879,6 +1881,15 @@ int manager_rtnl_process_address(sd_netlink *rtnl, sd_netlink_message *message,
         if (r < 0)
                 link_enter_failed(link);
 
+finalize:
+        if (update_dhcp4) {
+                r = dhcp4_update_ipv6_connectivity(link);
+                if (r < 0) {
+                        log_link_warning_errno(link, r, "Failed to notify IPv6 connectivity to DHCPv4 client: %m");
+                        link_enter_failed(link);
+                }
+        }
+
         return 1;
 }
 
index dacbb7e129b60549c184f204edca2a9b223fe422..569398571c02796a36e90705be0dcddcaf0e774c 100644 (file)
@@ -6,8 +6,10 @@
 
 #include "sd-dhcp-server.h"
 
+#include "dhcp-protocol.h"
 #include "fd-util.h"
 #include "fileio.h"
+#include "network-common.h"
 #include "networkd-address.h"
 #include "networkd-dhcp-server-bus.h"
 #include "networkd-dhcp-server-static-lease.h"
@@ -402,6 +404,10 @@ static int dhcp4_server_configure(Link *link) {
                         return log_link_error_errno(link, r, "Failed to set default lease time for DHCPv4 server instance: %m");
         }
 
+        r = sd_dhcp_server_set_ipv6_only_preferred_usec(link->dhcp_server, link->network->dhcp_server_ipv6_only_preferred_usec);
+        if (r < 0)
+                return log_link_error_errno(link, r, "Failed to set IPv6 only preferred time for DHCPv4 server instance: %m");
+
         r = sd_dhcp_server_set_boot_server_address(link->dhcp_server, &link->network->dhcp_server_boot_server_address);
         if (r < 0)
                 return log_link_warning_errno(link, r, "Failed to set boot server address for DHCPv4 server instance: %m");
@@ -726,3 +732,45 @@ int config_parse_dhcp_server_address(
         network->dhcp_server_address_prefixlen = prefixlen;
         return 0;
 }
+
+int config_parse_dhcp_server_ipv6_only_preferred(
+                const char *unit,
+                const char *filename,
+                unsigned line,
+                const char *section,
+                unsigned section_line,
+                const char *lvalue,
+                int ltype,
+                const char *rvalue,
+                void *data,
+                void *userdata) {
+
+        usec_t t, *usec = ASSERT_PTR(data);
+        int r;
+
+        assert(filename);
+        assert(section);
+        assert(lvalue);
+        assert(rvalue);
+
+        if (isempty(rvalue)) {
+                *usec = 0;
+                return 0;
+        }
+
+        r = parse_sec(rvalue, &t);
+        if (r < 0) {
+                log_syntax(unit, LOG_WARNING, filename, line, r,
+                           "Failed to parse [%s] %s=, ignoring assignment: %s", section, lvalue, rvalue);
+                return 0;
+        }
+
+        if (t < MIN_V6ONLY_WAIT_USEC && !network_test_mode_enabled()) {
+                log_syntax(unit, LOG_WARNING, filename, line, 0,
+                           "Invalid [%s] %s=, ignoring assignment: %s", section, lvalue, rvalue);
+                return 0;
+        }
+
+        *usec = t;
+        return 0;
+}
index 4fd4429deb3dd9c488424538cedea8b0fe48e0e3..960232ade6b9ed68ed0d2be0df766cbc10632a97 100644 (file)
@@ -14,3 +14,4 @@ int link_request_dhcp_server(Link *link);
 CONFIG_PARSER_PROTOTYPE(config_parse_dhcp_server_relay_agent_suboption);
 CONFIG_PARSER_PROTOTYPE(config_parse_dhcp_server_emit);
 CONFIG_PARSER_PROTOTYPE(config_parse_dhcp_server_address);
+CONFIG_PARSER_PROTOTYPE(config_parse_dhcp_server_ipv6_only_preferred);
index 3e8038ede6b71ea648d0530f6526350b42cc21a7..57d40e856ee0c4309721026f6ca80bbf730992ff 100644 (file)
@@ -1452,6 +1452,16 @@ static bool link_needs_dhcp_broadcast(Link *link) {
         return r == true;
 }
 
+static bool link_dhcp4_ipv6_only_mode(Link *link) {
+        assert(link);
+        assert(link->network);
+
+        if (link->network->dhcp_ipv6_only_mode >= 0)
+                return link->network->dhcp_ipv6_only_mode;
+
+        return link_dhcp6_enabled(link) || link_ipv6_accept_ra_enabled(link);
+}
+
 static int dhcp4_configure(Link *link) {
         sd_dhcp_option *send_option;
         void *request_options;
@@ -1560,6 +1570,12 @@ static int dhcp4_configure(Link *link) {
                                 return log_link_debug_errno(link, r, "DHCPv4 CLIENT: Failed to set request flag for 6rd: %m");
                 }
 
+                if (link_dhcp4_ipv6_only_mode(link)) {
+                        r = sd_dhcp_client_set_request_option(link->dhcp_client, SD_DHCP_OPTION_IPV6_ONLY_PREFERRED);
+                        if (r < 0)
+                                return log_link_debug_errno(link, r, "DHCPv4 CLIENT: Failed to set request flag for IPv6-only preferred option: %m");
+                }
+
                 SET_FOREACH(request_options, link->network->dhcp_request_options) {
                         uint32_t option = PTR_TO_UINT32(request_options);
 
@@ -1668,7 +1684,7 @@ int dhcp4_update_mac(Link *link) {
                 return r;
 
         if (restart) {
-                r = sd_dhcp_client_start(link->dhcp_client);
+                r = dhcp4_start(link);
                 if (r < 0)
                         return r;
         }
@@ -1676,10 +1692,35 @@ int dhcp4_update_mac(Link *link) {
         return 0;
 }
 
-int dhcp4_start(Link *link) {
+int dhcp4_update_ipv6_connectivity(Link *link) {
+        assert(link);
+
+        if (!link->network)
+                return 0;
+
+        if (!link->network->dhcp_ipv6_only_mode)
+                return 0;
+
+        if (!link->dhcp_client)
+                return 0;
+
+        /* If the client is running, set the current connectivity. */
+        if (sd_dhcp_client_is_running(link->dhcp_client))
+                return sd_dhcp_client_set_ipv6_connectivity(link->dhcp_client, link_has_ipv6_connectivity(link));
+
+        /* If the client has been already stopped or not started yet, let's check the current connectivity
+         * and start the client if necessary. */
+        if (link_has_ipv6_connectivity(link))
+                return 0;
+
+        return dhcp4_start_full(link, /* set_ipv6_connectivity = */ false);
+}
+
+int dhcp4_start_full(Link *link, bool set_ipv6_connectivity) {
         int r;
 
         assert(link);
+        assert(link->network);
 
         if (!link->dhcp_client)
                 return 0;
@@ -1694,6 +1735,12 @@ int dhcp4_start(Link *link) {
         if (r < 0)
                 return r;
 
+        if (set_ipv6_connectivity) {
+                r = dhcp4_update_ipv6_connectivity(link);
+                if (r < 0)
+                        return r;
+        }
+
         return 1;
 }
 
index 7446f0a1311441d28e69356f701503caddb2863f..d36b0585464187ae9db62b5a764acb6bad29130d 100644 (file)
@@ -15,7 +15,11 @@ typedef enum DHCPClientIdentifier {
 
 void network_adjust_dhcp4(Network *network);
 int dhcp4_update_mac(Link *link);
-int dhcp4_start(Link *link);
+int dhcp4_update_ipv6_connectivity(Link *link);
+int dhcp4_start_full(Link *link, bool set_ipv6_connectivity);
+static inline int dhcp4_start(Link *link) {
+        return dhcp4_start_full(link, true);
+}
 int dhcp4_lease_lost(Link *link);
 int dhcp4_check_ready(Link *link);
 
index 06749307832635f4fd55f32b271eada4fbb00756..5fd5734ce06f12c05201fcf4e4140132a681f3c9 100644 (file)
@@ -599,7 +599,7 @@ int bus_link_method_force_renew(sd_bus_message *message, void *userdata, sd_bus_
         if (r == 0)
                 return 1; /* Polkit will call us back */
 
-        if (l->dhcp_server) {
+        if (sd_dhcp_server_is_running(l->dhcp_server)) {
                 r = sd_dhcp_server_forcerenew(l->dhcp_server);
                 if (r < 0)
                         return r;
@@ -626,11 +626,15 @@ int bus_link_method_renew(sd_bus_message *message, void *userdata, sd_bus_error
         if (r == 0)
                 return 1; /* Polkit will call us back */
 
-        if (l->dhcp_client) {
+        if (sd_dhcp_client_is_running(l->dhcp_client))
                 r = sd_dhcp_client_send_renew(l->dhcp_client);
-                if (r < 0)
-                        return r;
-        }
+        else
+                /* The DHCPv4 client may have been stopped by the IPv6 only mode. Let's unconditionally
+                 * restart the client here. Note, if the DHCPv4 client is disabled, then dhcp4_start() does
+                 * nothing and returns 0. */
+                r = dhcp4_start(l);
+        if (r < 0)
+                return r;
 
         return sd_bus_reply_method_return(message, NULL);
 }
index a7b7200423c4691b6ff5e8672c49755fcd222ee8..555b19d580b57b27235cf2e4ab7e979655fd9426 100644 (file)
@@ -52,6 +52,7 @@
 #include "networkd-nexthop.h"
 #include "networkd-queue.h"
 #include "networkd-radv.h"
+#include "networkd-route-util.h"
 #include "networkd-route.h"
 #include "networkd-routing-policy-rule.h"
 #include "networkd-setlink.h"
@@ -94,6 +95,32 @@ bool link_ipv6_enabled(Link *link) {
         return false;
 }
 
+bool link_has_ipv6_connectivity(Link *link) {
+        LinkAddressState ipv6_address_state;
+
+        assert(link);
+
+        link_get_address_states(link, NULL, &ipv6_address_state, NULL);
+
+        switch (ipv6_address_state) {
+        case LINK_ADDRESS_STATE_ROUTABLE:
+                /* If the interface has a routable IPv6 address, then we assume yes. */
+                return true;
+
+        case LINK_ADDRESS_STATE_DEGRADED:
+                /* If the interface has only degraded IPv6 address (mostly, link-local address), then let's check
+                 * there is an IPv6 default gateway. */
+                return link_has_default_gateway(link, AF_INET6);
+
+        case LINK_ADDRESS_STATE_OFF:
+                /* No IPv6 address. */
+                return false;
+
+        default:
+                assert_not_reached();
+        }
+}
+
 static bool link_is_ready_to_configure_one(Link *link, bool allow_unmanaged) {
         assert(link);
 
index 8ced02f3c1aeb0872b2c4a8815bde18ffe53bf04..8bbbc4ec85ce82fb380a2a5a9f53ed261c8f3838 100644 (file)
@@ -236,6 +236,7 @@ static inline bool link_has_carrier(Link *link) {
 
 bool link_ipv6_enabled(Link *link);
 int link_ipv6ll_gained(Link *link);
+bool link_has_ipv6_connectivity(Link *link);
 
 int link_stop_engines(Link *link, bool may_keep_dhcp);
 
index 42e989e11608499b23b47c9e0358b1d504fc9907..02fda412439e3840af633db7c8c65a197c5ac3c4 100644 (file)
@@ -258,6 +258,7 @@ DHCPv4.InitialCongestionWindow,              config_parse_tcp_window,
 DHCPv4.InitialAdvertisedReceiveWindow,       config_parse_tcp_window,                                  0,                             offsetof(Network, dhcp_advertised_receive_window)
 DHCPv4.FallbackLeaseLifetimeSec,             config_parse_dhcp_fallback_lease_lifetime,                0,                             0
 DHCPv4.Use6RD,                               config_parse_bool,                                        0,                             offsetof(Network, dhcp_use_6rd)
+DHCPv4.IPv6OnlyMode,                         config_parse_tristate,                                    0,                             offsetof(Network, dhcp_ipv6_only_mode)
 DHCPv4.NetLabel,                             config_parse_string,                                      CONFIG_PARSE_STRING_SAFE,      offsetof(Network, dhcp_netlabel)
 DHCPv4.NFTSet,                               config_parse_nft_set,                                     NFT_SET_PARSE_NETWORK,         offsetof(Network, dhcp_nft_set_context)
 DHCPv6.UseAddress,                           config_parse_bool,                                        0,                             offsetof(Network, dhcp6_use_address)
@@ -313,6 +314,7 @@ DHCPServer.RelayAgentCircuitId,              config_parse_dhcp_server_relay_agen
 DHCPServer.RelayAgentRemoteId,               config_parse_dhcp_server_relay_agent_suboption,           0,                             offsetof(Network, dhcp_server_relay_agent_remote_id)
 DHCPServer.MaxLeaseTimeSec,                  config_parse_sec,                                         0,                             offsetof(Network, dhcp_server_max_lease_time_usec)
 DHCPServer.DefaultLeaseTimeSec,              config_parse_sec,                                         0,                             offsetof(Network, dhcp_server_default_lease_time_usec)
+DHCPServer.IPv6OnlyPreferredSec,             config_parse_dhcp_server_ipv6_only_preferred,             0,                             offsetof(Network, dhcp_server_ipv6_only_preferred_usec)
 DHCPServer.EmitDNS,                          config_parse_bool,                                        0,                             offsetof(Network, dhcp_server_emit[SD_DHCP_LEASE_DNS].emit)
 DHCPServer.DNS,                              config_parse_dhcp_server_emit,                            0,                             offsetof(Network, dhcp_server_emit[SD_DHCP_LEASE_DNS])
 DHCPServer.EmitNTP,                          config_parse_bool,                                        0,                             offsetof(Network, dhcp_server_emit[SD_DHCP_LEASE_NTP].emit)
index 94506c975de3d4ff88761892daebfd64b437d53f..3de4ea8dec31a47a5a3243fe6c0990bc81fea3bc 100644 (file)
@@ -400,6 +400,7 @@ int network_load_one(Manager *manager, OrderedHashmap **networks, const char *fi
                 .dhcp_route_table = RT_TABLE_MAIN,
                 .dhcp_ip_service_type = -1,
                 .dhcp_broadcast = -1,
+                .dhcp_ipv6_only_mode = -1,
 
                 .dhcp6_use_address = true,
                 .dhcp6_use_pd_prefix = true,
index cc2cf36f5ce6049617d2fe585f46f4d7d05fcbee..1091ce289c1b134a878f56bb99c2986120921e4a 100644 (file)
@@ -139,6 +139,7 @@ struct Network {
         bool dhcp_anonymize;
         bool dhcp_send_hostname;
         int dhcp_broadcast;
+        int dhcp_ipv6_only_mode;
         bool dhcp_use_dns;
         bool dhcp_use_dns_set;
         bool dhcp_routes_to_dns;
@@ -221,6 +222,7 @@ struct Network {
         struct in_addr dhcp_server_boot_server_address;
         char *dhcp_server_boot_server_name;
         char *dhcp_server_boot_filename;
+        usec_t dhcp_server_ipv6_only_preferred_usec;
 
         /* link-local addressing support */
         AddressFamily link_local;
index b4620079fcabd27361203b5815e993203251279e..a204fb9631950a9f74624f34798f68b09353ff3c 100644 (file)
@@ -47,7 +47,8 @@ static bool route_lifetime_is_valid(const Route *route) {
                 route->lifetime_usec > now(CLOCK_BOOTTIME);
 }
 
-static Route *link_find_default_gateway(Link *link, int family, Route *gw) {
+bool link_find_default_gateway(Link *link, int family, Route **gw) {
+        bool found = false;
         Route *route;
 
         assert(link);
@@ -69,16 +70,24 @@ static Route *link_find_default_gateway(Link *link, int family, Route *gw) {
                         continue;
                 if (!in_addr_is_set(route->gw_family, &route->gw))
                         continue;
-                if (gw) {
-                        if (route->gw_weight > gw->gw_weight)
+
+                /* Found a default gateway. */
+                if (!gw)
+                        return true;
+
+                /* If we have already found another gw, then let's compare their weight and priority. */
+                if (*gw) {
+                        if (route->gw_weight > (*gw)->gw_weight)
                                 continue;
-                        if (route->priority >= gw->priority)
+                        if (route->priority >= (*gw)->priority)
                                 continue;
                 }
-                gw = route;
+
+                *gw = route;
+                found = true;
         }
 
-        return gw;
+        return found;
 }
 
 int manager_find_uplink(Manager *m, int family, Link *exclude, Link **ret) {
@@ -98,7 +107,7 @@ int manager_find_uplink(Manager *m, int family, Link *exclude, Link **ret) {
                 if (link->state != LINK_STATE_CONFIGURED)
                         continue;
 
-                gw = link_find_default_gateway(link, family, gw);
+                link_find_default_gateway(link, family, &gw);
         }
 
         if (!gw)
index 1b082fc63f0a9562979549016e513e0d89e16828..f326888c9347dd2c9d87ed58966264a054ba26dc 100644 (file)
@@ -9,9 +9,15 @@
 typedef struct Link Link;
 typedef struct Manager Manager;
 typedef struct Address Address;
+typedef struct Route Route;
 
 unsigned routes_max(void);
 
+bool link_find_default_gateway(Link *link, int family, Route **gw);
+static inline bool link_has_default_gateway(Link *link, int family) {
+        return link_find_default_gateway(link, family, NULL);
+}
+
 int manager_find_uplink(Manager *m, int family, Link *exclude, Link **ret);
 
 bool gateway_is_ready(Link *link, bool onlink, int family, const union in_addr_union *gw);
index 023d81b5784287a87782ee26828b4d2461d7d54c..7218d799fc842098e9b19499a3ce7e4344e02676 100644 (file)
@@ -1620,6 +1620,7 @@ static int process_route_one(
 
         _cleanup_(route_freep) Route *tmp = in;
         Route *route = NULL;
+        bool update_dhcp4;
         int r;
 
         assert(manager);
@@ -1628,6 +1629,8 @@ static int process_route_one(
 
         /* link may be NULL. This consumes 'in'. */
 
+        update_dhcp4 = link && tmp->family == AF_INET6 && tmp->dst_prefixlen == 0;
+
         (void) route_get(manager, link, tmp, &route);
 
         switch (type) {
@@ -1680,6 +1683,14 @@ static int process_route_one(
                 assert_not_reached();
         }
 
+        if (update_dhcp4) {
+                r = dhcp4_update_ipv6_connectivity(link);
+                if (r < 0) {
+                        log_link_warning_errno(link, r, "Failed to notify IPv6 connectivity to DHCPv4 client: %m");
+                        link_enter_failed(link);
+                }
+        }
+
         return 1;
 }
 
index 77853298e0567564cf18bbfcfbc38017ceda5f2a..6f110117ab6dad83a0b91c071a5a88325527d921 100644 (file)
@@ -928,7 +928,7 @@ static int transient_service_set_properties(sd_bus_message *m, const char *pty_p
         return 0;
 }
 
-static int transient_scope_set_properties(sd_bus_message *m) {
+static int transient_scope_set_properties(sd_bus_message *m, bool allow_pidfd) {
         int r;
 
         assert(m);
@@ -945,12 +945,18 @@ static int transient_scope_set_properties(sd_bus_message *m) {
         if (r < 0)
                 return r;
 
-        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
-        r = pidref_set_self(&pidref);
-        if (r < 0)
-                return r;
+        if (allow_pidfd) {
+                _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
 
-        r = bus_append_scope_pidref(m, &pidref);
+                r = pidref_set_self(&pidref);
+                if (r < 0)
+                        return r;
+
+                r = bus_append_scope_pidref(m, &pidref);
+        } else
+                r = sd_bus_message_append(
+                                m, "(sv)",
+                                "PIDs", "au", 1, getpid_cached());
         if (r < 0)
                 return bus_log_create_error(r);
 
@@ -1480,13 +1486,13 @@ static int acquire_invocation_id(sd_bus *bus, sd_id128_t *ret) {
 }
 
 static int start_transient_scope(sd_bus *bus) {
-        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
-        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
+        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
         _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
         _cleanup_strv_free_ char **env = NULL, **user_env = NULL;
         _cleanup_free_ char *scope = NULL;
         const char *object = NULL;
         sd_id128_t invocation_id;
+        bool allow_pidfd = true;
         int r;
 
         assert(bus);
@@ -1508,42 +1514,56 @@ static int start_transient_scope(sd_bus *bus) {
                         return r;
         }
 
-        r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
-        if (r < 0)
-                return bus_log_create_error(r);
+        polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
 
-        r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
-        if (r < 0)
-                return bus_log_create_error(r);
+        for (;;) {
+                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
+                _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
 
-        /* Name and Mode */
-        r = sd_bus_message_append(m, "ss", scope, "fail");
-        if (r < 0)
-                return bus_log_create_error(r);
+                r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
+                if (r < 0)
+                        return bus_log_create_error(r);
 
-        /* Properties */
-        r = sd_bus_message_open_container(m, 'a', "(sv)");
-        if (r < 0)
-                return bus_log_create_error(r);
+                r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
+                if (r < 0)
+                        return bus_log_create_error(r);
 
-        r = transient_scope_set_properties(m);
-        if (r < 0)
-                return r;
+                /* Name and Mode */
+                r = sd_bus_message_append(m, "ss", scope, "fail");
+                if (r < 0)
+                        return bus_log_create_error(r);
 
-        r = sd_bus_message_close_container(m);
-        if (r < 0)
-                return bus_log_create_error(r);
+                /* Properties */
+                r = sd_bus_message_open_container(m, 'a', "(sv)");
+                if (r < 0)
+                        return bus_log_create_error(r);
 
-        /* Auxiliary units */
-        r = sd_bus_message_append(m, "a(sa(sv))", 0);
-        if (r < 0)
-                return bus_log_create_error(r);
+                r = transient_scope_set_properties(m, allow_pidfd);
+                if (r < 0)
+                        return r;
 
-        polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
+                r = sd_bus_message_close_container(m);
+                if (r < 0)
+                        return bus_log_create_error(r);
 
-        r = sd_bus_call(bus, m, 0, &error, &reply);
-        if (r < 0)
-                return log_error_errno(r, "Failed to start transient scope unit: %s", bus_error_message(&error, r));
+                /* Auxiliary units */
+                r = sd_bus_message_append(m, "a(sa(sv))", 0);
+                if (r < 0)
+                        return bus_log_create_error(r);
+
+                r = sd_bus_call(bus, m, 0, &error, &reply);
+                if (r < 0) {
+                        if (sd_bus_error_has_names(&error, SD_BUS_ERROR_UNKNOWN_PROPERTY, SD_BUS_ERROR_PROPERTY_READ_ONLY) && allow_pidfd) {
+                                log_debug("Retrying with classic PIDs.");
+                                allow_pidfd = false;
+                                continue;
+                        }
+
+                        return log_error_errno(r, "Failed to start transient scope unit: %s", bus_error_message(&error, r));
+                }
+
+                break;
+        }
 
         r = sd_bus_message_read(reply, "o", &object);
         if (r < 0)
index e63545312a337597c3fd6c9662816c055b5d7e00..91d2ca3025ab9047c8f3547b576bd5692e5a6982 100644 (file)
@@ -3915,6 +3915,7 @@ int verity_dissect_and_mount(
                 const char *required_host_os_release_id,
                 const char *required_host_os_release_version_id,
                 const char *required_host_os_release_sysext_level,
+                const char *required_host_os_release_confext_level,
                 const char *required_sysext_scope,
                 DissectedImage **ret_image) {
 
@@ -4032,7 +4033,7 @@ int verity_dissect_and_mount(
                                 dissected_image->image_name,
                                 required_host_os_release_id,
                                 required_host_os_release_version_id,
-                                required_host_os_release_sysext_level,
+                                class == IMAGE_SYSEXT ? required_host_os_release_sysext_level : required_host_os_release_confext_level,
                                 required_sysext_scope,
                                 extension_release,
                                 class);
index 8be632acc27530993593d3786ad7eaebc569eb43..f25686a7fd4bd9413cc5fd68fdbf89fcd3d6ba68 100644 (file)
@@ -212,7 +212,7 @@ bool dissected_image_verity_sig_ready(const DissectedImage *image, PartitionDesi
 
 int mount_image_privately_interactively(const char *path, const ImagePolicy *image_policy, DissectImageFlags flags, char **ret_directory, int *ret_dir_fd, LoopDevice **ret_loop_device);
 
-int verity_dissect_and_mount(int src_fd, const char *src, const char *dest, const MountOptions *options, const ImagePolicy *image_policy, const char *required_host_os_release_id, const char *required_host_os_release_version_id, const char *required_host_os_release_sysext_level, const char *required_sysext_scope, DissectedImage **ret_image);
+int verity_dissect_and_mount(int src_fd, const char *src, const char *dest, const MountOptions *options, const ImagePolicy *image_policy, const char *required_host_os_release_id, const char *required_host_os_release_version_id, const char *required_host_os_release_sysext_level, const char *required_host_os_release_confext_level, const char *required_sysext_scope, DissectedImage **ret_image);
 
 int dissect_fstype_ok(const char *fstype);
 
index 60560654bd41c1e26627017a08f6eb4250a9529e..b41c9b06ca3bfa471eab87839b0bffc7435bab0c 100644 (file)
@@ -206,7 +206,7 @@ int dns_label_escape(const char *p, size_t l, char *dest, size_t sz) {
         char *q;
 
         /* DNS labels must be between 1 and 63 characters long. A
-         * zero-length label does not exist. See RFC 2182, Section
+         * zero-length label does not exist. See RFC 2181, Section
          * 11. */
 
         if (l <= 0 || l > DNS_LABEL_MAX)
index 93e5af7e34ddd06f8766ba88334df52f5af8e7c4..011508e632a30214f505a907f7c467105c165939 100644 (file)
@@ -884,6 +884,7 @@ static int mount_in_namespace_legacy(
                                 /* required_host_os_release_id= */ NULL,
                                 /* required_host_os_release_version_id= */ NULL,
                                 /* required_host_os_release_sysext_level= */ NULL,
+                                /* required_host_os_release_confext_level= */ NULL,
                                 /* required_sysext_scope= */ NULL,
                                 /* ret_image= */ NULL);
         else
@@ -1102,6 +1103,7 @@ static int mount_in_namespace(
                                 /* required_host_os_release_id= */ NULL,
                                 /* required_host_os_release_version_id= */ NULL,
                                 /* required_host_os_release_sysext_level= */ NULL,
+                                /* required_host_os_release_confext_level= */ NULL,
                                 /* required_sysext_scope= */ NULL,
                                 &img);
                 if (r < 0)
index 2ffc524f15d696daf684228064f5dbc219a18d87..edb232e2eef58c3d4341109e6577f08f9c54ebde 100644 (file)
@@ -7,6 +7,7 @@
 #include "escape.h"
 #include "fd-util.h"
 #include "fileio.h"
+#include "hexdecoct.h"
 #include "memfd-util.h"
 #include "missing_mman.h"
 #include "missing_syscall.h"
@@ -173,6 +174,93 @@ int serialize_pidref(FILE *f, FDSet *fds, const char *key, PidRef *pidref) {
         return serialize_item_format(f, key, "@%i", copy);
 }
 
+int serialize_item_hexmem(FILE *f, const char *key, const void *p, size_t l) {
+        _cleanup_free_ char *encoded = NULL;
+        int r;
+
+        assert(f);
+        assert(key);
+        assert(p || l == 0);
+
+        if (l == 0)
+                return 0;
+
+        encoded = hexmem(p, l);
+        if (!encoded)
+                return log_oom_debug();
+
+        r = serialize_item(f, key, encoded);
+        if (r < 0)
+                return r;
+
+        return 1;
+}
+
+int serialize_item_base64mem(FILE *f, const char *key, const void *p, size_t l) {
+        _cleanup_free_ char *encoded = NULL;
+        ssize_t len;
+        int r;
+
+        assert(f);
+        assert(key);
+        assert(p || l == 0);
+
+        if (l == 0)
+                return 0;
+
+        len = base64mem(p, l, &encoded);
+        if (len <= 0)
+                return log_oom_debug();
+
+        r = serialize_item(f, key, encoded);
+        if (r < 0)
+                return r;
+
+        return 1;
+}
+
+int serialize_string_set(FILE *f, const char *key, Set *s) {
+        const char *e;
+        int r;
+
+        assert(f);
+        assert(key);
+
+        if (set_isempty(s))
+                return 0;
+
+        /* Serialize as individual items, as each element might contain separators and escapes */
+
+        SET_FOREACH(e, s) {
+                r = serialize_item(f, key, e);
+                if (r < 0)
+                        return r;
+        }
+
+        return 1;
+}
+
+int serialize_image_policy(FILE *f, const char *key, const ImagePolicy *p) {
+        _cleanup_free_ char *policy = NULL;
+        int r;
+
+        assert(f);
+        assert(key);
+
+        if (!p)
+                return 0;
+
+        r = image_policy_to_string(p, /* simplify= */ false, &policy);
+        if (r < 0)
+                return r;
+
+        r = serialize_item(f, key, policy);
+        if (r < 0)
+                return r;
+
+        return 1;
+}
+
 int deserialize_read_line(FILE *f, char **ret) {
         _cleanup_free_ char *line = NULL;
         int r;
@@ -333,3 +421,22 @@ int open_serialization_fd(const char *ident) {
 
         return fd;
 }
+
+int open_serialization_file(const char *ident, FILE **ret) {
+        _cleanup_fclose_ FILE *f = NULL;
+        _cleanup_close_ int fd;
+
+        assert(ret);
+
+        fd = open_serialization_fd(ident);
+        if (fd < 0)
+                return fd;
+
+        f = take_fdopen(&fd, "w+");
+        if (!f)
+                return -errno;
+
+        *ret = TAKE_PTR(f);
+
+        return 0;
+}
index 9463d1127cf448c9b09b570fb684d8e91ec09963..5122c42793677963c564c303b68ac38ab4fa0af5 100644 (file)
@@ -4,19 +4,25 @@
 #include <stdio.h>
 
 #include "fdset.h"
+#include "image-policy.h"
 #include "macro.h"
 #include "pidref.h"
+#include "set.h"
 #include "string-util.h"
 #include "time-util.h"
 
 int serialize_item(FILE *f, const char *key, const char *value);
 int serialize_item_escaped(FILE *f, const char *key, const char *value);
 int serialize_item_format(FILE *f, const char *key, const char *value, ...) _printf_(3,4);
+int serialize_item_hexmem(FILE *f, const char *key, const void *p, size_t l);
+int serialize_item_base64mem(FILE *f, const char *key, const void *p, size_t l);
 int serialize_fd(FILE *f, FDSet *fds, const char *key, int fd);
 int serialize_usec(FILE *f, const char *key, usec_t usec);
 int serialize_dual_timestamp(FILE *f, const char *key, const dual_timestamp *t);
 int serialize_strv(FILE *f, const char *key, char **l);
 int serialize_pidref(FILE *f, FDSet *fds, const char *key, PidRef *pidref);
+int serialize_string_set(FILE *f, const char *key, Set *s);
+int serialize_image_policy(FILE *f, const char *key, const ImagePolicy *p);
 
 static inline int serialize_bool(FILE *f, const char *key, bool b) {
         return serialize_item(f, key, yes_no(b));
@@ -25,6 +31,10 @@ static inline int serialize_bool_elide(FILE *f, const char *key, bool b) {
         return b ? serialize_item(f, key, yes_no(b)) : 0;
 }
 
+static inline int serialize_item_tristate(FILE *f, const char *key, int value) {
+        return value >= 0 ? serialize_item_format(f, key, "%i", value) : 0;
+}
+
 int deserialize_read_line(FILE *f, char **ret);
 
 int deserialize_usec(const char *value, usec_t *timestamp);
@@ -34,3 +44,4 @@ int deserialize_strv(char ***l, const char *value);
 int deserialize_pidref(FDSet *fds, const char *value, PidRef *ret);
 
 int open_serialization_fd(const char *ident);
+int open_serialization_file(const char *ident, FILE **ret);
index 8189e9d8c0dcc408c6680c013187ca559a8eec2f..bb7928bbd70c8373acd07df2f59463edeb8abfa4 100644 (file)
@@ -792,11 +792,10 @@ int tpm2_index_to_handle(
                                        "Invalid handle 0x%08" PRIx32 " (in unknown range).", index);
         }
 
-        /* For transient handles, the kernel tpm "resource manager" (i.e. /dev/tpmrm0) never acknowleges that
-         * any transient handles exist, even if they actually do. So a failure to find the requested handle
-         * index, if it's a transient handle, may not actually mean it's not present in the tpm; thus, only
-         * check GetCapability() if the handle isn't transient. */
-        if (TPM2_HANDLE_TYPE(index) != TPM2_HT_TRANSIENT) { // FIXME: once kernel tpmrm is fixed to acknowledge transient handles, check transient handles too
+        /* For transient handles, the kernel tpm "resource manager" (i.e. /dev/tpmrm0) performs mapping
+         * which breaks GetCapability requests, so only check GetCapability if it's not a transient handle.
+         * https://bugzilla.kernel.org/show_bug.cgi?id=218009 */
+        if (TPM2_HANDLE_TYPE(index) != TPM2_HT_TRANSIENT) { // FIXME: once kernel bug is fixed, check transient handles too
                 r = tpm2_get_capability_handle(c, index);
                 if (r < 0)
                         return r;
index 73f336c522ec947a3aac9b8660f0954527785b59..7d9d7874c1b1d55741ddec38b49198f121d119dc 100644 (file)
@@ -658,7 +658,7 @@ static int varlink_idl_subparse_field_type(
                 if (r < 0)
                         return r;
                 if (!token)
-                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF: %m", *line, *column);
+                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF.", *line, *column);
 
                 field->named_type = TAKE_PTR(token);
                 field->field_type = VARLINK_NAMED_TYPE;
@@ -715,9 +715,9 @@ static int varlink_idl_subparse_struct_or_enum(
 
                 case STATE_OPEN:
                         if (!token)
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF: %m", *line, *column);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF.", *line, *column);
                         if (!streq(token, "("))
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s': %m", *line, *column, token);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s'.", *line, *column, token);
 
                         state = STATE_NAME;
                         allowed_delimiters = ")";
@@ -728,7 +728,7 @@ static int varlink_idl_subparse_struct_or_enum(
                         assert(!field_name);
 
                         if (!token)
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF: %m", *line, *column);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF.", *line, *column);
                         if (streq(token, "#")) {
                                 r = varlink_idl_subparse_comment(p, line, column);
                                 if (r < 0)
@@ -748,7 +748,7 @@ static int varlink_idl_subparse_struct_or_enum(
                         assert(field_name);
 
                         if (!token)
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF: %m", *line, *column);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF.", *line, *column);
 
                         if (streq(token, ":")) {
                                 VarlinkField *field;
@@ -756,7 +756,7 @@ static int varlink_idl_subparse_struct_or_enum(
                                 if ((*symbol)->symbol_type < 0)
                                         (*symbol)->symbol_type = VARLINK_STRUCT_TYPE;
                                 if ((*symbol)->symbol_type == VARLINK_ENUM_TYPE)
-                                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Enum with struct fields, refusing: %m", *line, *column);
+                                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Enum with struct fields, refusing.", *line, *column);
 
                                 r = varlink_symbol_realloc(symbol, *n_fields + 1);
                                 if (r < 0)
@@ -783,7 +783,7 @@ static int varlink_idl_subparse_struct_or_enum(
                                 if ((*symbol)->symbol_type < 0)
                                         (*symbol)->symbol_type = VARLINK_ENUM_TYPE;
                                 if ((*symbol)->symbol_type != VARLINK_ENUM_TYPE)
-                                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Struct with enum fields, refusing: %m", *line, *column);
+                                        return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Struct with enum fields, refusing.", *line, *column);
 
                                 r = varlink_symbol_realloc(symbol, *n_fields + 1);
                                 if (r < 0)
@@ -804,7 +804,7 @@ static int varlink_idl_subparse_struct_or_enum(
                                         state = STATE_DONE;
                                 }
                         } else
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s': %m", *line, *column, token);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s'.", *line, *column, token);
 
                         break;
 
@@ -812,7 +812,7 @@ static int varlink_idl_subparse_struct_or_enum(
                         assert(!field_name);
 
                         if (!token)
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF: %m", *line, *column);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF.", *line, *column);
                         if (streq(token, ",")) {
                                 state = STATE_NAME;
                                 allowed_delimiters = NULL;
@@ -820,7 +820,7 @@ static int varlink_idl_subparse_struct_or_enum(
                         } else if (streq(token, ")"))
                                 state = STATE_DONE;
                         else
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s': %m", *line, *column, token);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s'.", *line, *column, token);
                         break;
 
                 default:
@@ -828,6 +828,11 @@ static int varlink_idl_subparse_struct_or_enum(
                 }
         }
 
+        /* If we don't know the type of the symbol by now it was an empty () which doesn't allow us to
+         * determine if we look at an enum or a struct */
+        if ((*symbol)->symbol_type < 0)
+                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Ambiguous empty () enum/struct is not permitted.", *line, *column);
+
         return 0;
 }
 
@@ -923,7 +928,7 @@ int varlink_idl_parse(
 
                 case STATE_PRE_INTERFACE:
                         if (!token)
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF: %m", *line, *column);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF.", *line, *column);
                         if (streq(token, "#")) {
                                 r = varlink_idl_subparse_comment(&text, line, column);
                                 if (r < 0)
@@ -933,7 +938,7 @@ int varlink_idl_parse(
                                 allowed_delimiters = NULL;
                                 allowed_chars = VALID_CHARS_INTERFACE_NAME;
                         } else
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s': %m", *line, *column, token);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s'.", *line, *column, token);
                         break;
 
                 case STATE_INTERFACE:
@@ -941,7 +946,7 @@ int varlink_idl_parse(
                         assert(n_symbols == 0);
 
                         if (!token)
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF: %m", *line, *column);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Premature EOF.", *line, *column);
 
                         r = varlink_interface_realloc(&interface, n_symbols);
                         if (r < 0)
@@ -973,7 +978,7 @@ int varlink_idl_parse(
                                 state = STATE_ERROR;
                                 allowed_chars = VALID_CHARS_IDENTIFIER;
                         } else
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s': %m", *line, *column, token);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s'.", *line, *column, token);
 
                         break;
 
@@ -1000,7 +1005,7 @@ int varlink_idl_parse(
                         assert(symbol);
 
                         if (!streq(token, "->"))
-                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s': %m", *line, *column, token);
+                                return log_debug_errno(SYNTHETIC_ERRNO(EBADMSG), "%u:%u: Unexpected token '%s'.", *line, *column, token);
 
                         r = varlink_idl_subparse_struct_or_enum(&text, line, column, &symbol, &n_fields, VARLINK_OUTPUT);
                         if (r < 0)
index 52ba99dd2bdfce96ec32df26e288d50e3037b5cc..36dc68fd262a7e18a1c77cdad8e1bcf6c06928a1 100644 (file)
@@ -32,6 +32,8 @@ static VARLINK_DEFINE_ERROR(
 
 static VARLINK_DEFINE_ERROR(PermissionDenied);
 
+static VARLINK_DEFINE_ERROR(ExpectedMore);
+
 /* As per https://varlink.org/Service */
 VARLINK_DEFINE_INTERFACE(
                 org_varlink_service,
@@ -42,4 +44,5 @@ VARLINK_DEFINE_INTERFACE(
                 &vl_error_MethodNotFound,
                 &vl_error_MethodNotImplemented,
                 &vl_error_InvalidParameter,
-                &vl_error_PermissionDenied);
+                &vl_error_PermissionDenied,
+                &vl_error_ExpectedMore);
index 121de882bbfa326ee30cefb97b1a356e05c5b0b3..ae6e142b650ce4a01830a5166f324fd3b810d82c 100644 (file)
@@ -1314,7 +1314,12 @@ static int varlink_dispatch_method(Varlink *v) {
                         r = varlink_idl_validate_method_call(v->current_method, parameters, &bad_field);
                         if (r < 0) {
                                 log_debug_errno(r, "Parameters for method %s() didn't pass validation on field '%s': %m", method, strna(bad_field));
-                                r = varlink_errorb(v, VARLINK_ERROR_INVALID_PARAMETER, JSON_BUILD_OBJECT(JSON_BUILD_PAIR_STRING("parameter", bad_field)));
+
+                                if (!FLAGS_SET(flags, VARLINK_METHOD_ONEWAY)) {
+                                        r = varlink_errorb(v, VARLINK_ERROR_INVALID_PARAMETER, JSON_BUILD_OBJECT(JSON_BUILD_PAIR_STRING("parameter", bad_field)));
+                                        if (r < 0)
+                                                return r;
+                                }
                                 invalid = true;
                         }
                 }
@@ -1325,7 +1330,9 @@ static int varlink_dispatch_method(Varlink *v) {
                                 log_debug_errno(r, "Callback for %s returned error: %m", method);
 
                                 /* We got an error back from the callback. Propagate it to the client if the method call remains unanswered. */
-                                if (!FLAGS_SET(flags, VARLINK_METHOD_ONEWAY)) {
+                                if (v->state == VARLINK_PROCESSED_METHOD)
+                                        r = 0; /* already processed */
+                                else if (!FLAGS_SET(flags, VARLINK_METHOD_ONEWAY)) {
                                         r = varlink_error_errno(v, r);
                                         if (r < 0)
                                                 return r;
@@ -2182,7 +2189,7 @@ int varlink_error(Varlink *v, const char *error_id, JsonVariant *parameters) {
         else {
                 const char *bad_field = NULL;
 
-                r = varlink_idl_validate_method_reply(symbol, parameters, &bad_field);
+                r = varlink_idl_validate_error(symbol, parameters, &bad_field);
                 if (r < 0)
                         log_debug_errno(r, "Parameters for error %s didn't pass validation on field '%s', ignoring: %m", error_id, strna(bad_field));
         }
@@ -2275,6 +2282,12 @@ int varlink_notify(Varlink *v, JsonVariant *parameters) {
 
         if (v->state == VARLINK_DISCONNECTED)
                 return varlink_log_errno(v, SYNTHETIC_ERRNO(ENOTCONN), "Not connected.");
+
+        /* If we want to reply with a notify connection but the caller didn't set "more", then return an
+         * error indicating that we expected to be called with "more" set */
+        if (IN_SET(v->state, VARLINK_PROCESSING_METHOD, VARLINK_PENDING_METHOD))
+                return varlink_error(v, VARLINK_ERROR_EXPECTED_MORE, NULL);
+
         if (!IN_SET(v->state, VARLINK_PROCESSING_METHOD_MORE, VARLINK_PENDING_METHOD_MORE))
                 return varlink_log_errno(v, SYNTHETIC_ERRNO(EBUSY), "Connection busy.");
 
index 5fe529c8532786213c0ffa62e7f705dce9b1401c..e5541d3ce5f794173650935d6a496ef526e43633 100644 (file)
@@ -214,3 +214,4 @@ DEFINE_TRIVIAL_CLEANUP_FUNC(VarlinkServer *, varlink_server_unref);
 
 /* These are errors we came up with and squatted the namespace with */
 #define VARLINK_ERROR_PERMISSION_DENIED "org.varlink.service.PermissionDenied"
+#define VARLINK_ERROR_EXPECTED_MORE "org.varlink.service.ExpectedMore"
index e3d647f75d1eb272632ca4d5530ed8714287f7d4..b67ec0f34dc5bca71d3910c49cc944aebf417f64 100644 (file)
@@ -129,6 +129,7 @@ sd_device *sd_device_enumerator_get_subsystem_next(sd_device_enumerator *enumera
 int sd_device_enumerator_add_match_subsystem(sd_device_enumerator *enumerator, const char *subsystem, int match);
 int sd_device_enumerator_add_match_sysattr(sd_device_enumerator *enumerator, const char *sysattr, const char *value, int match);
 int sd_device_enumerator_add_match_property(sd_device_enumerator *enumerator, const char *property, const char *value);
+int sd_device_enumerator_add_match_property_required(sd_device_enumerator *enumerator, const char *property, const char *value);
 int sd_device_enumerator_add_match_sysname(sd_device_enumerator *enumerator, const char *sysname);
 int sd_device_enumerator_add_nomatch_sysname(sd_device_enumerator *enumerator, const char *sysname);
 int sd_device_enumerator_add_match_tag(sd_device_enumerator *enumerator, const char *tag);
index 19efd3bd87c84474d8b81eaf6370fe7a95150f1b..372603d43ec52dca0e0a8953f4e2650fbf720f2d 100644 (file)
@@ -152,6 +152,7 @@ int sd_dhcp_client_start(sd_dhcp_client *client);
 int sd_dhcp_client_send_release(sd_dhcp_client *client);
 int sd_dhcp_client_send_decline(sd_dhcp_client *client);
 int sd_dhcp_client_send_renew(sd_dhcp_client *client);
+int sd_dhcp_client_set_ipv6_connectivity(sd_dhcp_client *client, int have);
 
 sd_dhcp_client *sd_dhcp_client_ref(sd_dhcp_client *client);
 sd_dhcp_client *sd_dhcp_client_unref(sd_dhcp_client *client);
index 64d95258fd6cb0091f27bde9f0783376c7f11547..1256076b833bf746d599472d8c0dc528f55d325a 100644 (file)
@@ -84,6 +84,7 @@ int sd_dhcp_server_set_static_lease(sd_dhcp_server *server, const struct in_addr
 
 int sd_dhcp_server_set_max_lease_time(sd_dhcp_server *server, uint64_t t);
 int sd_dhcp_server_set_default_lease_time(sd_dhcp_server *server, uint64_t t);
+int sd_dhcp_server_set_ipv6_only_preferred_usec(sd_dhcp_server *server, uint64_t t);
 
 int sd_dhcp_server_forcerenew(sd_dhcp_server *server);
 
index 20d412f5c6c82292644e47d365a5bd1880db986c..67ec3e59f1f93a3267c82585ac6f66002ff85a7c 100644 (file)
@@ -100,6 +100,17 @@ TEST(open_serialization_fd) {
         assert_se(write(fd, "test\n", 5) == 5);
 }
 
+TEST(open_serialization_file) {
+        _cleanup_fclose_ FILE *f = NULL;
+        int r;
+
+        r = open_serialization_file("test", &f);
+        assert_se(r >= 0);
+        assert_se(f);
+
+        assert_se(fwrite("test\n", 1, 5, f) == 5);
+}
+
 TEST(fd_move_above_stdio) {
         int original_stdin, new_fd;
 
index 36052b64859ba8b6a42883f526c9ab8615198c76..9229e3f5c77af0f24e02cf3657c054b7f0aeed4e 100644 (file)
@@ -190,6 +190,72 @@ TEST(serialize_environment) {
         assert_se(strv_equal(env, env2));
 }
 
+TEST(serialize_item_hexmem) {
+        _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-serialize.XXXXXX";
+        _cleanup_fclose_ FILE *f = NULL;
+
+        assert_se(fmkostemp_safe(fn, "r+", &f) == 0);
+        log_info("/* %s (%s) */", __func__, fn);
+
+        assert_se(serialize_item_hexmem(f, "a", NULL, 0) == 0);
+        assert_se(serialize_item_hexmem(f, "a", (uint8_t []){0xff, 0xff, 0xff}, sizeof(uint8_t) * 3) == 1);
+
+        rewind(f);
+
+        _cleanup_free_ char *line = NULL;
+        assert_se(read_line(f, LONG_LINE_MAX, &line) > 0);
+        assert_se(streq(line, "a=ffffff"));
+
+}
+
+TEST(serialize_item_base64mem) {
+        _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-serialize.XXXXXX";
+        _cleanup_fclose_ FILE *f = NULL;
+
+        assert_se(fmkostemp_safe(fn, "r+", &f) == 0);
+        log_info("/* %s (%s) */", __func__, fn);
+
+        assert_se(serialize_item_base64mem(f, "a", NULL, 0) == 0);
+        assert_se(serialize_item_base64mem(f, "a", (uint8_t []){0xff, 0xff, 0xff}, sizeof(uint8_t) * 3) == 1);
+
+        rewind(f);
+
+        _cleanup_free_ char *line = NULL;
+        assert_se(read_line(f, LONG_LINE_MAX, &line) > 0);
+        assert_se(streq(line, "a=////"));
+}
+
+TEST(serialize_string_set) {
+        _cleanup_(unlink_tempfilep) char fn[] = "/tmp/test-serialize.XXXXXX";
+        _cleanup_fclose_ FILE *f = NULL;
+        _cleanup_set_free_free_ Set *s = NULL;
+        _cleanup_free_ char *line1 = NULL, *line2 = NULL;
+        char *p, *q;
+
+        assert_se(fmkostemp_safe(fn, "r+", &f) == 0);
+        log_info("/* %s (%s) */", __func__, fn);
+
+        assert_se(set_ensure_allocated(&s, &string_hash_ops) >= 0);
+
+        assert_se(serialize_string_set(f, "a", s) == 0);
+
+        assert_se(set_put_strsplit(s, "abc def,ghi jkl", ",", 0) >= 0);
+
+        assert_se(serialize_string_set(f, "a", s) == 1);
+
+        rewind(f);
+
+        assert_se(read_line(f, LONG_LINE_MAX, &line1) > 0);
+        assert_se((p = startswith(line1, "a=")));
+
+        assert_se(read_line(f, LONG_LINE_MAX, &line2) > 0);
+        assert_se((q = startswith(line2, "a=")));
+
+        assert_se(!streq(p, q));
+        assert_se(STR_IN_SET(p, "abc def", "ghi jkl"));
+        assert_se(STR_IN_SET(q, "abc def", "ghi jkl"));
+}
+
 static int intro(void) {
         memset(long_string, 'x', sizeof(long_string)-1);
         char_array_0(long_string);
index a93d717f3fb629ccac185a7bbfd0090a37fafcae..028408b16e63ea30f7ae1701f7e9fe47685fdf1e 100644 (file)
@@ -152,6 +152,12 @@ TEST(parse) {
 
         assert_se(varlink_idl_parse(text, NULL, NULL, &parsed) >= 0);
         test_parse_format_one(parsed);
+
+        assert_se(varlink_idl_parse("interface org.freedesktop.Foo\n"
+                                    "type Foo (b: bool, c: foo, c: int)", NULL, NULL, NULL) == -ENETUNREACH); /* unresolved type */
+        assert_se(varlink_idl_parse("interface org.freedesktop.Foo\n"
+                                    "type Foo ()", NULL, NULL, NULL) == -EBADMSG); /* empty struct/enum */
+
 }
 
 TEST(interface_name_is_valid) {
index e1feeac061513b920e5b92ae252b5823e14b4f67..93e69a28b0e27607683af6709602208e67e31e4f 100644 (file)
@@ -275,6 +275,7 @@ static int set_local_rtc(int argc, char **argv, void *userdata) {
 }
 
 static int set_ntp(int argc, char **argv, void *userdata) {
+        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
         _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
         sd_bus *bus = userdata;
         int b, r;
@@ -285,7 +286,16 @@ static int set_ntp(int argc, char **argv, void *userdata) {
         if (b < 0)
                 return log_error_errno(b, "Failed to parse NTP setting '%s': %m", argv[1]);
 
-        r = bus_call_method(bus, bus_timedate, "SetNTP", &error, NULL, "bb", b, arg_ask_password);
+        r = bus_message_new_method_call(bus, &m, bus_timedate, "SetNTP");
+        if (r < 0)
+                return bus_log_create_error(r);
+                
+        r = sd_bus_message_append(m, "bb", b, arg_ask_password);
+        if (r < 0)
+                return bus_log_create_error(r);
+
+        /* Reloading the daemon may take long, hence set a longer timeout here */
+        r = sd_bus_call(bus, m, DAEMON_RELOAD_TIMEOUT_SEC, &error, NULL);
         if (r < 0)
                 return log_error_errno(r, "Failed to set ntp: %s", bus_error_message(&error, r));
 
index 5ac7c9f8b248862de0517b4e679ddabbe7bed043..6406d6fefd5370251a10c43f4a8485bf1021d6dd 100644 (file)
@@ -18,6 +18,7 @@
 #include "bus-log-control-api.h"
 #include "bus-map-properties.h"
 #include "bus-polkit.h"
+#include "bus-unit-util.h"
 #include "clock-util.h"
 #include "conf-files.h"
 #include "constants.h"
@@ -545,7 +546,7 @@ static int unit_enable_or_disable(UnitStatusInfo *u, sd_bus *bus, sd_bus_error *
         if (r < 0)
                 return r;
 
-        r = bus_call_method(bus, bus_systemd_mgr, "Reload", error, NULL, NULL);
+        r = bus_service_manager_reload(bus);
         if (r < 0)
                 return r;
 
index 99a0d72650bb48bbc7e6acdbed0274614e252cf7..04dd4f958f9352a8e1215a9a9a5da8614dff28af 100755 (executable)
@@ -250,7 +250,7 @@ DEFAULT_SECTIONS_TO_SHOW = {
         '.linux'    : 'binary',
         '.initrd'   : 'binary',
         '.splash'   : 'binary',
-        '.dt      : 'binary',
+        '.dtb'      : 'binary',
         '.cmdline'  : 'text',
         '.osrel'    : 'text',
         '.uname'    : 'text',
index a656bfcaf003300d0259b920f14a81de41676e0b..33c85b87ff33a73d803a0f8efd78d4ca2293c9b1 100644 (file)
@@ -475,12 +475,20 @@ static int verb_validate_idl(int argc, char *argv[], void *userdata) {
         }
 
         r = varlink_idl_parse(text, &line, &column, &vi);
+        if (r == -EBADMSG)
+                return log_error_errno(r, "%s:%u:%u: Bad syntax.", fname, line, column);
+        if (r == -ENETUNREACH)
+                return log_error_errno(r, "%s:%u:%u: Failed to parse interface description due an unresolved type.", fname, line, column);
         if (r < 0)
                 return log_error_errno(r, "%s:%u:%u: Failed to parse interface description: %m", fname, line, column);
 
         r = varlink_idl_consistent(vi, LOG_ERR);
+        if (r == -EUCLEAN)
+                return log_error_errno(r, "Interface is inconsistent.");
+        if (r == -ENOTUNIQ)
+                return log_error_errno(r, "Field or symbol not unique in interface.");
         if (r < 0)
-                return r;
+                return log_error_errno(r, "Failed to check interface for consistency: %m");
 
         pager_open(arg_pager_flags);
 
diff --git a/test/test-network/conf/25-dhcp-client-ipv6-only-mode.network b/test/test-network/conf/25-dhcp-client-ipv6-only-mode.network
new file mode 100644 (file)
index 0000000..21a6bc7
--- /dev/null
@@ -0,0 +1,10 @@
+# SPDX-License-Identifier: LGPL-2.1-or-later
+[Match]
+Name=veth99
+
+[Network]
+DHCP=ipv4
+IPv6AcceptRA=no
+
+[DHCPv4]
+IPv6OnlyMode=yes
index 017f76f4d589d4d8541eaf7d696e5d80ff8b76fa..4aba206cb4bfdfbec4cdda4d4ac04b53f35471c8 100644 (file)
@@ -3,7 +3,8 @@
 Name=veth99
 
 [Network]
-DHCP=ipv6
+# DHCPv4 is also enabled here, but will be stopped when an IPv6 address is acquired.
+DHCP=yes
 IPv6Token=::1a:2b:3c:4d
 
 [Route]
diff --git a/test/test-network/conf/25-dhcp-server-ipv6-only-mode.network b/test/test-network/conf/25-dhcp-server-ipv6-only-mode.network
new file mode 100644 (file)
index 0000000..cb19e74
--- /dev/null
@@ -0,0 +1,16 @@
+# SPDX-License-Identifier: LGPL-2.1-or-later
+[Match]
+Name=veth-peer
+
+[Network]
+IPv6AcceptRA=false
+DHCPServer=yes
+
+[DHCPServer]
+ServerAddress=192.168.5.1/24
+PoolOffset=10
+PoolSize=50
+Router=192.168.5.3
+DNS=_server_address 192.168.5.10
+NTP=_server_address 192.168.5.11
+IPv6OnlyPreferredSec=20s
index 1496a615fe48e35d5fffedc78efe5fc171f198b9..122f9e875dd279a99dd2e00e0f0d2c6900386667 100755 (executable)
@@ -770,7 +770,11 @@ def setUpModule():
     save_timezone()
 
     create_service_dropin('systemd-networkd', networkd_bin,
-                          ['[Service]', 'Restart=no', '[Unit]', 'StartLimitIntervalSec=0'])
+                          ['[Service]',
+                           'Restart=no',
+                           'Environment=SYSTEMD_NETWORK_TEST_MODE=yes',
+                           '[Unit]',
+                           'StartLimitIntervalSec=0'])
     create_service_dropin('systemd-resolved', resolved_bin)
     create_service_dropin('systemd-timesyncd', timesyncd_bin)
 
@@ -5110,7 +5114,10 @@ class NetworkdDHCPClientTests(unittest.TestCase, Utilities):
         self.wait_online(['veth-peer:carrier'])
 
         # information request mode
-        start_dnsmasq('--dhcp-option=option6:dns-server,[2600::ee]',
+        # The name ipv6-only option may not be supported by older dnsmasq
+        # start_dnsmasq('--dhcp-option=option:ipv6-only,300')
+        start_dnsmasq('--dhcp-option=108,00:00:02:00',
+                      '--dhcp-option=option6:dns-server,[2600::ee]',
                       '--dhcp-option=option6:ntp-server,[2600::ff]',
                       ra_mode='ra-stateless')
         self.wait_online(['veth99:routable', 'veth-peer:routable'])
@@ -5140,7 +5147,8 @@ class NetworkdDHCPClientTests(unittest.TestCase, Utilities):
 
         # solicit mode
         stop_dnsmasq()
-        start_dnsmasq('--dhcp-option=option6:dns-server,[2600::ee]',
+        start_dnsmasq('--dhcp-option=108,00:00:02:00',
+                      '--dhcp-option=option6:dns-server,[2600::ee]',
                       '--dhcp-option=option6:ntp-server,[2600::ff]')
         networkctl_reconfigure('veth99')
         self.wait_online(['veth99:routable', 'veth-peer:routable'])
@@ -5189,7 +5197,8 @@ class NetworkdDHCPClientTests(unittest.TestCase, Utilities):
             f.write('\n[DHCPv6]\nRapidCommit=no\n')
 
         stop_dnsmasq()
-        start_dnsmasq('--dhcp-option=option6:dns-server,[2600::ee]',
+        start_dnsmasq('--dhcp-option=108,00:00:02:00',
+                      '--dhcp-option=option6:dns-server,[2600::ee]',
                       '--dhcp-option=option6:ntp-server,[2600::ff]')
 
         networkctl_reload()
@@ -5238,16 +5247,55 @@ class NetworkdDHCPClientTests(unittest.TestCase, Utilities):
         # Note that at this point the DHCPv6 client has not been started because no RA (with managed
         # bit set) has yet been received and the configuration does not include WithoutRA=true
         state = get_dhcp6_client_state('veth99')
-        print(f"State = {state}")
+        print(f"DHCPv6 client state = {state}")
         self.assertEqual(state, 'stopped')
 
-        start_dnsmasq()
+        state = get_dhcp4_client_state('veth99')
+        print(f"DHCPv4 client state = {state}")
+        self.assertEqual(state, 'selecting')
+
+        start_dnsmasq('--dhcp-option=108,00:00:02:00')
         self.wait_online(['veth99:routable', 'veth-peer:routable'])
 
         state = get_dhcp6_client_state('veth99')
-        print(f"State = {state}")
+        print(f"DHCPv6 client state = {state}")
         self.assertEqual(state, 'bound')
 
+        # DHCPv4 client will stop after an DHCPOFFER message received, so we need to wait for a while.
+        for _ in range(100):
+            state = get_dhcp4_client_state('veth99')
+            if state == 'stopped':
+                break
+            time.sleep(.2)
+
+        print(f"DHCPv4 client state = {state}")
+        self.assertEqual(state, 'stopped')
+
+        # restart dnsmasq to clear log
+        stop_dnsmasq()
+        start_dnsmasq('--dhcp-option=108,00:00:02:00')
+
+        # Test renew command
+        # See https://github.com/systemd/systemd/pull/29472#issuecomment-1759092138
+        check_output(*networkctl_cmd, 'renew', 'veth99', env=env)
+
+        for _ in range(100):
+            state = get_dhcp4_client_state('veth99')
+            if state == 'stopped':
+                break
+            time.sleep(.2)
+
+        print(f"DHCPv4 client state = {state}")
+        self.assertEqual(state, 'stopped')
+
+        print('## dnsmasq log')
+        output = read_dnsmasq_log_file()
+        print(output)
+        self.assertIn('DHCPDISCOVER(veth-peer) 12:34:56:78:9a:bc', output)
+        self.assertIn('DHCPOFFER(veth-peer)', output)
+        self.assertNotIn('DHCPREQUEST(veth-peer)', output)
+        self.assertNotIn('DHCPACK(veth-peer)', output)
+
     def test_dhcp_client_ipv6_only_with_custom_client_identifier(self):
         copy_network_unit('25-veth.netdev', '25-dhcp-server-veth-peer.network', '25-dhcp-client-ipv6-only-custom-client-identifier.network')
 
@@ -5271,8 +5319,6 @@ class NetworkdDHCPClientTests(unittest.TestCase, Utilities):
         self.assertIn('DHCPREPLY(veth-peer)', output)
         self.assertIn('sent size:  0 option: 14 rapid-commit', output)
 
-        stop_dnsmasq()
-
     def test_dhcp_client_ipv4_only(self):
         copy_network_unit('25-veth.netdev', '25-dhcp-server-veth-peer.network', '25-dhcp-client-ipv4-only.network')
 
@@ -5493,6 +5539,18 @@ class NetworkdDHCPClientTests(unittest.TestCase, Utilities):
         print(f"State = {state}")
         self.assertEqual(state, 'bound')
 
+    def test_dhcp_client_ipv6_only_mode_without_ipv6_connectivity(self):
+        copy_network_unit('25-veth.netdev',
+                          '25-dhcp-server-ipv6-only-mode.network',
+                          '25-dhcp-client-ipv6-only-mode.network')
+        start_networkd()
+        self.wait_online(['veth99:routable', 'veth-peer:routable'], timeout='40s')
+        self.wait_address('veth99', r'inet 192.168.5.[0-9]*/24', ipv='-4')
+
+        state = get_dhcp4_client_state('veth99')
+        print(f"State = {state}")
+        self.assertEqual(state, 'bound')
+
     def test_dhcp_client_ipv4_use_routes_gateway(self):
         first = True
         for (routes, gateway, dns_and_ntp_routes, classless) in itertools.product([True, False], repeat=4):
index 06210868fd2719ff0a552c4ec052d6d5f3512006..6e2af9a2a148bf9534e2406c0ab3e6267b886aa8 100644 (file)
@@ -2,5 +2,5 @@
 Description=Log filtering unit
 
 [Service]
-ExecStart=sh -c 'while true; do echo "Logging from the service, and ~more~"; sleep .25; done'
+ExecStart=sh -c 'while true; do echo "Logging from the service, and ~more~ foo bar"; sleep .25; done'
 SyslogLevel=notice
index d81676a8c354984e81fe3948264157e9f5399771..637fea43875951e8dbcd7c6065dd8a3866699d17 100644 (file)
@@ -7,4 +7,4 @@ After=testsuite-23-bound-by.service
 [Service]
 ExecStart=/bin/sleep infinity
 # --kill-who= (no 'm') to check that the short form is accepted
-ExecStopPost=systemctl kill --kill-who=main -sRTMIN+1 testsuite-23.service
+ExecStopPost=systemctl kill --kill-whom=main -sRTMIN+1 testsuite-23.service
index 3f889d1294ac377d86746df4c0c58927de028176..41cf8a1fa1d3851f5c09b1e8d9e07fae3fc6d5af 100755 (executable)
@@ -78,6 +78,10 @@ if is_xattr_supported; then
     add_logs_filtering_override "logs-filtering.service" "10-allow-with-escape-char" "\\\\x7emore~"
     [[ -n $(run_service_and_fetch_logs "logs-filtering.service") ]]
 
+    add_logs_filtering_override "logs-filtering.service" "11-reset" ""
+    add_logs_filtering_override "logs-filtering.service" "12-allow-with-spaces" "foo bar"
+    [[ -n $(run_service_and_fetch_logs "logs-filtering.service") ]]
+
     add_logs_filtering_override "delegated-cgroup-filtering.service" "00-allow-all" ".*"
     [[ -n $(run_service_and_fetch_logs "delegated-cgroup-filtering.service") ]]
 
index 291d156e88ef7de28cb0fdad2b16e3eb85a4f0f1..fa942091e6f1fdae651b5989bc5844f2a64b8af9 100755 (executable)
@@ -364,7 +364,7 @@ testcase_sanity_check() {
     session=$(loginctl --no-legend | awk '$3 == "logind-test-user" { print $1; exit; }')
     loginctl kill-session --signal=SIGCONT "$session"
     # FIXME(?)
-    #loginctl kill-session --signal=SIGCONT --kill-who=leader "$session"
+    #loginctl kill-session --signal=SIGCONT --kill-whom=leader "$session"
 
     loginctl list-users
     loginctl user-status
index c6258dead63a16c0c84fafa6355f84c1074302cc..ffa9af2f6ac5fa880a0064833111d2842ac7e33e 100755 (executable)
@@ -68,6 +68,12 @@ if systemctl is-active systemd-oomd.service; then
     systemctl restart systemd-oomd.service
 fi
 
+# Ensure that we can start services even with a very low hard memory cap without oom-kills, but skip under
+# sanitizers as they balloon memory usage.
+if ! [[ -v ASAN_OPTIONS || -v UBSAN_OPTIONS ]]; then
+    systemd-run -t -p MemoryMax=10M -p MemorySwapMax=0 -p MemoryZSwapMax=0 /bin/true
+fi
+
 systemctl start testsuite-55-testchill.service
 systemctl start testsuite-55-testbloat.service
 
index fe52f696376a38a11dc1b0ab4097fc34a777e223..273511e72f7fa94cc8b83cbc6b444cf933396442 100644 (file)
@@ -26,6 +26,9 @@ ProtectHostname=yes
 ProtectKernelLogs=yes
 ProtectKernelModules=yes
 ProtectKernelTunables=yes
+Restart=on-failure
+RestartSteps=10
+RestartMaxDelaySec=60
 RestrictAddressFamilies=AF_UNIX AF_INET AF_INET6
 RestrictNamespaces=yes
 RestrictRealtime=yes