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 1001–2000 of 6,768

                log_unit_debug(u, "Restored fd '%s'.", fdname);
        return r;
}
 
static void service_remove_fd_store(Service *s, const char *name) {
        assert(s);
        assert(name);
 
        LIST_FOREACH(fd_store, fs, s->fd_store) {
                if (!streq(fs->fdname, name))
                        continue;
 
                log_unit_debug(UNIT(s), "Got explicit request to remove fd %i (%s), closing.", fs->fd, name);
                service_fd_store_unlink_full(fs, /* propagate_upstream= */ true);
        }
}
 
static usec_t service_running_timeout(Service *s) {
        usec_t delta = 0;
 
        assert(s);
 
        if (s->runtime_rand_extra_usec != 0) {
                delta = random_u64_range(s->runtime_rand_extra_usec);
                log_unit_debug(UNIT(s), "Adding delta of %s sec to timeout", FORMAT_TIMESPAN(delta, USEC_PER_SEC));
        }
 
        return usec_add(usec_add(UNIT(s)->active_enter_timestamp.monotonic,
                                 s->runtime_max_usec),
                        delta);
}
 
static int service_arm_timer(Service *s, bool relative, usec_t usec) {
        assert(s);
 
        return unit_arm_timer(UNIT(s), &s->timer_event_source, relative, usec, service_dispatch_timer);
}
 
static int service_verify(Service *s) {
        assert(s);
        assert(UNIT(s)->load_state == UNIT_LOADED);
 
        if (!s->exec_command[SERVICE_EXEC_START] && !s->exec_command[SERVICE_EXEC_STOP] &&
            UNIT(s)->success_action == EMERGENCY_ACTION_NONE)
                /* FailureAction= only makes sense if one of the start or stop commands is specified.
                 * SuccessAction= will be executed unconditionally if no commands are specified. Hence,
                 * either a command or SuccessAction= are required. */
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart=, ExecStop=, or SuccessAction=. Refusing.");
 
        if (s->type != SERVICE_ONESHOT && !s->exec_command[SERVICE_EXEC_START])
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
 
        if (!s->remain_after_exit && !s->exec_command[SERVICE_EXEC_START] && UNIT(s)->success_action == EMERGENCY_ACTION_NONE)
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has no ExecStart= and no SuccessAction= settings and does not have RemainAfterExit=yes set. Refusing.");
 
        if (s->type != SERVICE_ONESHOT && s->exec_command[SERVICE_EXEC_START]->command_next)
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has more than one ExecStart= setting, which is only allowed for Type=oneshot services. Refusing.");
 
        if (s->type == SERVICE_ONESHOT && IN_SET(s->restart, SERVICE_RESTART_ALWAYS, SERVICE_RESTART_ON_SUCCESS))
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has Restart= set to either always or on-success, which isn't allowed for Type=oneshot services. Refusing.");
 
        if (s->type == SERVICE_ONESHOT && s->exit_type == SERVICE_EXIT_CGROUP)
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service has ExitType=cgroup set, which isn't allowed for Type=oneshot services. Refusing.");
 
        if (s->type == SERVICE_DBUS && !s->bus_name)
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service is of type D-Bus but no D-Bus service name has been specified. Refusing.");
 
        if (s->type == SERVICE_FORKING && exec_needs_pid_namespace(&s->exec_context, /* params= */ NULL))
                return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(ENOEXEC), "Service of Type=forking does not support PrivatePIDs=yes. Refusing.");
 
        if (s->usb_function_descriptors && !s->usb_function_strings)
                log_unit_warning(UNIT(s), "Service has USBFunctionDescriptors= setting, but no USBFunctionStrings=. Ignoring.");
 
        if (!s->usb_function_descriptors && s->usb_function_strings)
                log_unit_warning(UNIT(s), "Service has USBFunctionStrings= setting, but no USBFunctionDescriptors=. Ignoring.");
 
        if (s->runtime_max_usec != USEC_INFINITY && s->type == SERVICE_ONESHOT)
                log_unit_warning(UNIT(s), "RuntimeMaxSec= has no effect in combination with Type=oneshot. Ignoring.");
 
        if (s->runtime_max_usec == USEC_INFINITY && s->runtime_rand_extra_usec != 0)
                log_unit_warning(UNIT(s), "Service has RuntimeRandomizedExtraSec= setting, but no RuntimeMaxSec=. Ignoring.");
 
        if (s->type == SERVICE_SIMPLE && s->exec_command[SERVICE_EXEC_START_POST] && exec_context_has_credentials(&s->exec_context))
                log_unit_warning(UNIT(s), "Service uses a combination of Type=simple, ExecStartPost=, and credentials. This could lead to race conditions. Continuing.");
 
        if (s->restart_max_delay_usec == USEC_INFINITY && s->restart_steps > 0)
                log_unit_warning(UNIT(s), "Service has RestartSteps= but no RestartMaxDelaySec= setting. Ignoring.");
 
        if (s->restart_max_delay_usec != USEC_INFINITY && s->restart_steps == 0)
                log_unit_warning(UNIT(s), "Service has RestartMaxDelaySec= but no RestartSteps= setting. Ignoring.");
 
        if (s->restart_max_delay_usec < s->restart_usec) {
                log_unit_warning(UNIT(s), "RestartMaxDelaySec= has a value smaller than RestartSec=, resetting RestartSec= to RestartMaxDelaySec=.");
                s->restart_usec = s->restart_max_delay_usec;
        }
 
        if (s->restart_randomized_delay_usec == USEC_INFINITY) {
                log_unit_warning(UNIT(s), "RestartRandomizedDelaySec= cannot be infinity, ignoring.");
                s->restart_randomized_delay_usec = 0;
        }
 
        if (s->refresh_on_reload_set && s->refresh_on_reload_flags != _SERVICE_REFRESH_ON_RELOAD_ALL) {
                if (FLAGS_SET(s->refresh_on_reload_flags, SERVICE_RELOAD_EXTENSIONS))
                        service_can_reload_extensions(s, /* warn = */ true);
 
                if (FLAGS_SET(s->refresh_on_reload_flags, SERVICE_RELOAD_CREDENTIALS) &&
                    !exec_context_has_credentials(&s->exec_context))
                        log_unit_warning(UNIT(s), "Service has RefreshOnReload=credentials, but no credentials are in use. The credentials tree will be masked which blocks further refreshing. Continuing.");
        }
 
        return 0;
}
 
static int service_add_default_dependencies(Service *s) {
        int r;
 
        assert(s);
 
        if (!UNIT(s)->default_dependencies)
                return 0;
 
        /* Add a number of automatic dependencies useful for the
         * majority of services. */
 
        if (MANAGER_IS_SYSTEM(UNIT(s)->manager)) {
                /* First, pull in the really early boot stuff, and
                 * require it, so that we fail if we can't acquire
                 * it. */
 
                r = unit_add_two_dependencies_by_name(UNIT(s), UNIT_AFTER, UNIT_REQUIRES, SPECIAL_SYSINIT_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
                if (r < 0)
                        return r;
        } else {
 
                /* In the --user instance there's no sysinit.target,
                 * in that case require basic.target instead. */
 
                r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_BASIC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
                if (r < 0)
                        return r;
        }
 
        /* Second, if the rest of the base system is in the same
         * transaction, order us after it, but do not pull it in or
         * even require it. */
        r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_BASIC_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
        if (r < 0)
                return r;
 
        /* Third, add us in for normal shutdown. */
        return unit_add_two_dependencies_by_name(UNIT(s), UNIT_BEFORE, UNIT_CONFLICTS, SPECIAL_SHUTDOWN_TARGET, true, UNIT_DEPENDENCY_DEFAULT);
}
 
static void service_fix_stdio(Service *s) {
        assert(s);
 
        /* Note that EXEC_INPUT_NULL and EXEC_OUTPUT_INHERIT play a special role here: they are both the
         * default value that is subject to automatic overriding triggered by other settings and an explicit
         * choice the user can make. We don't distinguish between these cases currently. */
 
        if (s->exec_context.std_input == EXEC_INPUT_NULL &&
            s->exec_context.stdin_data_size > 0)
                s->exec_context.std_input = EXEC_INPUT_DATA;
 
        if (exec_input_is_inheritable(s->exec_context.std_input))
                return;
 
        /* Override EXEC_OUTPUT_INHERIT with the default stderr/stdout setting if not applicable for
         * given stdin mode. */
 
        if (s->exec_context.std_error == EXEC_OUTPUT_INHERIT &&
            s->exec_context.std_output == EXEC_OUTPUT_INHERIT)
                s->exec_context.std_error = UNIT(s)->manager->defaults.std_error;
 
        if (s->exec_context.std_output == EXEC_OUTPUT_INHERIT)
                s->exec_context.std_output = UNIT(s)->manager->defaults.std_output;
}
 
static int service_setup_bus_name(Service *s) {
        int r;
 
        assert(s);
 
        /* If s->bus_name is not set, then the unit will be refused by service_verify() later. */
        if (!s->bus_name)
                return 0;
 
        if (s->type == SERVICE_DBUS) {
                r = unit_add_dependency_by_name(UNIT(s), UNIT_REQUIRES, SPECIAL_DBUS_SOCKET, true, UNIT_DEPENDENCY_FILE);
                if (r < 0)
                        return log_unit_error_errno(UNIT(s), r, "Failed to add dependency on %s: %m", SPECIAL_DBUS_SOCKET);
 
                /* We always want to be ordered against dbus.socket if both are in the transaction. */
                r = unit_add_dependency_by_name(UNIT(s), UNIT_AFTER, SPECIAL_DBUS_SOCKET, true, UNIT_DEPENDENCY_FILE);
                if (r < 0)
                        return log_unit_error_errno(UNIT(s), r, "Failed to add dependency on %s: %m", SPECIAL_DBUS_SOCKET);
        }
 
        r = unit_watch_bus_name(UNIT(s), s->bus_name);
        if (r == -EEXIST)
                return log_unit_error_errno(UNIT(s), r, "Two services allocated for the same bus name %s, refusing operation.", s->bus_name);
        if (r < 0)
                return log_unit_error_errno(UNIT(s), r, "Cannot watch bus name %s: %m", s->bus_name);
 
        return 0;
}
 
static int service_add_extras(Service *s) {
        int r;
 
        assert(s);
 
        if (s->type == _SERVICE_TYPE_INVALID) {
                /* Figure out a type automatically */
                if (s->bus_name)
                        s->type = SERVICE_DBUS;
                else if (exec_context_has_credentials(&s->exec_context))
                        s->type = SERVICE_EXEC;
                else if (s->exec_command[SERVICE_EXEC_START])
                        s->type = SERVICE_SIMPLE;
                else
                        s->type = SERVICE_ONESHOT;
        }
 
        /* Oneshot services have disabled start timeout by default */
        if (s->type == SERVICE_ONESHOT && !s->start_timeout_defined)
                s->timeout_start_usec = USEC_INFINITY;
 
        service_fix_stdio(s);
 
        r = unit_patch_contexts(UNIT(s));
        if (r < 0)
                return r;
 
        r = unit_add_exec_dependencies(UNIT(s), &s->exec_context);
        if (r < 0)
                return r;
 
        r = unit_set_default_slice(UNIT(s));
        if (r < 0)
                return r;
 
        /* Each configured LUOSession= is handed to the service through the fd store, hence make sure the
         * store is large enough to hold them all. */
        s->n_fd_store_max += strv_length(s->luo_sessions);
 
        /* If the service needs the notify socket, let's enable it automatically. */
        if (s->notify_access == NOTIFY_NONE &&
            (IN_SET(s->type, SERVICE_NOTIFY, SERVICE_NOTIFY_RELOAD) || s->watchdog_usec > 0 || s->n_fd_store_max > 0))
                s->notify_access = NOTIFY_MAIN;
 
        if (!s->refresh_on_reload_set) {
                assert_cc(SERVICE_REFRESH_ON_RELOAD_DEFAULT == SERVICE_RELOAD_EXTENSIONS);
                s->refresh_on_reload_flags = service_can_reload_extensions(s, /* warn = */ false) ? SERVICE_RELOAD_EXTENSIONS : 0;
        }
 
        /* If no OOM policy was explicitly set, then default to the configure default OOM policy. Except when
         * delegation is on, in that case it we assume the payload knows better what to do and can process
         * things in a more focused way. */
        if (s->oom_policy < 0)
                s->oom_policy = s->cgroup_context.delegate ? OOM_CONTINUE : UNIT(s)->manager->defaults.oom_policy;
 
        /* Let the kernel do the killing if that's requested. */
        s->cgroup_context.memory_oom_group = s->oom_policy == OOM_KILL;
 
        r = service_add_default_dependencies(s);
        if (r < 0)
                return r;
 
        r = service_setup_bus_name(s);
        if (r < 0)
                return r;
 
        return 0;
}
 
static int service_load(Unit *u) {
        Service *s = ASSERT_PTR(SERVICE(u));
        int r;
 
        r = unit_load_fragment_and_dropin(u, true);
        if (r < 0)
                return r;
 
        if (u->load_state != UNIT_LOADED)
                return 0;
 
        /* The fragment may have lowered FileDescriptorStoreMax= below the number of fds currently in the
         * store (e.g. fds restored from LUO into a synthesized UNIT_NOT_FOUND service that just got a real
         * fragment via lazy reload, but which now disables the fd store). */
        service_truncate_fd_store(s);
 
        /* This is a new unit? Then let's add in some extras */
        r = service_add_extras(s);
        if (r < 0)
                return r;
 
        return service_verify(s);
}
 
static int service_dump_fd(int fd, const char *fdname, const char *header, FILE *f, const char *prefix) {
        _cleanup_free_ char *path = NULL;
        struct stat st;
        int flags;
 
        assert(fd >= 0);
        assert(fdname);
        assert(header);
        assert(f);
        assert(prefix);
 
        if (fstat(fd, &st) < 0)
                return log_debug_errno(errno, "Failed to stat service fd: %m");
 
        flags = fcntl(fd, F_GETFL);
        if (flags < 0)
                return log_debug_errno(errno, "Failed to get service fd flags: %m");
 
        (void) fd_get_path(fd, &path);
 
        fprintf(f,
                "%s%s '%s' (type=%s; dev=" DEVNUM_FORMAT_STR "; inode=%" PRIu64 "; rdev=" DEVNUM_FORMAT_STR "; path=%s; access=%s)\n",
                prefix,
                header,
                fdname,
                strna(inode_type_to_string(st.st_mode)),
                DEVNUM_FORMAT_VAL(st.st_dev),
                (uint64_t) st.st_ino,
                DEVNUM_FORMAT_VAL(st.st_rdev),
                strna(path),
                strna(accmode_to_string(flags)));
 
        return 0;
}
 
static void service_dump(Unit *u, FILE *f, const char *prefix) {
        Service *s = ASSERT_PTR(SERVICE(u));
        const char *prefix2;
 
        prefix = strempty(prefix);
        prefix2 = strjoina(prefix, "\t");
 
        fprintf(f,
                "%sService State: %s\n"
                "%sResult: %s\n"
                "%sReload Result: %s\n"
                "%sClean Result: %s\n"
                "%sLiveMount Result: %s\n"
                "%sPermissionsStartOnly: %s\n"
                "%sRootDirectoryStartOnly: %s\n"
                "%sRemainAfterExit: %s\n"
                "%sGuessMainPID: %s\n"
                "%sType: %s\n"
                "%sRestart: %s\n"
                "%sNotifyAccess: %s\n"
                "%sNotifyState: %s\n"
                "%sOOMPolicy: %s\n"
                "%sReloadSignal: %s\n",
                prefix, service_state_to_string(s->state),
                prefix, service_result_to_string(s->result),
                prefix, service_result_to_string(s->reload_result),
                prefix, service_result_to_string(s->live_mount_result),
                prefix, service_result_to_string(s->clean_result),
                prefix, yes_no(s->permissions_start_only),
                prefix, yes_no(s->root_directory_start_only),
                prefix, yes_no(s->remain_after_exit),
                prefix, yes_no(s->guess_main_pid),
                prefix, service_type_to_string(s->type),
                prefix, service_restart_to_string(s->restart),
                prefix, notify_access_to_string(service_get_notify_access(s)),
                prefix, notify_state_to_string(s->notify_state),
                prefix, oom_policy_to_string(s->oom_policy),
                prefix, signal_to_string(s->reload_signal));
 
        if (pidref_is_set(&s->control_pid))
                fprintf(f,
                        "%sControl PID: "PID_FMT"\n",
                        prefix, s->control_pid.pid);
 
        if (pidref_is_set(&s->main_pid))
                fprintf(f,
                        "%sMain PID: "PID_FMT"\n"
                        "%sMain PID Known: %s\n"
                        "%sMain PID Alien: %s\n",
                        prefix, s->main_pid.pid,
                        prefix, yes_no(s->main_pid_known),
                        prefix, yes_no(s->main_pid_alien));
 
        if (s->pid_file)
                fprintf(f,
                        "%sPIDFile: %s\n",
                        prefix, s->pid_file);
 
        if (s->bus_name)
                fprintf(f,
                        "%sBusName: %s\n"
                        "%sBus Name Good: %s\n",
                        prefix, s->bus_name,
                        prefix, yes_no(s->bus_name_good));
 
        if (UNIT_ISSET(s->accept_socket))
                fprintf(f,
                        "%sAccept Socket: %s\n",
                        prefix, UNIT_DEREF(s->accept_socket)->id);
 
        fprintf(f,
                "%sRestartSec: %s\n"
                "%sRestartSteps: %u\n"
                "%sRestartMaxDelaySec: %s\n"
                "%sRestartRandomizedDelaySec: %s\n"
                "%sTimeoutStartSec: %s\n"
                "%sTimeoutStopSec: %s\n"
                "%sTimeoutStartFailureMode: %s\n"
                "%sTimeoutStopFailureMode: %s\n",
                prefix, FORMAT_TIMESPAN(s->restart_usec, USEC_PER_SEC),
                prefix, s->restart_steps,
                prefix, FORMAT_TIMESPAN(s->restart_max_delay_usec, USEC_PER_SEC),
                prefix, FORMAT_TIMESPAN(s->restart_randomized_delay_usec, USEC_PER_SEC),
                prefix, FORMAT_TIMESPAN(s->timeout_start_usec, USEC_PER_SEC),
                prefix, FORMAT_TIMESPAN(s->timeout_stop_usec, USEC_PER_SEC),
                prefix, service_timeout_failure_mode_to_string(s->timeout_start_failure_mode),
                prefix, service_timeout_failure_mode_to_string(s->timeout_stop_failure_mode));
 
        if (s->timeout_abort_set)
                fprintf(f,
                        "%sTimeoutAbortSec: %s\n",
                        prefix, FORMAT_TIMESPAN(s->timeout_abort_usec, USEC_PER_SEC));
 
        fprintf(f,
                "%sRuntimeMaxSec: %s\n"
                "%sRuntimeRandomizedExtraSec: %s\n"
                "%sWatchdogSec: %s\n",
                prefix, FORMAT_TIMESPAN(s->runtime_max_usec, USEC_PER_SEC),
                prefix, FORMAT_TIMESPAN(s->runtime_rand_extra_usec, USEC_PER_SEC),
                prefix, FORMAT_TIMESPAN(s->watchdog_usec, USEC_PER_SEC));
 
        kill_context_dump(&s->kill_context, f, prefix);
        exec_context_dump(&s->exec_context, f, prefix);
 
        for (ServiceExecCommand c = 0; c < _SERVICE_EXEC_COMMAND_MAX; c++) {
                if (!s->exec_command[c])
                        continue;
 
                fprintf(f, "%s%s %s:\n",
                        prefix, glyph(GLYPH_ARROW_RIGHT), service_exec_command_to_string(c));
 
                exec_command_dump_list(s->exec_command[c], f, prefix2);
        }
 
        if (s->status_text)
                fprintf(f, "%sStatus Text: %s\n",
                        prefix, s->status_text);
 
        if (s->status_errno > 0)
                fprintf(f, "%sStatus Errno: %s\n",
                        prefix, STRERROR(s->status_errno));
 
        if (s->status_bus_error)
                fprintf(f, "%sStatus Bus Error: %s\n",
                        prefix, s->status_bus_error);
 
        if (s->status_varlink_error)
                fprintf(f, "%sStatus Varlink Error: %s\n",
                        prefix, s->status_varlink_error);
 
        if (s->n_fd_store_max > 0) {
                fprintf(f,
                        "%sFile Descriptor Store Max: %u\n"
                        "%sFile Descriptor Store Pin: %s\n"
                        "%sFile Descriptor Store Current: %zu\n",
                        prefix, s->n_fd_store_max,
                        prefix, exec_preserve_mode_to_string(s->fd_store_preserve_mode),
                        prefix, s->n_fd_store);
 
                LIST_FOREACH(fd_store, i, s->fd_store)
                        (void) service_dump_fd(i->fd,
                                               i->fdname,
                                               i == s->fd_store ? "File Descriptor Store Entry:" : "                            ",
                                               f,
                                               prefix);
        }
 
        FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds)
                (void) service_dump_fd(i->fd,
                                       i->fdname,
                                       i == s->extra_fds ? "Extra File Descriptor Entry:" : "                            ",
                                       f,
                                       prefix);
 
        if (s->root_directory_fd >= 0)
                (void) service_dump_fd(s->root_directory_fd, "Root Directory File Descriptor", "", f, prefix);
 
        if (s->open_files)
                LIST_FOREACH(open_files, of, s->open_files) {
                        _cleanup_free_ char *ofs = NULL;
                        int r;
 
                        r = open_file_to_string(of, &ofs);
                        if (r < 0) {
                                log_debug_errno(r,
                                                "Failed to convert OpenFile= setting to string, ignoring: %m");
                                continue;
                        }
 
                        fprintf(f, "%sOpen File: %s\n", prefix, ofs);
                }
 
        cgroup_context_dump(UNIT(s), f, prefix);
}
 
static int service_is_suitable_main_pid(Service *s, PidRef *pid, int prio) {
        Unit *owner;
        int r;
 
        assert(s);
        assert(pidref_is_set(pid));
 
        /* Checks whether the specified PID is suitable as main PID for this service. returns negative if not, 0 if the
         * PID is questionnable but should be accepted if the source of configuration is trusted. > 0 if the PID is
         * good */
 
        if (pidref_is_self(pid) || pid->pid == 1)
                return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(EPERM), "New main PID "PID_FMT" is the manager, refusing.", pid->pid);
 
        if (pidref_equal(pid, &s->control_pid))
                return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(EPERM), "New main PID "PID_FMT" is the control process, refusing.", pid->pid);
 
        r = pidref_is_alive(pid);
        if (r < 0)
                return log_unit_full_errno(UNIT(s), prio, r, "Failed to check if main PID "PID_FMT" exists or is a zombie: %m", pid->pid);
        if (r == 0)
                return log_unit_full_errno(UNIT(s), prio, SYNTHETIC_ERRNO(ESRCH), "New main PID "PID_FMT" does not exist or is a zombie.", pid->pid);
 
        owner = manager_get_unit_by_pidref(UNIT(s)->manager, pid);
        if (owner == UNIT(s)) {
                log_unit_debug(UNIT(s), "New main PID "PID_FMT" belongs to service, we are happy.", pid->pid);
                return 1; /* Yay, it's definitely a good PID */
        }
 
        return 0; /* Hmm it's a suspicious PID, let's accept it if configuration source is trusted */
}
 
static int service_load_pid_file(Service *s, bool may_warn) {
        _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
        _cleanup_fclose_ FILE *f = NULL;
        _cleanup_free_ char *k = NULL;
        bool questionable_pid_file = false;
        int r, prio = may_warn ? LOG_INFO : LOG_DEBUG;
 
        assert(s);
 
        if (!s->pid_file)
                return -ENOENT;
 
        r = chase_and_fopen_unlocked(s->pid_file, NULL, CHASE_SAFE, "re", NULL, &f);
        if (r == -ENOLINK) {
                log_unit_debug_errno(UNIT(s), r,
                                     "Potentially unsafe symlink chain, will now retry with relaxed checks: %s", s->pid_file);
 
                questionable_pid_file = true;
 
                r = chase_and_fopen_unlocked(s->pid_file, NULL, 0, "re", NULL, &f);
        }
        if (r < 0)
                return log_unit_full_errno(UNIT(s), prio, r,
                                           "Can't open PID file '%s' (yet?) after %s: %m", s->pid_file, service_state_to_string(s->state));
 
        /* Let's read the PID file now that we chased it down. */
        r = read_line(f, LINE_MAX, &k);
        if (r < 0)
                return log_unit_error_errno(UNIT(s), r, "Failed to read PID file '%s': %m", s->pid_file);
 
        r = pidref_set_pidstr(&pidref, k);
        if (r < 0)
                return log_unit_full_errno(UNIT(s), prio, r, "Failed to create reference to PID %s from file '%s': %m", k, s->pid_file);
 
        if (s->main_pid_known && pidref_equal(&pidref, &s->main_pid))
                return 0;
 
        r = service_is_suitable_main_pid(s, &pidref, prio);
        if (r < 0)
                return r;
        if (r == 0) {
                struct stat st;
 
                if (questionable_pid_file)
                        return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EPERM),
                                                    "Refusing to accept PID outside of service control group, acquired through unsafe symlink chain: %s", s->pid_file);
 
                /* Hmm, it's not clear if the new main PID is safe. Let's allow this if the PID file is owned by root */
 
                if (fstat(fileno(f), &st) < 0)
                        return log_unit_error_errno(UNIT(s), errno, "Failed to fstat() PID file '%s': %m", s->pid_file);
 
                if (st.st_uid != getuid())
                        return log_unit_error_errno(UNIT(s), SYNTHETIC_ERRNO(EPERM),
                                                    "New main PID "PID_FMT" from PID file does not belong to service, and PID file is owned by "UID_FMT" (must be owned by "UID_FMT"). Refusing.",
                                                    pidref.pid, st.st_uid, getuid());
 
                log_unit_debug(UNIT(s), "New main PID "PID_FMT" does not belong to service, accepting anyway since PID file is owned by "UID_FMT".",
                               pidref.pid, st.st_uid);
        }
 
        if (s->main_pid_known) {
                log_unit_debug(UNIT(s), "Main PID changing: "PID_FMT" -> "PID_FMT, s->main_pid.pid, pidref.pid);
 
                service_unwatch_main_pid(s);
                s->main_pid_known = false;
        } else
                log_unit_debug(UNIT(s), "Main PID loaded: "PID_FMT, pidref.pid);
 
        r = service_set_main_pidref(s, TAKE_PIDREF(pidref), /* start_timestamp= */ NULL);
        if (r < 0)
                return r;
 
        r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
        if (r < 0) /* FIXME: we need to do something here */
                return log_unit_warning_errno(UNIT(s), r, "Failed to watch PID "PID_FMT" for service: %m", s->main_pid.pid);
 
        return 1;
}
 
static void service_search_main_pid(Service *s) {
        _cleanup_(pidref_done) PidRef pid = PIDREF_NULL;
        int r;
 
        assert(s);
 
        /* If we know it anyway, don't ever fall back to unreliable heuristics */
        if (s->main_pid_known)
                return;
 
        if (!s->guess_main_pid)
                return;
 
        assert(!pidref_is_set(&s->main_pid));
 
        if (unit_search_main_pid(UNIT(s), &pid) < 0)
                return;
 
        log_unit_debug(UNIT(s), "Main PID guessed: "PID_FMT, pid.pid);
        if (service_set_main_pidref(s, TAKE_PIDREF(pid), /* start_timestamp= */ NULL) < 0)
                return;
 
        r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
        if (r < 0)
                /* FIXME: we need to do something here */
                log_unit_warning_errno(UNIT(s), r, "Failed to watch main PID "PID_FMT": %m", s->main_pid.pid);
}
 
static void service_set_state(Service *s, ServiceState state) {
        Unit *u = UNIT(ASSERT_PTR(s));
        ServiceState old_state;
        const UnitActiveState *table;
 
        if (s->state != state)
                bus_unit_send_pending_change_signal(u, false);
 
        table = s->type == SERVICE_IDLE ? state_translation_table_idle : state_translation_table;
 
        old_state = s->state;
        s->state = state;
 
        service_unwatch_pid_file(s);
 
        if (!IN_SET(state,
                    SERVICE_CONDITION, SERVICE_START_PRE, SERVICE_START, SERVICE_START_POST,
                    SERVICE_RUNNING,
                    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,
                    SERVICE_AUTO_RESTART,
                    SERVICE_CLEANING))
                s->timer_event_source = sd_event_source_disable_unref(s->timer_event_source);
 
        if (state != SERVICE_RUNNING_REVALIDATING)
                s->bus_name_grace_event_source = sd_event_source_disable_unref(s->bus_name_grace_event_source);
 
        if (!SERVICE_STATE_WITH_MAIN_PROCESS(state)) {
                service_unwatch_main_pid(s);
                s->main_command = NULL;
        }
 
        if (!SERVICE_STATE_WITH_CONTROL_PROCESS(state)) {
                service_unwatch_control_pid(s);
                s->control_command = NULL;
                s->control_command_id = _SERVICE_EXEC_COMMAND_INVALID;
        }
 
        if (IN_SET(state,
                   SERVICE_DEAD, SERVICE_FAILED,
                   SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED,
                   SERVICE_DEAD_RESOURCES_PINNED))
                unit_unwatch_all_pids(u);
 
        if (state != SERVICE_START)
                s->exec_fd_event_source = sd_event_source_disable_unref(s->exec_fd_event_source);
 
        if (!SERVICE_STATE_WITH_WATCHDOG(state))
                service_stop_watchdog(s);
 
        if (state != SERVICE_MOUNTING) /* Just in case */
                s->mount_request = sd_bus_message_unref(s->mount_request);
 
        if (state == SERVICE_EXITED && !MANAGER_IS_RELOADING(u->manager)) {
                /* For the inactive states unit_notify() will trim the cgroup. But for exit we have to
                 * do that ourselves... */
                unit_prune_cgroup(u);
 
                /* If none of ExecReload= and ExecStop*= is used, we can safely destroy runtime data
                 * as soon as the service enters SERVICE_EXITED. This saves us from keeping the credential mount
                 * for the whole duration of the oneshot service while no processes are actually running,
                 * among other things. */
 
                bool start_only = true;
                for (ServiceExecCommand c = SERVICE_EXEC_RELOAD; c < _SERVICE_EXEC_COMMAND_MAX; c++)
                        if (s->exec_command[c]) {
                                start_only = false;
                                break;
                        }
 
                if (start_only)
                        unit_destroy_runtime_data(u, &s->exec_context, /* destroy_runtime_dir= */ false);
        }
 
        if (old_state != state)
                log_unit_debug(u, "Changed %s -> %s", service_state_to_string(old_state), service_state_to_string(state));
 
        unit_notify(u, table[old_state], table[state], s->reload_result == SERVICE_SUCCESS);
}
 
static usec_t service_coldplug_timeout(Service *s) {
        assert(s);
 
        switch (s->deserialized_state) {
 
        case SERVICE_CONDITION:
        case SERVICE_START_PRE:
        case SERVICE_START:
        case SERVICE_START_POST:
        case SERVICE_REFRESH_EXTENSIONS:
        case SERVICE_REFRESH_CREDENTIALS:
        case SERVICE_RELOAD:
        case SERVICE_RELOAD_SIGNAL:
        case SERVICE_RELOAD_NOTIFY:
        case SERVICE_RELOAD_POST:
        case SERVICE_MOUNTING:
                return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_start_usec);
 
        case SERVICE_RUNNING:
                return service_running_timeout(s);
 
        case SERVICE_STOP:
        case SERVICE_STOP_SIGTERM:
        case SERVICE_STOP_SIGKILL:
        case SERVICE_STOP_POST:
        case SERVICE_FINAL_SIGTERM:
        case SERVICE_FINAL_SIGKILL:
                return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->timeout_stop_usec);
 
        case SERVICE_STOP_WATCHDOG:
        case SERVICE_FINAL_WATCHDOG:
                return usec_add(UNIT(s)->state_change_timestamp.monotonic, service_timeout_abort_usec(s));
 
        case SERVICE_AUTO_RESTART:
                return usec_add(UNIT(s)->inactive_enter_timestamp.monotonic,
                                service_restart_usec_next_jittered(s));
 
        case SERVICE_CLEANING:
                return usec_add(UNIT(s)->state_change_timestamp.monotonic, s->exec_context.timeout_clean_usec);
 
        default:
                return USEC_INFINITY;
        }
}
 
static int service_coldplug(Unit *u) {
        Service *s = SERVICE(u);
        int r;
 
        assert(s);
        /* Ensure we can insert FD store into units at boot */
        assert(IN_SET(s->state, SERVICE_DEAD, SERVICE_DEAD_RESOURCES_PINNED));
 
        if (s->deserialized_state == s->state)
                return 0;
 
        r = service_arm_timer(s, /* relative= */ false, service_coldplug_timeout(s));
        if (r < 0)
                return r;
 
        if (s->deserialized_state == SERVICE_RUNNING_REVALIDATING) {
                r = unit_arm_timer(UNIT(s), &s->bus_name_grace_event_source, /* relative= */ true,
                                   SERVICE_BUS_NAME_GRACE_USEC,
                                   service_dispatch_bus_name_grace);
                if (r < 0)
                        return r;
        }
 
        if (pidref_is_set(&s->main_pid) &&
            pidref_is_unwaited(&s->main_pid) > 0 &&
            SERVICE_STATE_WITH_MAIN_PROCESS(s->deserialized_state)) {
                r = unit_watch_pidref(UNIT(s), &s->main_pid, /* exclusive= */ false);
                if (r < 0)
                        return r;
        }
 
        if (pidref_is_set(&s->control_pid) &&
            pidref_is_unwaited(&s->control_pid) > 0 &&
            SERVICE_STATE_WITH_CONTROL_PROCESS(s->deserialized_state)) {
                r = unit_watch_pidref(UNIT(s), &s->control_pid, /* exclusive= */ false);
                if (r < 0)
                        return r;
        }
 
        if (!IN_SET(s->deserialized_state,
                    SERVICE_DEAD, SERVICE_FAILED,
                    SERVICE_DEAD_BEFORE_AUTO_RESTART, SERVICE_FAILED_BEFORE_AUTO_RESTART, SERVICE_AUTO_RESTART, SERVICE_AUTO_RESTART_QUEUED,
                    SERVICE_CLEANING,
                    SERVICE_DEAD_RESOURCES_PINNED))
                (void) unit_setup_exec_runtime(u);
 
        if (SERVICE_STATE_WITH_WATCHDOG(s->deserialized_state) &&
            freezer_state_objective(u->freezer_state) == FREEZER_RUNNING)
                service_start_watchdog(s);
 
        if (UNIT_ISSET(s->accept_socket)) {
                Socket *socket = SOCKET(UNIT_DEREF(s->accept_socket));
 
                if (socket->max_connections_per_source > 0) {
                        SocketPeer *peer;
 
                        /* Make a best-effort attempt at bumping the connection count */
                        if (socket_acquire_peer(socket, s->socket_fd, &peer) > 0) {
                                socket_peer_unref(s->socket_peer);
                                s->socket_peer = peer;
                        }
                }
        }
 
        service_set_state(s, s->deserialized_state);
        return 0;
}
 
static int service_collect_fds(
                Service *s,
                int **fds,
                char ***fd_names,
                size_t *n_socket_fds,
                size_t *n_stashed_fds) {
 
        _cleanup_strv_free_ char **rfd_names = NULL;
        _cleanup_free_ int *rfds = NULL;
        size_t rn_socket_fds = 0;
        int r;
 
        assert(s);
        assert(fds);
        assert(fd_names);
        assert(n_socket_fds);
 
        if (s->socket_fd >= 0) {
                Socket *sock = ASSERT_PTR(SOCKET(UNIT_DEREF(s->accept_socket)));
 
                /* Pass the per-connection socket */
 
                rfds = newdup(int, &s->socket_fd, 1);
                if (!rfds)
                        return -ENOMEM;
 
                rfd_names = strv_new(socket_fdname(sock));
                if (!rfd_names)
                        return -ENOMEM;
 
                rn_socket_fds = 1;
        } else {
                /* Pass all our configured sockets for singleton services */
 
                Unit *u;
                UNIT_FOREACH_DEPENDENCY(u, UNIT(s), UNIT_ATOM_TRIGGERED_BY) {
                        _cleanup_free_ int *cfds = NULL;
                        int cn_fds;
                        Socket *sock;
 
                        sock = SOCKET(u);
                        if (!sock)
                                continue;
 
                        cn_fds = socket_collect_fds(sock, &cfds);
                        if (cn_fds < 0)
                                return cn_fds;
                        if (cn_fds == 0)
                                continue;
 
                        if (!rfds) {
                                rfds = TAKE_PTR(cfds);
                                rn_socket_fds = cn_fds;
                        } else if (!GREEDY_REALLOC_APPEND(rfds, rn_socket_fds, cfds, cn_fds))
                                return -ENOMEM;
 
                        r = strv_extend_n(&rfd_names, socket_fdname(sock), cn_fds);
                        if (r < 0)
                                return r;
                }
        }
 
        if (n_stashed_fds && s->n_fd_store + s->n_extra_fds > 0) {
                int *t = reallocarray(rfds, rn_socket_fds + s->n_fd_store + s->n_extra_fds, sizeof(int));
                if (!t)
                        return -ENOMEM;
                rfds = t;
 
                char **nl = reallocarray(rfd_names, rn_socket_fds + s->n_fd_store + s->n_extra_fds + 1, sizeof(char *));
                if (!nl)
                        return -ENOMEM;
                rfd_names = nl;
 
                size_t n_fds = rn_socket_fds;
 
                LIST_FOREACH(fd_store, fs, s->fd_store) {
                        rfds[n_fds] = fs->fd;
                        rfd_names[n_fds] = strdup(fs->fdname);
                        if (!rfd_names[n_fds])
                                return -ENOMEM;
 
                        n_fds++;
                }
 
                FOREACH_ARRAY(i, s->extra_fds, s->n_extra_fds) {
                        rfds[n_fds] = i->fd;
                        rfd_names[n_fds] = strdup(i->fdname);
                        if (!rfd_names[n_fds])
                                return -ENOMEM;
 
                        n_fds++;
                }
 
                rfd_names[n_fds] = NULL;
        }
 
        *fds = TAKE_PTR(rfds);
        *fd_names = TAKE_PTR(rfd_names);
        *n_socket_fds = rn_socket_fds;
        if (n_stashed_fds)
                *n_stashed_fds = s->n_fd_store + s->n_extra_fds;
 
        return 0;
}
 
static int service_allocate_exec_fd_event_source(
                Service *s,
                int fd,
                sd_event_source **ret_event_source) {
 
        _cleanup_(sd_event_source_unrefp) sd_event_source *source = NULL;
        int r;
 
        assert(s);
        assert(fd >= 0);
        assert(ret_event_source);
 
        r = sd_event_add_io(UNIT(s)->manager->event, &source, fd, 0, service_dispatch_exec_io, s);
        if (r < 0)
                return log_unit_error_errno(UNIT(s), r, "Failed to allocate exec_fd event source: %m");
 
        /* This is a bit higher priority than SIGCHLD, to make sure we don't confuse the case "failed to
         * start" from the case "succeeded to start, but failed immediately after". */
 
        r = sd_event_source_set_priority(source, EVENT_PRIORITY_EXEC_FD);
        if (r < 0)
                return log_unit_error_errno(UNIT(s), r, "Failed to adjust priority of exec_fd event source: %m");
 
        (void) sd_event_source_set_description(source, "service exec_fd");
 
        r = sd_event_source_set_io_fd_own(source, true);
        if (r < 0)
                return log_unit_error_errno(UNIT(s), r, "Failed to pass ownership of fd to event source: %m");
 
        *ret_event_source = TAKE_PTR(source);
        return 0;
}
 
static int service_allocate_exec_fd(
                Service *s,
                sd_event_source **ret_event_source,
                int *ret_exec_fd) {
 
        _cleanup_close_pair_ int p[] = EBADF_PAIR;
        int r;
 
        assert(s);
        assert(ret_event_source);
        assert(ret_exec_fd);
 
        if (pipe2(p, O_CLOEXEC|O_NONBLOCK) < 0)
                return log_unit_error_errno(UNIT(s), errno, "Failed to allocate exec_fd pipe: %m");
 
        r = service_allocate_exec_fd_event_source(s, p[0], ret_event_source);