HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/core/service.c

280,768 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: 5c097c139d401c81662897faf4f6e6779f5302c7

Lines 1–1000 of 6,768

/* SPDX-License-Identifier: LGPL-2.1-or-later */
 
#include <linux/liveupdate.h>
#include <math.h>
#include <sys/stat.h>
#include <unistd.h>
 
#include "sd-bus.h"
#include "sd-id128.h"
#include "sd-json.h"
#include "sd-messages.h"
 
#include "alloc-util.h"
#include "async.h"
#include "bus-common-errors.h"
#include "bus-error.h"
#include "bus-util.h"
#include "cgroup.h"
#include "chase.h"
#include "daemon-util.h"
#include "dbus-service.h"
#include "dbus-unit.h"
#include "devnum-util.h"
#include "env-util.h"
#include "errno-util.h"
#include "escape.h"
#include "execute.h"
#include "exec-credential.h"
#include "exit-status.h"
#include "extract-word.h"
#include "fd-util.h"
#include "fdset.h"
#include "fileio.h"
#include "format-util.h"
#include "glyph-util.h"
#include "id128-util.h"
#include "image-policy.h"
#include "libaudit-util.h"      /* IWYU pragma: keep */
#include "log.h"
#include "luo-util.h"
#include "manager.h"
#include "memfd-util.h"
#include "mount-util.h"
#include "namespace.h"
#include "open-file.h"
#include "parse-util.h"
#include "path-util.h"
#include "path.h"
#include "pidfd-util.h"
#include "process-util.h"
#include "random-util.h"
#include "selinux-util.h"
#include "serialize.h"
#include "service.h"
#include "signal-util.h"
#include "socket.h"
#include "special.h"
#include "stat-util.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "transaction.h"
#include "unit.h"
#include "unit-name.h"
#include "utf8.h"
 
#define STATUS_TEXT_MAX (16U*1024U)
 
#define service_spawn(...) service_spawn_internal(__func__, __VA_ARGS__)
 
#define SERVICE_FD_STORE_POPULATED(s) (!!(s)->fd_store)
 
#define SERVICE_BUS_NAME_GRACE_USEC (2 * USEC_PER_SEC)
 
static const UnitActiveState state_translation_table[_SERVICE_STATE_MAX] = {
        [SERVICE_DEAD]                       = UNIT_INACTIVE,
        [SERVICE_CONDITION]                  = UNIT_ACTIVATING,
        [SERVICE_START_PRE]                  = UNIT_ACTIVATING,
        [SERVICE_START]                      = UNIT_ACTIVATING,
        [SERVICE_START_POST]                 = UNIT_ACTIVATING,
        [SERVICE_RUNNING]                    = UNIT_ACTIVE,
        [SERVICE_RUNNING_REVALIDATING]       = UNIT_ACTIVE,
        [SERVICE_EXITED]                     = UNIT_ACTIVE,
        [SERVICE_REFRESH_EXTENSIONS]         = UNIT_REFRESHING,
        [SERVICE_REFRESH_CREDENTIALS]        = UNIT_REFRESHING,
        [SERVICE_RELOAD]                     = UNIT_RELOADING,
        [SERVICE_RELOAD_SIGNAL]              = UNIT_RELOADING,
        [SERVICE_RELOAD_NOTIFY]              = UNIT_RELOADING,
        [SERVICE_RELOAD_POST]                = UNIT_RELOADING,
        [SERVICE_MOUNTING]                   = UNIT_REFRESHING,
        [SERVICE_STOP]                       = UNIT_DEACTIVATING,
        [SERVICE_STOP_WATCHDOG]              = UNIT_DEACTIVATING,
        [SERVICE_STOP_SIGTERM]               = UNIT_DEACTIVATING,
        [SERVICE_STOP_SIGKILL]               = UNIT_DEACTIVATING,
        [SERVICE_STOP_POST]                  = UNIT_DEACTIVATING,
        [SERVICE_FINAL_WATCHDOG]             = UNIT_DEACTIVATING,
        [SERVICE_FINAL_SIGTERM]              = UNIT_DEACTIVATING,
        [SERVICE_FINAL_SIGKILL]              = UNIT_DEACTIVATING,
        [SERVICE_FAILED]                     = UNIT_FAILED,
        [SERVICE_DEAD_BEFORE_AUTO_RESTART]   = UNIT_INACTIVE,
        [SERVICE_FAILED_BEFORE_AUTO_RESTART] = UNIT_FAILED,
        [SERVICE_DEAD_RESOURCES_PINNED]      = UNIT_INACTIVE,
        [SERVICE_AUTO_RESTART]               = UNIT_ACTIVATING,
        [SERVICE_AUTO_RESTART_QUEUED]        = UNIT_ACTIVATING,
        [SERVICE_CLEANING]                   = UNIT_MAINTENANCE,
};
 
/* For Type=idle we never want to delay any other jobs, hence we
 * consider idle jobs active as soon as we start working on them */
static const UnitActiveState state_translation_table_idle[_SERVICE_STATE_MAX] = {
        [SERVICE_DEAD]                       = UNIT_INACTIVE,
        [SERVICE_CONDITION]                  = UNIT_ACTIVE,
        [SERVICE_START_PRE]                  = UNIT_ACTIVE,
        [SERVICE_START]                      = UNIT_ACTIVE,
        [SERVICE_START_POST]                 = UNIT_ACTIVE,
        [SERVICE_RUNNING]                    = UNIT_ACTIVE,
        [SERVICE_RUNNING_REVALIDATING]       = UNIT_ACTIVE,
        [SERVICE_EXITED]                     = UNIT_ACTIVE,
        [SERVICE_REFRESH_EXTENSIONS]         = UNIT_REFRESHING,
        [SERVICE_REFRESH_CREDENTIALS]        = UNIT_REFRESHING,
        [SERVICE_RELOAD]                     = UNIT_RELOADING,
        [SERVICE_RELOAD_SIGNAL]              = UNIT_RELOADING,
        [SERVICE_RELOAD_NOTIFY]              = UNIT_RELOADING,
        [SERVICE_RELOAD_POST]                = UNIT_RELOADING,
        [SERVICE_MOUNTING]                   = UNIT_REFRESHING,
        [SERVICE_STOP]                       = UNIT_DEACTIVATING,
        [SERVICE_STOP_WATCHDOG]              = UNIT_DEACTIVATING,
        [SERVICE_STOP_SIGTERM]               = UNIT_DEACTIVATING,
        [SERVICE_STOP_SIGKILL]               = UNIT_DEACTIVATING,
        [SERVICE_STOP_POST]                  = UNIT_DEACTIVATING,
        [SERVICE_FINAL_WATCHDOG]             = UNIT_DEACTIVATING,
        [SERVICE_FINAL_SIGTERM]              = UNIT_DEACTIVATING,
        [SERVICE_FINAL_SIGKILL]              = UNIT_DEACTIVATING,
        [SERVICE_FAILED]                     = UNIT_FAILED,
        [SERVICE_DEAD_BEFORE_AUTO_RESTART]   = UNIT_INACTIVE,
        [SERVICE_FAILED_BEFORE_AUTO_RESTART] = UNIT_FAILED,
        [SERVICE_DEAD_RESOURCES_PINNED]      = UNIT_INACTIVE,
        [SERVICE_AUTO_RESTART]               = UNIT_ACTIVATING,
        [SERVICE_AUTO_RESTART_QUEUED]        = UNIT_ACTIVATING,
        [SERVICE_CLEANING]                   = UNIT_MAINTENANCE,
};
 
static int service_dispatch_inotify_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
static int service_dispatch_timer(sd_event_source *source, usec_t usec, void *userdata);
static int service_dispatch_watchdog(sd_event_source *source, usec_t usec, void *userdata);
static int service_dispatch_exec_io(sd_event_source *source, int fd, uint32_t events, void *userdata);
static int service_dispatch_bus_name_grace(sd_event_source *source, usec_t usec, void *userdata);
 
static void service_enter_signal(Service *s, ServiceState state, ServiceResult f);
 
static void service_reload_finish(Service *s, ServiceResult f);
static void service_enter_reload_by_notify(Service *s);
 
static bool service_can_reload_extensions(Service *s, bool warn);
 
static void service_set_state(Service *s, ServiceState state);
 
static bool SERVICE_STATE_WITH_MAIN_PROCESS(ServiceState state) {
        return IN_SET(state,
                      SERVICE_START, SERVICE_START_POST,
                      SERVICE_RUNNING, SERVICE_RUNNING_REVALIDATING,
                      SERVICE_REFRESH_EXTENSIONS, SERVICE_REFRESH_CREDENTIALS,
                      SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_RELOAD_POST,
                      SERVICE_MOUNTING,
                      SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
                      SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL);
}
 
static bool SERVICE_STATE_WITH_CONTROL_PROCESS(ServiceState state) {
        return IN_SET(state,
                      SERVICE_CONDITION,
                      SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
                      SERVICE_REFRESH_EXTENSIONS, SERVICE_REFRESH_CREDENTIALS, SERVICE_RELOAD, SERVICE_RELOAD_POST,
                      SERVICE_MOUNTING,
                      SERVICE_STOP, SERVICE_STOP_WATCHDOG, SERVICE_STOP_SIGTERM, SERVICE_STOP_SIGKILL, SERVICE_STOP_POST,
                      SERVICE_FINAL_WATCHDOG, SERVICE_FINAL_SIGTERM, SERVICE_FINAL_SIGKILL,
                      SERVICE_CLEANING);
}
 
static bool SERVICE_STATE_WITH_WATCHDOG(ServiceState state) {
        return IN_SET(state,
                      SERVICE_START_POST,
                      SERVICE_RUNNING, SERVICE_RUNNING_REVALIDATING,
                      SERVICE_REFRESH_EXTENSIONS, SERVICE_REFRESH_CREDENTIALS,
                      SERVICE_RELOAD, SERVICE_RELOAD_SIGNAL, SERVICE_RELOAD_NOTIFY, SERVICE_RELOAD_POST,
                      SERVICE_MOUNTING);
}
 
static void service_init(Unit *u) {
        Service *s = SERVICE(u);
 
        assert(u);
        assert(u->load_state == UNIT_STUB);
 
        s->timeout_start_usec = u->manager->defaults.timeout_start_usec;
        s->timeout_stop_usec = u->manager->defaults.timeout_stop_usec;
        s->timeout_abort_usec = u->manager->defaults.timeout_abort_usec;
        s->timeout_abort_set = u->manager->defaults.timeout_abort_set;
        s->restart_usec = u->manager->defaults.restart_usec;
        s->restart_max_delay_usec = USEC_INFINITY;
        s->runtime_max_usec = USEC_INFINITY;
        s->type = _SERVICE_TYPE_INVALID;
        s->socket_fd = -EBADF;
        s->stdin_fd = s->stdout_fd = s->stderr_fd = -EBADF;
        s->root_directory_fd = -EBADF;
        s->guess_main_pid = true;
        s->main_pid = PIDREF_NULL;
        s->control_pid = PIDREF_NULL;
        s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
 
        s->exec_context.keyring_mode = MANAGER_IS_SYSTEM(u->manager) ?
                EXEC_KEYRING_PRIVATE : EXEC_KEYRING_INHERIT;
 
        s->notify_access_override = _NOTIFY_ACCESS_INVALID;
        s->notify_state = _NOTIFY_STATE_INVALID;
 
        s->watchdog_original_usec = USEC_INFINITY;
 
        s->oom_policy = _OOM_POLICY_INVALID;
        s->reload_begin_usec = USEC_INFINITY;
        s->revalidate_runtime_begin_usec = USEC_INFINITY;
        s->reload_signal = SIGHUP;
 
        s->fd_store_preserve_mode = EXEC_PRESERVE_RESTART;
}
 
static void service_unwatch_control_pid(Service *s) {
        assert(s);
        unit_unwatch_pidref_done(UNIT(s), &s->control_pid);
}
 
static void service_unwatch_main_pid(Service *s) {
        assert(s);
        unit_unwatch_pidref_done(UNIT(s), &s->main_pid);
}
 
static void service_unwatch_pid_file(Service *s) {
        assert(s);
 
        if (!s->pid_file_pathspec)
                return;
 
        log_unit_debug(UNIT(s), "Stopping watch for PID file %s", s->pid_file_pathspec->path);
        path_spec_unwatch(s->pid_file_pathspec);
        path_spec_done(s->pid_file_pathspec);
        s->pid_file_pathspec = mfree(s->pid_file_pathspec);
}
 
static int service_set_main_pidref(Service *s, PidRef pidref_consume, const dual_timestamp *start_timestamp) {
        _cleanup_(pidref_done) PidRef pidref = pidref_consume;
        int r;
 
        assert(s);
 
        /* Takes ownership of the specified pidref on both success and failure. */
 
        if (!pidref_is_set(&pidref))
                return -ESRCH;
 
        if (pidref.pid <= 1)
                return -EINVAL;
 
        if (pidref_is_self(&pidref))
                return -EINVAL;
 
        if (s->main_pid_known && pidref_equal(&s->main_pid, &pidref))
                return 0;
 
        if (!pidref_equal(&s->main_pid, &pidref)) {
                service_unwatch_main_pid(s);
 
                dual_timestamp pid_start_time;
 
                if (!start_timestamp) {
                        usec_t t;
 
                        if (pidref_get_start_time(&pidref, &t) >= 0)
                                start_timestamp = dual_timestamp_from_boottime(&pid_start_time, t);
                }
 
                exec_status_start(&s->main_exec_status, pidref.pid, start_timestamp);
        }
 
        s->main_pid = TAKE_PIDREF(pidref);
        s->main_pid_known = true;
 
        r = pidref_is_my_child(&s->main_pid);
        if (r < 0)
                log_unit_warning_errno(UNIT(s), r, "Can't determine if process "PID_FMT" is our child, assuming it is not: %m", s->main_pid.pid);
        else if (r == 0) // FIXME: Supervise through pidfd here
                log_unit_warning(UNIT(s), "Supervising process "PID_FMT" which is not our child. We'll most likely not notice when it exits.", s->main_pid.pid);
        s->main_pid_alien = r <= 0;
 
        return 0;
}
 
void service_release_socket_fd(Service *s) {
        assert(s);
 
        if (s->socket_fd < 0 && !UNIT_ISSET(s->accept_socket) && !s->socket_peer)
                return;
 
        log_unit_debug(UNIT(s), "Closing connection socket.");
 
        /* Undo the effect of service_set_socket_fd(). */
 
        s->socket_fd = asynchronous_close(s->socket_fd);
 
        if (UNIT_ISSET(s->accept_socket)) {
                socket_connection_unref(SOCKET(UNIT_DEREF(s->accept_socket)));
                unit_ref_unset(&s->accept_socket);
        }
 
        s->socket_peer = socket_peer_unref(s->socket_peer);
}
 
static void service_override_notify_access(Service *s, NotifyAccess notify_access_override) {
        assert(s);
 
        s->notify_access_override = notify_access_override;
 
        log_unit_debug(UNIT(s), "notify_access=%s", notify_access_to_string(s->notify_access));
        log_unit_debug(UNIT(s), "notify_access_override=%s", notify_access_to_string(s->notify_access_override));
}
 
static void service_stop_watchdog(Service *s) {
        assert(s);
 
        s->watchdog_event_source = sd_event_source_disable_unref(s->watchdog_event_source);
        s->watchdog_timestamp = DUAL_TIMESTAMP_NULL;
}
 
static void service_start_watchdog(Service *s) {
        usec_t watchdog_usec;
        int r;
 
        assert(s);
 
        watchdog_usec = service_get_watchdog_usec(s);
        if (!timestamp_is_set(watchdog_usec)) {
                service_stop_watchdog(s);
                return;
        }
 
        if (s->watchdog_event_source) {
                r = sd_event_source_set_time(s->watchdog_event_source, usec_add(s->watchdog_timestamp.monotonic, watchdog_usec));
                if (r < 0) {
                        log_unit_warning_errno(UNIT(s), r, "Failed to reset watchdog timer: %m");
                        return;
                }
 
                r = sd_event_source_set_enabled(s->watchdog_event_source, SD_EVENT_ONESHOT);
        } else {
                r = sd_event_add_time(
                                UNIT(s)->manager->event,
                                &s->watchdog_event_source,
                                CLOCK_MONOTONIC,
                                usec_add(s->watchdog_timestamp.monotonic, watchdog_usec), 0,
                                service_dispatch_watchdog, s);
                if (r < 0) {
                        log_unit_warning_errno(UNIT(s), r, "Failed to add watchdog timer: %m");
                        return;
                }
 
                (void) sd_event_source_set_description(s->watchdog_event_source, "service-watchdog");
 
                /* Let's process everything else which might be a sign
                 * of living before we consider a service died. */
                r = sd_event_source_set_priority(s->watchdog_event_source, EVENT_PRIORITY_SERVICE_WATCHDOG);
        }
        if (r < 0)
                log_unit_warning_errno(UNIT(s), r, "Failed to install watchdog timer: %m");
}
 
usec_t service_restart_usec_next(const Service *s) {
        unsigned n_restarts_next;
 
        assert(s);
 
        /* When the service state is in SERVICE_*_BEFORE_AUTO_RESTART or SERVICE_AUTO_RESTART, we still need
         * to add 1 to s->n_restarts manually, because s->n_restarts is not updated until a restart job is
         * enqueued, i.e. state has transitioned to SERVICE_AUTO_RESTART_QUEUED. */
        n_restarts_next = s->n_restarts + (s->state == SERVICE_AUTO_RESTART_QUEUED ? 0 : 1);
 
        if (n_restarts_next <= 1 ||
            s->restart_steps == 0 ||
            s->restart_usec == 0 ||
            s->restart_max_delay_usec == USEC_INFINITY ||
            s->restart_usec >= s->restart_max_delay_usec)
                return s->restart_usec;
 
        if (n_restarts_next > s->restart_steps)
                return s->restart_max_delay_usec;
 
        /* Enforced in service_verify() and above */
        assert(s->restart_max_delay_usec > s->restart_usec);
 
        /* r_i / r_0 = (r_n / r_0) ^ (i / n)
         * where,
         *   r_0 : initial restart usec (s->restart_usec),
         *   r_i : i-th restart usec (value),
         *   r_n : maximum restart usec (s->restart_max_delay_usec),
         *   i : index of the next step (n_restarts_next - 1)
         *   n : num maximum steps (s->restart_steps) */
        return (usec_t) (s->restart_usec * powl((long double) s->restart_max_delay_usec / s->restart_usec,
                                                (long double) (n_restarts_next - 1) / s->restart_steps));
}
 
static usec_t service_restart_usec_next_jittered(const Service *s) {
        assert(s);
 
        /* Single helper for the restart timer and the deadline reconstructed at coldplug so they can't drift */
        return usec_add(service_restart_usec_next(s), s->restart_randomized_delay_chosen_usec);
}
 
static void service_extend_event_source_timeout(Service *s, sd_event_source *source, usec_t extended) {
        usec_t current;
        int r;
 
        assert(s);
 
        /* Extends the specified event source timer to at least the specified time, unless it is already later
         * anyway. */
 
        if (!source)
                return;
 
        r = sd_event_source_get_time(source, &current);
        if (r < 0) {
                const char *desc;
                (void) sd_event_source_get_description(s->timer_event_source, &desc);
                log_unit_warning_errno(UNIT(s), r, "Failed to retrieve timeout time for event source '%s', ignoring: %m", strna(desc));
                return;
        }
 
        if (current >= extended) /* Current timeout is already longer, ignore this. */
                return;
 
        r = sd_event_source_set_time(source, extended);
        if (r < 0) {
                const char *desc;
                (void) sd_event_source_get_description(s->timer_event_source, &desc);
                log_unit_warning_errno(UNIT(s), r, "Failed to set timeout time for event source '%s', ignoring: %m", strna(desc));
        }
}
 
static void service_extend_timeout(Service *s, usec_t extend_timeout_usec) {
        usec_t extended;
 
        assert(s);
 
        if (!timestamp_is_set(extend_timeout_usec))
                return;
 
        extended = usec_add(now(CLOCK_MONOTONIC), extend_timeout_usec);
 
        service_extend_event_source_timeout(s, s->timer_event_source, extended);
        service_extend_event_source_timeout(s, s->watchdog_event_source, extended);
}
 
static void service_reset_watchdog(Service *s) {
        assert(s);
 
        if (freezer_state_objective(UNIT(s)->freezer_state) != FREEZER_RUNNING) {
                log_unit_debug(UNIT(s), "Service is currently %s, skipping resetting watchdog.",
                               freezer_state_to_string(UNIT(s)->freezer_state));
                return;
        }
 
        dual_timestamp_now(&s->watchdog_timestamp);
        service_start_watchdog(s);
}
 
static void service_override_watchdog_timeout(Service *s, usec_t watchdog_override_usec) {
        assert(s);
 
        s->watchdog_override_enable = true;
        s->watchdog_override_usec = watchdog_override_usec;
        service_reset_watchdog(s);
 
        log_unit_debug(UNIT(s), "watchdog_usec="USEC_FMT, s->watchdog_usec);
        log_unit_debug(UNIT(s), "watchdog_override_usec="USEC_FMT, s->watchdog_override_usec);
}
 
static ServiceFDStore* service_fd_store_unlink_full(ServiceFDStore *fs, bool propagate_upstream) {
        if (!fs)
                return NULL;
 
        if (fs->service) {
                assert(fs->service->n_fd_store > 0);
 
                /* If we previously propagated this fd to an enveloping service/container manager via
                 * the FDSTORE=1 protocol on its NOTIFY_SOCKET (only done when persistence is on),
                 * tell that supervisor to drop it now too, so the upstream fd store stays in sync.
                 * Only do this for explicit removals (EPOLLHUP/EPOLLERR or app FDSTOREREMOVE), not
                 * for local cleanup like service shutdown or fdstore-limit truncation: in those
                 * cases we want the upstream copy to survive so it can be handed back to us later. */
                if (propagate_upstream && fs->index > 0) {
                        (void) notify_remove_fd_warnf(SERVICE_FDSTORE_SUB_FDNAME_PREFIX "%" PRIu64, fs->index);
                        fs->index = 0;
                        /* Refresh the upstream JSON mapping so the supervisor's view stays in sync
                         * with what fds are actually still around. */
                        (void) service_propagate_fd_store_mapping_upstream(UNIT(fs->service)->manager);
                }
 
                LIST_REMOVE(fd_store, fs->service->fd_store, fs);
                fs->service->n_fd_store--;
        }
 
        sd_event_source_disable_unref(fs->event_source);
 
        free(fs->fdname);
        asynchronous_close(fs->fd);
        return mfree(fs);
}
 
static ServiceFDStore* service_fd_store_unlink(ServiceFDStore *fs) {
        return service_fd_store_unlink_full(fs, /* propagate_upstream= */ false);
}
 
DEFINE_TRIVIAL_CLEANUP_FUNC(ServiceFDStore*, service_fd_store_unlink);
 
static void service_release_fd_store(Service *s) {
        assert(s);
 
        if (!SERVICE_FD_STORE_POPULATED(s))
                return;
 
        log_unit_debug(UNIT(s), "Releasing all stored fds.");
 
        while (SERVICE_FD_STORE_POPULATED(s))
                service_fd_store_unlink(s->fd_store);
 
        assert(s->n_fd_store == 0);
}
 
static void service_truncate_fd_store(Service *s) {
        assert(s);
 
        /* Drop fds that exceed the (possibly newly lowered) n_fd_store_max, e.g. after the fragment was
         * parsed and FileDescriptorStoreMax= shrunk the configured limit. Newest entries are at the head
         * of the list, so drop from the head (newest first). */
 
        while (s->n_fd_store > s->n_fd_store_max + strv_length(s->luo_sessions)) {
                ServiceFDStore *fs = ASSERT_PTR(s->fd_store);
                log_unit_debug(UNIT(s), "Dropping stored fd '%s' to honor FileDescriptorStoreMax=%u.",
                               strna(fs->fdname), s->n_fd_store_max);
                service_fd_store_unlink(fs);
        }
}
 
static void service_release_extra_fds(Service *s) {
        assert(s);
 
        if (!s->extra_fds)
                return;
 
        log_unit_debug(UNIT(s), "Releasing extra file descriptors.");
 
        FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds) {
                asynchronous_close(i->fd);
                free(i->fdname);
        }
 
        s->extra_fds = mfree(s->extra_fds);
        s->n_extra_fds = 0;
}
 
ServiceExtraFD* service_extra_fd_free(ServiceExtraFD *fd) {
        if (!fd)
                return NULL;
 
        safe_close(fd->fd);
        free(fd->fdname);
        return mfree(fd);
}
 
static void service_release_stdio_fd(Service *s) {
        assert(s);
 
        if (s->stdin_fd < 0 && s->stdout_fd < 0 && s->stderr_fd < 0)
                return;
 
        log_unit_debug(UNIT(s), "Releasing stdin/stdout/stderr file descriptors.");
 
        s->stdin_fd = asynchronous_close(s->stdin_fd);
        s->stdout_fd = asynchronous_close(s->stdout_fd);
        s->stderr_fd = asynchronous_close(s->stderr_fd);
}
 
static void service_done(Unit *u) {
        Service *s = ASSERT_PTR(SERVICE(u));
 
        open_file_free_many(&s->open_files);
 
        s->pid_file = mfree(s->pid_file);
        s->status_text = mfree(s->status_text);
        s->status_bus_error = mfree(s->status_bus_error);
        s->status_varlink_error = mfree(s->status_varlink_error);
 
        s->exec_runtime = exec_runtime_free(s->exec_runtime);
 
        exec_command_free_array(s->exec_command, _SERVICE_EXEC_COMMAND_MAX);
        s->control_command = NULL;
        s->main_command = NULL;
 
        exit_status_set_free(&s->restart_prevent_status);
        exit_status_set_free(&s->restart_force_status);
        exit_status_set_free(&s->success_status);
 
        /* This will leak a process, but at least no memory or any of our resources */
        service_unwatch_main_pid(s);
        service_unwatch_control_pid(s);
        service_unwatch_pid_file(s);
 
        if (s->bus_name)  {
                unit_unwatch_bus_name(u, s->bus_name);
                s->bus_name = mfree(s->bus_name);
        }
 
        s->usb_function_descriptors = mfree(s->usb_function_descriptors);
        s->usb_function_strings = mfree(s->usb_function_strings);
 
        service_stop_watchdog(s);
 
        s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
        s->bus_name_grace_event_source = sd_event_source_disable_unref(s->bus_name_grace_event_source);
        s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
 
        s->bus_name_pid_lookup_slot = sd_bus_slot_unref(s->bus_name_pid_lookup_slot);
 
        service_release_socket_fd(s);
        service_release_stdio_fd(s);
        service_release_fd_store(s);
        service_release_extra_fds(s);
        s->root_directory_fd = asynchronous_close(s->root_directory_fd);
 
        s->luo_sessions = strv_free(s->luo_sessions);
 
        s->mount_request = sd_bus_message_unref(s->mount_request);
}
 
static int on_fd_store_io(sd_event_source *e, int fd, uint32_t revents, void *userdata) {
        ServiceFDStore *fs = ASSERT_PTR(userdata);
        Service *s = fs->service;
 
        assert(e);
 
        /* If we get either EPOLLHUP or EPOLLERR, it's time to remove this entry from the fd store */
        log_unit_debug(UNIT(s),
                       "Received %s on stored fd %d (%s), closing.",
                       revents & EPOLLERR ? "EPOLLERR" : "EPOLLHUP",
                       fs->fd, strna(fs->fdname));
        service_fd_store_unlink_full(fs, /* propagate_upstream= */ true);
 
        if (s->state == SERVICE_DEAD_RESOURCES_PINNED && !SERVICE_FD_STORE_POPULATED(s))
                service_set_state(s, SERVICE_DEAD);
 
        return 0;
}
 
int service_add_fd_store(Service *s, int fd_in, const char *name, bool do_poll, bool propagate_upstream) {
        _cleanup_(service_fd_store_unlinkp) ServiceFDStore *fs = NULL;
        _cleanup_(asynchronous_closep) int fd = ASSERT_FD(fd_in);
        struct stat st;
        int r;
 
        /* fd is always consumed even if the function fails. */
 
        assert(s);
 
        if (fstat(fd, &st) < 0)
                return -errno;
 
        log_unit_debug(UNIT(s), "Trying to stash fd for dev=" DEVNUM_FORMAT_STR "/inode=%" PRIu64,
                       DEVNUM_FORMAT_VAL(st.st_dev), (uint64_t) st.st_ino);
 
        if (s->n_fd_store >= s->n_fd_store_max)
                /* Our store is full.  Use this errno rather than E[NM]FILE to distinguish from the case
                 * where systemd itself hits the file limit. */
                return log_unit_debug_errno(UNIT(s), SYNTHETIC_ERRNO(EXFULL), "Hit fd store limit.");
 
        LIST_FOREACH(fd_store, i, s->fd_store) {
                r = same_fd(i->fd, fd);
                if (r < 0)
                        return r;
                if (r > 0) {
                        log_unit_debug(UNIT(s), "Suppressing duplicate fd %i in fd store.", fd);
                        return 0; /* fd already included */
                }
        }
 
        fs = new(ServiceFDStore, 1);
        if (!fs)
                return -ENOMEM;
 
        *fs = (ServiceFDStore) {
                .fd = TAKE_FD(fd),
                .do_poll = do_poll,
                .fdname = strdup(name ?: "stored"),
        };
 
        if (!fs->fdname)
                return -ENOMEM;
 
        if (do_poll) {
                r = sd_event_add_io(UNIT(s)->manager->event, &fs->event_source, fs->fd, 0, on_fd_store_io, fs);
                if (r < 0 && r != -EPERM) /* EPERM indicates fds that aren't pollable, which is OK */
                        return r;
                if (r >= 0)
                        (void) sd_event_source_set_description(fs->event_source, "service-fd-store");
        }
 
        log_unit_debug(UNIT(s), "Added fd %i (%s) to fd store.", fs->fd, fs->fdname);
 
        /* If fd-store persistence is enabled and we have an enveloping service/container manager (i.e.
         * NOTIFY_SOCKET is set), forward the fd to it via sd_notify(FDSTORE=1) tagged with a fresh
         * incrementing index, and (re-)push the JSON mapping memfd that pairs the index back to this
         * unit and the original fdname. This way fdstore persistence chains all the way up to whichever
         * entity is ultimately responsible for surviving across kexec/restart, regardless of fdname
         * length or charset constraints. */
        if (propagate_upstream && IN_SET(s->fd_store_preserve_mode, EXEC_PRESERVE_YES, EXEC_PRESERVE_ON_SUCCESS)) {
                Manager *m = ASSERT_PTR(UNIT(s)->manager);
                char idx_str[STRLEN(SERVICE_FDSTORE_SUB_FDNAME_PREFIX) + DECIMAL_STR_MAX(uint64_t)];
 
                assert(m->fd_store_upstream_next_index < UINT64_MAX);
                uint64_t idx = ++m->fd_store_upstream_next_index;
 
                xsprintf(idx_str, SERVICE_FDSTORE_SUB_FDNAME_PREFIX "%" PRIu64, idx);
 
                r = notify_push_fd(fs->fd, idx_str);
                if (r < 0)
                        log_unit_debug_errno(UNIT(s), r,
                                             "Failed to propagate fd '%s' to upstream supervisor as index %" PRIu64 ", ignoring: %m",
                                             fs->fdname, idx);
                else
                        fs->index = idx;
        }
 
        fs->service = s;
        LIST_PREPEND(fd_store, s->fd_store, TAKE_PTR(fs));
        s->n_fd_store++;
 
        if (propagate_upstream && IN_SET(s->fd_store_preserve_mode, EXEC_PRESERVE_YES, EXEC_PRESERVE_ON_SUCCESS))
                /* Refresh the JSON mapping memfd so the supervisor can resolve the new index. Do this
                 * after LIST_PREPEND so the new entry is visible to the helper. */
                (void) service_propagate_fd_store_mapping_upstream(UNIT(s)->manager);
 
        return 1; /* fd newly stored */
}
 
static int service_add_fd_store_set(Service *s, FDSet *fds, const char *name, bool do_poll, bool propagate_upstream) {
        int r;
 
        assert(s);
 
        for (;;) {
                int fd;
 
                fd = fdset_steal_first(fds);
                if (fd < 0)
                        break;
 
                r = service_add_fd_store(s, fd, name, do_poll, propagate_upstream);
                if (r == -EXFULL)
                        return log_unit_warning_errno(UNIT(s), r,
                                                      "Cannot store more fds than FileDescriptorStoreMax=%u, closing remaining.",
                                                      s->n_fd_store_max);
                if (r < 0)
                        return log_unit_error_errno(UNIT(s), r, "Failed to add fd to store: %m");
        }
 
        return 0;
}
 
/* Build a deterministic LUO session name from the unit's name and the session name, with stable length. */
static int service_build_luo_session_name(Service *s, const char *name, char **ret) {
        _cleanup_free_ char *full = NULL, *result = NULL;
 
        assert(s);
        assert(name);
        assert(ret);
 
        full = strjoin(UNIT(s)->id, "/", name);
        if (!full)
                return -ENOMEM;
 
        /* The kernel embeds the session name in the anon_inode path shown in /proc/self/fd/, i.e.
         * "anon_inode:[luo_session] <name>". On kernels lacking commit 97b67e64affb ("dcache: permit
         * dynamic_dname()s up to NAME_MAX") that path must fit dynamic_dname()'s historical 64 byte limit,
         * otherwise reading it back will fail. Can be simplified once Ubuntu 26.04 support is dropped. */
        // FIXME: allow longer prefix once Ubuntu 26.04 support is dropped
        size_t name_max = 64U - STRLEN("anon_inode:[luo_session] ") - 1U; /* = 38 */
        size_t digest_chars = 24U; /* 96 bit, leaves room for a useful unit id prefix within name_max */
 
        assert_cc(64U - STRLEN("anon_inode:[luo_session] ") - 1U < LIVEUPDATE_SESSION_NAME_LENGTH);
        assert_cc(24U < SD_ID128_STRING_MAX);
        assert_cc(24U + 1U < 64U - STRLEN("anon_inode:[luo_session] ") - 1U);
 
        char digest[SD_ID128_STRING_MAX];
        sd_id128_to_string(id128_digest(full, SIZE_MAX), digest);
 
        if (asprintf(&result, "%.*s-%.*s",
                     (int) (name_max - digest_chars - 1U), UNIT(s)->id,
                     (int) digest_chars, digest) < 0)
                return -ENOMEM;
 
        *ret = TAKE_PTR(result);
        return 0;
}
 
static int service_setup_luo_sessions(Service *s) {
        int r;
 
        assert(s);
 
        /* For each configured LUOSession=, create a fresh LUO session and hand it to the service via the fd
         * store (and thus LISTEN_FDS, with the configured name as FDNAME). The kernel-level session name is
         * derived deterministically from the unit and the configured name so it stays stable and fits the
         * kernel's length limit. */
 
        if (strv_isempty(s->luo_sessions))
                return 0;
 
        if (!MANAGER_IS_SYSTEM(UNIT(s)->manager)) {
                log_unit_debug(UNIT(s), "LUOSession= is only supported in the system manager, ignoring.");
                return 0;
        }
 
        _cleanup_close_ int device_fd = luo_open_device();
        if (device_fd < 0) {
                if (ERRNO_IS_NEG_DEVICE_ABSENT(device_fd)) {
                        log_unit_debug_errno(UNIT(s), device_fd, "No /dev/liveupdate device found, not handing out LUO sessions.");
                        return 0;
                }
                return log_unit_warning_errno(UNIT(s), device_fd, "Failed to open /dev/liveupdate: %m");
        }
 
        STRV_FOREACH(name, s->luo_sessions) {
                _cleanup_free_ char *session_name = NULL;
                _cleanup_close_ int session_fd = -EBADF;
                bool already_given_out = false;
 
                LIST_FOREACH(fd_store, fs, s->fd_store)
                        if (streq_ptr(fs->fdname, *name) && fd_is_luo_session(fs->fd) > 0) {
                                already_given_out = true;
                                break;
                        }
                if (already_given_out)
                        continue;
 
                r = service_build_luo_session_name(s, *name, &session_name);
                if (r < 0)
                        return log_unit_warning_errno(UNIT(s), r, "Failed to build LUO session name for '%s': %m", *name);
 
                session_fd = luo_create_session(device_fd, session_name);
                if (session_fd < 0) {
                        log_unit_warning_errno(UNIT(s), session_fd, "Failed to create LUO session '%s', ignoring: %m", session_name);
                        continue;
                }
 
                r = service_add_fd_store(s, TAKE_FD(session_fd), *name, /* do_poll= */ false, /* propagate_upstream= */ false);
                if (r < 0)
                        return log_unit_warning_errno(UNIT(s), r, "Failed to hand out LUO session '%s': %m", *name);
 
                log_unit_debug(UNIT(s), "Handed out LUO session '%s' (kernel name '%s').", *name, session_name);
        }
 
        return 0;
}
 
int service_propagate_fd_store_mapping_upstream(Manager *m) {
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *root = NULL;
        _cleanup_close_ int fd = -EBADF;
        _cleanup_free_ char *text = NULL;
        Unit *u;
        int r;
 
        assert(m);
 
        /* Build a JSON object listing all fdstore entries that have been propagated upstream:
         *
         *   {
         *     "unit-name.service": [
         *       { "name": "fdname1", "index": 1 },
         *       { "name": "fdname2", "index": 2 }
         *     ],
         *     ...
         *   }
         *
         * Push it as a sealed memfd to the upstream supervisor under a fixed FDNAME so it can resolve
         * the per-fd numeric indices back to (unit_id, original fdname) at startup. The mapping is
         * regenerated and re-pushed after every add/remove, so the supervisor's view stays in sync. */
        HASHMAP_FOREACH(u, m->units) {
                _cleanup_(sd_json_variant_unrefp) sd_json_variant *entries = NULL;
                Service *s;
 
                if (u->type != UNIT_SERVICE)
                        continue;
 
                s = SERVICE(u);
                if (!s->fd_store)
                        continue;
 
                LIST_FOREACH(fd_store, fs, s->fd_store) {
                        if (fs->index == 0)
                                continue;
 
                        r = sd_json_variant_append_arraybo(
                                        &entries,
                                        SD_JSON_BUILD_PAIR_STRING("name", fs->fdname),
                                        SD_JSON_BUILD_PAIR_UNSIGNED("index", fs->index));
                        if (r < 0)
                                return log_warning_errno(r, "Failed to build fdstore-mapping JSON entry: %m");
                }
 
                if (!entries)
                        continue;
 
                r = sd_json_variant_set_field(&root, u->id, entries);
                if (r < 0)
                        return log_warning_errno(r, "Failed to add unit to fdstore-mapping JSON: %m");
        }
 
        if (!root) {
                /* Nothing to map: tell the supervisor to drop any previously-pushed mapping memfd
                 * so it doesn't keep stale entries around. Only do this if we have actually pushed
                 * one in the past (i.e. we ever assigned an upstream index, either in this
                 * incarnation or in a previous one whose counter we deserialized), otherwise we
                 * might inadvertently remove a mapping that was just handed back to us via
                 * LISTEN_FDS during a fresh manager startup. */
                if (m->fd_store_upstream_next_index > 0)
                        (void) notify_remove_fd_warn(SERVICE_FDSTORE_MAPPING_FDNAME);
                return 0;
        }
 
        r = sd_json_variant_format(root, /* flags= */ 0, &text);
        if (r < 0)
                return log_warning_errno(r, "Failed to format fdstore-mapping JSON: %m");
 
        fd = memfd_new_and_seal_string(SERVICE_FDSTORE_MAPPING_FDNAME, text);
        if (fd < 0)
                return log_warning_errno(fd, "Failed to create fdstore-mapping memfd: %m");
 
        r = notify_push_fd(fd, SERVICE_FDSTORE_MAPPING_FDNAME);
        if (r < 0)
                return log_warning_errno(r, "Failed to propagate fdstore-mapping to upstream supervisor: %m");
 
        return 0;
}
 
static int service_attach_external_fd_to_fdstore(Unit *u, int fd, const char *fdname, uint64_t index) {
        Service *s = ASSERT_PTR(SERVICE(u));
        int r;
 
        assert(u->type == UNIT_SERVICE);
 
        /* If the unit file is absent, bump the limit by one and force preserve so the fd is
         * accepted and pins the unit until a daemon-reload picks up the unit file or it is
         * explicitly stopped. */
        if (u->load_state == UNIT_NOT_FOUND) {
                s->fd_store_preserve_mode = EXEC_PRESERVE_YES;
                s->n_fd_store_max++;
        }
 
        /* Don't propagate upstream: the fd just came back from upstream, forwarding it would loop. */
        r = service_add_fd_store(s, fd, fdname, /* do_poll= */ true, /* propagate_upstream= */ false);
        if (r <= 0 && u->load_state == UNIT_NOT_FOUND)
                s->n_fd_store_max--;
        if (r < 0)
                return log_unit_debug_errno(u, r, "Failed to add LUO fd '%s' to fd store: %m", fdname);
 
        /* If the fd was previously propagated to an upstream supervisor under a numeric index,
         * preserve that index on the freshly-added entry so that future FDSTOREREMOVE messages
         * (and the fdstore-mapping memfd we re-push to the supervisor) reference the same index
         * the supervisor already knows about. service_add_fd_store() does LIST_PREPEND() on
         * success, so the new entry is at the head. Also keep the manager's allocator counter
         * past the highest restored index, to avoid collisions with newly allocated indices. */
        if (r > 0 && index > 0 && s->fd_store) {
                Manager *m = ASSERT_PTR(u->manager);
 
                s->fd_store->index = index;
                if (index > m->fd_store_upstream_next_index)
                        m->fd_store_upstream_next_index = index;
        }
 
        /* If the unit is otherwise inactive (typical for LUO/upstream restore), pin its resources so it
         * isn't garbage-collected before something explicitly stops it. Only flip the state when both
         * runtime and deserialized state agree on DEAD, to avoid clobbering a just-deserialized live
         * state (e.g. SERVICE_RUNNING after daemon-reload, where service_coldplug() will set the proper
         * state later). */
        if (r > 0 &&
            s->state == SERVICE_DEAD &&
            s->deserialized_state == SERVICE_DEAD &&
            IN_SET(s->fd_store_preserve_mode, EXEC_PRESERVE_YES, EXEC_PRESERVE_ON_SUCCESS)) {
                service_set_state(s, SERVICE_DEAD_RESOURCES_PINNED);
                s->deserialized_state = SERVICE_DEAD_RESOURCES_PINNED;
        }
 
        if (r > 0)