HALF ECHO LEARN / REFERENCE COLLECTION

v262.2

src/run/run.c

123,298 bytesGit mode 100644Download original fileLGPL-2.1-or-later

Git blob: b4b5df1634fa3cb574305a65a1bfab1e48a1c5dd

Lines 2001–3000 of 3,060

        if (r < 0)
                return bus_log_create_error(r);
 
        *message = TAKE_PTR(m);
        return 0;
}
 
static int bus_call_with_hint(
                sd_bus *bus,
                sd_bus_message *message,
                const char *name,
                sd_bus_message **reply) {
 
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        int r;
 
        r = sd_bus_call(bus, message, 0, &error, reply);
        if (r < 0) {
                log_error_errno(r, "Failed to start transient %s unit: %s", name, bus_error_message(&error, r));
 
                if (!arg_expand_environment &&
                    sd_bus_error_has_names(&error,
                                           SD_BUS_ERROR_UNKNOWN_PROPERTY,
                                           SD_BUS_ERROR_PROPERTY_READ_ONLY))
                        log_notice_errno(r, "Hint: --expand-environment=no is not supported by old systemd");
        }
 
        return r;
}
 
static int acquire_invocation_id(sd_bus *bus, const char *unit, sd_id128_t *ret) {
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
        _cleanup_free_ char *object = NULL;
        int r;
 
        assert(bus);
        assert(ret);
 
        if (unit) {
                object = unit_dbus_path_from_name(unit);
                if (!object)
                        return log_oom();
        }
 
        r = sd_bus_get_property(bus,
                                "org.freedesktop.systemd1",
                                object ?: "/org/freedesktop/systemd1/unit/self",
                                "org.freedesktop.systemd1.Unit",
                                "InvocationID",
                                &error,
                                &reply,
                                "ay");
        if (r < 0) {
                /* Let's ignore connection errors. This might be caused by that the service manager is being
                 * restarted. Handle this gracefully. */
                if (bus_error_is_connection(&error) || bus_error_is_unknown_service(&error)) {
                        log_debug_errno(r, "Invocation ID request failed due to bus connection problems, ignoring: %s",
                                        bus_error_message(&error, r));
                        *ret = SD_ID128_NULL;
                        return 0;
                }
 
                return log_error_errno(r, "Failed to request invocation ID for unit: %s", bus_error_message(&error, r));
        }
 
        r = bus_message_read_id128(reply, ret);
        if (r < 0)
                return bus_log_parse_error(r);
 
        return r; /* Return true when we get a non-null invocation ID. */
}
 
static int fchown_to_capsule(int fd, const char *capsule) {
        _cleanup_free_ char *p = NULL;
        int r;
 
        assert(fd >= 0);
        assert(capsule);
 
        p = path_join("/run/capsules/", capsule);
        if (!p)
                return -ENOMEM;
 
        struct stat st;
        r = chase_and_stat(p, /* root= */ NULL, CHASE_SAFE|CHASE_PROHIBIT_SYMLINKS, /* ret_path= */ NULL, &st);
        if (r < 0)
                return r;
 
        return fchmod_and_chown(fd, 0600, st.st_uid, st.st_gid);
}
 
static int print_unit_invocation(const char *unit, sd_id128_t invocation_id) {
        _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
        int r;
 
        assert(unit);
 
        if (!sd_json_format_enabled(arg_json_format_flags)) {
                if (sd_id128_is_null(invocation_id))
                        log_info("Running as unit: %s", unit);
                else
                        log_info("Running as unit: %s; invocation ID: " SD_ID128_FORMAT_STR, unit, SD_ID128_FORMAT_VAL(invocation_id));
                return 0;
        }
 
        r = sd_json_variant_set_field_string(&v, "unit", unit);
        if (r < 0)
                return r;
 
        if (!sd_id128_is_null(invocation_id)) {
                r = sd_json_variant_set_field_id128(&v, "invocation_id", invocation_id);
                if (r < 0)
                        return r;
        }
 
        return sd_json_variant_dump(v, arg_json_format_flags, stdout, NULL);
}
 
static int run_context_setup_ptyfwd(RunContext *c) {
        int r;
 
        assert(c);
 
        if (c->pty_fd < 0 || c->forward)
                return 0;
 
        /* Stop agents now that we are online, to avoid TTY conflicts */
        polkit_agent_close();
        ask_password_agent_close();
 
        if (!arg_quiet)
                log_info("Press ^] three times within 1s to disconnect TTY.");
 
        r = pty_forward_new(c->event, c->pty_fd, PTY_FORWARD_IGNORE_INITIAL_VHANGUP, &c->forward);
        if (r < 0)
                return log_error_errno(r, "Failed to create PTY forwarder: %m");
 
        pty_forward_set_hangup_handler(c->forward, pty_forward_handler, c);
 
        /* Make sure to process any TTY events before we process bus events */
        (void) pty_forward_set_priority(c->forward, SD_EVENT_PRIORITY_IMPORTANT);
 
        if (!isempty(arg_background))
                (void) pty_forward_set_background_color(c->forward, arg_background);
 
        (void) pty_forward_set_window_title(c->forward, pty_window_glyph(), arg_host, arg_cmdline);
        return 0;
}
 
static int run_context_show_result(RunContext *c) {
        int r;
 
        assert(c);
 
        _cleanup_(table_unrefp) Table *t = table_new_vertical();
        if (!t)
                return log_oom();
 
        if (!isempty(c->result)) {
                r = table_add_many(
                                t,
                                TABLE_FIELD, "Finished with result",
                                TABLE_STRING, c->result,
                                TABLE_SET_COLOR, streq(c->result, "success") ? ansi_highlight_green() : ansi_highlight_red());
                if (r < 0)
                        return table_log_add_error(r);
        }
 
        if (c->exit_code > 0) {
                r = table_add_cell(
                                t,
                                /* ret_cell= */ NULL,
                                TABLE_FIELD,
                                "Main processes terminated with");
                if (r < 0)
                        return table_log_add_error(r);
 
                r = table_add_cell_stringf(
                                t,
                                /* ret_cell= */ NULL,
                                "code=%s, status=%u/%s",
                                sigchld_code_to_string(c->exit_code),
                                c->exit_status,
                                strna(c->exit_code == CLD_EXITED ?
                                      exit_status_to_string(c->exit_status, EXIT_STATUS_FULL) :
                                      signal_to_string(c->exit_status)));
                if (r < 0)
                        return table_log_add_error(r);
        }
 
        if (timestamp_is_set(c->inactive_enter_usec) &&
            timestamp_is_set(c->inactive_exit_usec) &&
            c->inactive_enter_usec > c->inactive_exit_usec) {
                r = table_add_many(
                                t,
                                TABLE_FIELD, "Service runtime",
                                TABLE_TIMESPAN_MSEC, c->inactive_enter_usec - c->inactive_exit_usec);
                if (r < 0)
                        return table_log_add_error(r);
        }
 
        if (c->cpu_usage_nsec != NSEC_INFINITY) {
                r = table_add_many(
                                t,
                                TABLE_FIELD, "CPU time consumed",
                                TABLE_TIMESPAN_MSEC, DIV_ROUND_UP(c->cpu_usage_nsec, NSEC_PER_USEC));
                if (r < 0)
                        return table_log_add_error(r);
        }
 
        if (c->memory_peak != UINT64_MAX) {
                const char *swap;
 
                if (c->memory_swap_peak != UINT64_MAX)
                        swap = strjoina(" (swap: ", FORMAT_BYTES(c->memory_swap_peak), ")");
                else
                        swap = "";
 
                r = table_add_cell(
                                t,
                                /* ret_cell= */ NULL,
                                TABLE_FIELD, "Memory peak");
                if (r < 0)
                        return table_log_add_error(r);
 
                r = table_add_cell_stringf(
                                t,
                                /* ret_cell= */ NULL,
                                "%s%s",
                                FORMAT_BYTES(c->memory_peak), swap);
                if (r < 0)
                        return table_log_add_error(r);
        }
 
        const char *ip_ingress = NULL, *ip_egress = NULL;
        if (!IN_SET(c->ip_ingress_bytes, 0, UINT64_MAX))
                ip_ingress = strjoina("received ", FORMAT_BYTES(c->ip_ingress_bytes));
        if (!IN_SET(c->ip_egress_bytes, 0, UINT64_MAX))
                ip_egress = strjoina("sent ", FORMAT_BYTES(c->ip_egress_bytes));
 
        if (ip_ingress || ip_egress) {
                r = table_add_cell(
                                t,
                                /* ret_cell= */ NULL,
                                TABLE_FIELD, "IP Traffic");
                if (r < 0)
                        return table_log_add_error(r);
 
                r = table_add_cell_stringf(
                                t,
                                /* ret_cell= */ NULL,
                                "%s%s%s", strempty(ip_ingress), ip_ingress && ip_egress ? ", " : "", strempty(ip_egress));
                if (r < 0)
                        return table_log_add_error(r);
        }
 
        const char *io_read = NULL, *io_write = NULL;
        if (!IN_SET(c->io_read_bytes, 0, UINT64_MAX))
                io_read = strjoina("read ", FORMAT_BYTES(c->io_read_bytes));
        if (!IN_SET(c->io_write_bytes, 0, UINT64_MAX))
                io_write = strjoina("written ", FORMAT_BYTES(c->io_write_bytes));
 
        if (io_read || io_write) {
                r = table_add_cell(
                                t,
                                /* ret_cell= */ NULL,
                                TABLE_FIELD, "IO Bytes");
                if (r < 0)
                        return table_log_add_error(r);
 
                r = table_add_cell_stringf(
                                t,
                                /* ret_cell= */ NULL,
                                "%s%s%s", strempty(io_read), io_read && io_write ? ", " : "", strempty(io_write));
                if (r < 0)
                        return table_log_add_error(r);
        }
 
        r = table_print_full(t, stderr, /* flush= */ true);
        if (r < 0)
                return table_log_print_error(r);
 
        return 0;
}
 
static int start_transient_service(sd_bus *bus) {
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
        _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
        _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
        _cleanup_free_ char *pty_path = NULL;
        _cleanup_close_ int peer_fd = -EBADF;
        int r;
 
        assert(bus);
 
        (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
        (void) ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
 
        _cleanup_(run_context_done) RunContext c = {
                .pty_fd = -EBADF,
                .cpu_usage_nsec = NSEC_INFINITY,
                .memory_peak = UINT64_MAX,
                .memory_swap_peak = UINT64_MAX,
                .ip_ingress_bytes = UINT64_MAX,
                .ip_egress_bytes = UINT64_MAX,
                .io_read_bytes = UINT64_MAX,
                .io_write_bytes = UINT64_MAX,
                .inactive_exit_usec = USEC_INFINITY,
                .inactive_enter_usec = USEC_INFINITY,
        };
 
        if (arg_stdio == ARG_STDIO_PTY) {
 
                if (IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_CAPSULE)) {
                        c.pty_fd = openpt_allocate(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK, &pty_path);
                        if (c.pty_fd < 0)
                                return log_error_errno(c.pty_fd, "Failed to acquire pseudo tty: %m");
 
                        peer_fd = pty_open_peer(c.pty_fd, O_RDWR|O_NOCTTY|O_CLOEXEC);
                        if (peer_fd < 0)
                                return log_error_errno(peer_fd, "Failed to open pty peer: %m");
 
                        if (arg_transport == BUS_TRANSPORT_CAPSULE) {
                                /* If we are in capsule mode, we must give the capsule UID/GID access to the PTY we just allocated first. */
 
                                r = fchown_to_capsule(peer_fd, arg_host);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to chown tty to capsule UID/GID: %m");
                        }
 
                } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
                        _cleanup_(sd_bus_unrefp) sd_bus *system_bus = NULL;
                        _cleanup_(sd_bus_message_unrefp) sd_bus_message *pty_reply = NULL;
                        const char *s;
 
                        r = sd_bus_default_system(&system_bus);
                        if (r < 0)
                                return log_error_errno(r, "Failed to connect to system bus: %m");
 
                        (void) sd_bus_set_allow_interactive_authorization(system_bus, arg_ask_password);
 
                        /* Chop off a username prefix. We allow this for sd-bus machine connections, hence
                         * support that here too. */
                        _cleanup_free_ char *h = NULL;
                        r = split_user_at_host(arg_host, /* ret_user= */ NULL, &h);
                        if (r < 0)
                                return log_error_errno(r, "Failed to split host specification '%s': %m", arg_host);
 
                        r = bus_call_method(
                                        system_bus,
                                        bus_machine_mgr,
                                        "OpenMachinePTY",
                                        &error,
                                        &pty_reply,
                                        "s", h ?: ".host");
                        if (r < 0)
                                return log_error_errno(r, "Failed to get machine PTY: %s", bus_error_message(&error, r));
 
                        r = sd_bus_message_read(pty_reply, "hs", &c.pty_fd, &s);
                        if (r < 0)
                                return bus_log_parse_error(r);
 
                        c.pty_fd = fcntl(c.pty_fd, F_DUPFD_CLOEXEC, 3);
                        if (c.pty_fd < 0)
                                return log_error_errno(errno, "Failed to duplicate master fd: %m");
 
                        pty_path = strdup(s);
                        if (!pty_path)
                                return log_oom();
 
                        peer_fd = pty_open_peer(c.pty_fd, O_RDWR|O_NOCTTY|O_CLOEXEC);
                        if (peer_fd < 0)
                                return log_error_errno(peer_fd, "Failed to open PTY peer: %m");
                } else
                        assert_not_reached();
        }
 
        if (arg_unit) {
                r = unit_name_mangle_with_suffix(
                                arg_unit,
                                "as unit",
                                (arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN) | UNIT_NAME_MANGLE_STRICT,
                                ".service",
                                &c.unit);
                if (r < 0)
                        return log_error_errno(r, "Failed to mangle unit name: %m");
        } else {
                r = make_unit_name(UNIT_SERVICE, &c.unit);
                if (r < 0)
                        return r;
        }
 
        /* Optionally, wait for the start job to complete. If we are supposed to read the service's stdin
         * lets skip this however, because we should start that already when the start job is running, and
         * there's little point in waiting for the start job to complete in that case anyway, as we'll wait
         * for EOF anyway, which is going to be much later. Similar applies to --wait where we're going
         * to wait for the service to terminate. */
        if (!arg_no_block && !arg_wait && arg_stdio == ARG_STDIO_NONE) {
                r = bus_wait_for_jobs_new(bus, &w);
                if (r < 0)
                        return log_error_errno(r, "Could not watch jobs: %m");
        }
 
        r = make_transient_service_unit(bus, &m, c.unit, pty_path, peer_fd);
        if (r < 0)
                return r;
        peer_fd = safe_close(peer_fd);
 
        _cleanup_(fork_notify_terminate) PidRef journal_pid = PIDREF_NULL;
        if (arg_verbose)
                (void) journal_fork(arg_runtime_scope, STRV_MAKE(c.unit), arg_output, &journal_pid);
 
        r = bus_call_with_hint(bus, m, "service", &reply);
        if (r < 0)
                return r;
 
        const char *object;
        r = sd_bus_message_read(reply, "o", &object);
        if (r < 0)
                return bus_log_parse_error(r);
 
        if (w) {
                r = bus_wait_for_jobs_one(
                                w,
                                object,
                                arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
                                arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
                if (r < 0)
                        return r;
        } else if (!arg_no_block) {
                c.start_job = strdup(object);
                if (!c.start_job)
                        return log_oom();
        }
 
        if (!arg_quiet) {
                sd_id128_t invocation_id;
 
                r = acquire_invocation_id(bus, c.unit, &invocation_id);
                if (r < 0)
                        return r;
 
                r = print_unit_invocation(c.unit, invocation_id);
                if (r < 0)
                        return r;
        }
 
        if (arg_wait || arg_stdio != ARG_STDIO_NONE) {
                c.bus_path = unit_dbus_path_from_name(c.unit);
                if (!c.bus_path)
                        return log_oom();
 
                r = sd_event_default(&c.event);
                if (r < 0)
                        return log_error_errno(r, "Failed to get event loop: %m");
 
                _cleanup_(osc_context_closep) sd_id128_t osc_context_id = SD_ID128_NULL;
                if (c.pty_fd >= 0) {
                        if (arg_exec_user && !terminal_is_dumb()) {
                                r = osc_context_open_chpriv(arg_exec_user, /* ret_seq= */ NULL, &osc_context_id);
                                if (r < 0)
                                        return log_error_errno(r, "Failed to set OSC context: %m");
                        }
 
                        (void) sd_event_set_signal_exit(c.event, true);
 
                        assert(arg_pty_late >= 0);
                        if (!arg_pty_late) { /* If late PTY mode is off, start pty forwarder immediately */
                                r = run_context_setup_ptyfwd(&c);
                                if (r < 0)
                                        return r;
                        }
                }
 
                r = run_context_attach_bus(&c, bus);
                if (r < 0)
                        return r;
 
                r = run_context_update(&c);
                if (r < 0)
                        return r;
 
                r = sd_event_loop(c.event);
                if (r < 0)
                        return log_error_errno(r, "Failed to run event loop: %m");
 
                /* Close the journal watch logic before we output the exit summary */
                fork_notify_terminate(&journal_pid);
 
                if (arg_wait && !arg_quiet)
                        run_context_show_result(&c);
 
                /* Try to propagate the service's return value. But if the service defines
                 * e.g. SuccessExitStatus, honour this, and return 0 to mean "success". */
                if (streq_ptr(c.result, "success"))
                        return EXIT_SUCCESS;
                if (streq_ptr(c.result, "exit-code") && c.exit_status > 0)
                        return c.exit_status;
                if (streq_ptr(c.result, "signal"))
                        return EXIT_EXCEPTION;
                return EXIT_FAILURE;
        }
 
        return EXIT_SUCCESS;
}
 
static int log_scope_group_setup_errno(int r, gid_t gid, const char *message) {
        assert(r < 0);
        assert(message);
 
        if (!ERRNO_IS_PRIVILEGE(r) || gid != getgid())
                return log_error_errno(r, "%s: %m", message);
 
        log_debug_errno(r, "%s, ignoring: %m", message);
        return 0;
}
 
static int start_transient_scope(sd_bus *bus) {
        _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);
        assert(!strv_isempty(arg_cmdline));
 
        r = bus_wait_for_jobs_new(bus, &w);
        if (r < 0)
                return log_error_errno(r, "Could not watch jobs: %m");
 
        if (arg_unit) {
                r = unit_name_mangle_with_suffix(arg_unit, "as unit",
                                                 (arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN) | UNIT_NAME_MANGLE_STRICT,
                                                 ".scope", &scope);
                if (r < 0)
                        return log_error_errno(r, "Failed to mangle scope name: %m");
        } else {
                r = make_unit_name(UNIT_SCOPE, &scope);
                if (r < 0)
                        return r;
        }
 
        (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
        (void) ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
 
        for (;;) {
                _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
                _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
 
                r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
                if (r < 0)
                        return bus_log_create_error(r);
 
                /* Name and Mode */
                r = sd_bus_message_append(m, "ss", scope, job_mode_to_string(arg_job_mode));
                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 = transient_scope_set_properties(m, allow_pidfd);
                if (r < 0)
                        return r;
 
                r = sd_bus_message_close_container(m);
                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 = sd_bus_call(bus, m, /* usec = */ 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)
                return bus_log_parse_error(r);
 
        r = bus_wait_for_jobs_one(w, object, arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
                                  arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
        if (r < 0)
                return r;
 
        r = acquire_invocation_id(bus, NULL, &invocation_id);
        if (r < 0)
                return r;
        if (r == 0)
                log_debug("No invocation ID set.");
        else {
                if (strv_extendf(&user_env, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(invocation_id)) < 0)
                        return log_oom();
        }
 
        /* Stop agents before we pass control away and before we drop privileges, to avoid TTY conflicts and
         * before we become unable to stop agents. */
        polkit_agent_close();
        ask_password_agent_close();
 
        if (arg_nice_set) {
                if (setpriority(PRIO_PROCESS, 0, arg_nice) < 0)
                        return log_error_errno(errno, "Failed to set nice level: %m");
        }
 
        gid_t gid = GID_INVALID;
        if (arg_exec_group) {
                r = get_group_creds(arg_exec_group, /* flags= */ 0, /* ret_name= */ NULL, &gid);
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve group '%s': %s",
                                               arg_exec_group, STRERROR_GROUP(r));
        }
 
        uid_t uid = UID_INVALID;
        if (arg_exec_user) {
                _cleanup_free_ char *user = NULL, *home = NULL, *shell = NULL;
                gid_t user_gid;
 
                r = get_user_creds(arg_exec_user,
                                   USER_CREDS_CLEAN|USER_CREDS_SUPPRESS_PLACEHOLDER|USER_CREDS_PREFER_NSS,
                                   &user, &uid, &user_gid, &home, &shell);
                if (r < 0)
                        return log_error_errno(r, "Failed to resolve user '%s': %s",
                                               arg_exec_user, STRERROR_USER(r));
 
                free_and_replace(arg_exec_user, user);
 
                if (home) {
                        r = strv_extendf(&user_env, "HOME=%s", home);
                        if (r < 0)
                                return log_oom();
                }
 
                if (shell) {
                        r = strv_extendf(&user_env, "SHELL=%s", shell);
                        if (r < 0)
                                return log_oom();
                }
 
                r = strv_extendf(&user_env, "USER=%s", arg_exec_user);
                if (r < 0)
                        return log_oom();
 
                r = strv_extendf(&user_env, "LOGNAME=%s", arg_exec_user);
                if (r < 0)
                        return log_oom();
 
                if (!gid_is_valid(gid))
                        gid = user_gid;
 
                r = initgroups_wrapper(arg_exec_user, gid);
                if (r < 0) {
                        r = log_scope_group_setup_errno(
                                        r,
                                        gid,
                                        strjoina("Failed to initialize supplementary groups for user '", arg_exec_user, "'"));
                        if (r < 0)
                                return r;
                }
        } else if (gid_is_valid(gid)) {
                r = maybe_setgroups(/* size= */ 0, /* list= */ NULL);
                if (r < 0) {
                        r = log_scope_group_setup_errno(r, gid, "Failed to drop supplementary groups");
                        if (r < 0)
                                return r;
                }
        }
 
        if (gid_is_valid(gid) && setresgid(gid, gid, gid) < 0)
                return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
 
        if (uid_is_valid(uid) && setresuid(uid, uid, uid) < 0)
                return log_error_errno(errno, "Failed to change UID to " UID_FMT ": %m", uid);
 
        if (arg_working_directory && chdir(arg_working_directory) < 0)
                return log_error_errno(errno, "Failed to change directory to '%s': %m", arg_working_directory);
 
        env = strv_env_merge(environ, user_env, arg_environment);
        if (!env)
                return log_oom();
 
        if (!arg_quiet) {
                r = print_unit_invocation(scope, invocation_id);
                if (r < 0)
                        return r;
        }
 
        if (arg_expand_environment) {
                _cleanup_strv_free_ char **expanded_cmdline = NULL, **unset_variables = NULL, **bad_variables = NULL;
 
                r = replace_env_argv(arg_cmdline, env, &expanded_cmdline, &unset_variables, &bad_variables);
                if (r < 0)
                        return log_error_errno(r, "Failed to expand environment variables: %m");
 
                free_and_replace(arg_cmdline, expanded_cmdline);
 
                if (!strv_isempty(unset_variables)) {
                        _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
                        log_warning("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_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb));
                }
        }
 
        execvpe(arg_cmdline[0], arg_cmdline, env);
 
        return log_error_errno(errno, "Failed to execute: %m");
}
 
static int make_transient_trigger_unit(
                sd_bus *bus,
                sd_bus_message **message,
                const char *suffix,
                const char *trigger,
                const char *service) {
 
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
        int r;
 
        assert(bus);
        assert(message);
        assert(suffix);
        assert(trigger);
        assert(service);
 
        r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
        if (r < 0)
                return bus_log_create_error(r);
 
        /* Name and Mode */
        r = sd_bus_message_append(m, "ss", trigger, job_mode_to_string(arg_job_mode));
        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);
 
        if (streq(suffix, ".path"))
                r = transient_unit_set_properties(m, UNIT_PATH, arg_path_property);
        else if (streq(suffix, ".socket"))
                r = transient_unit_set_properties(m, UNIT_SOCKET, arg_socket_property);
        else if (streq(suffix, ".timer"))
                r = transient_timer_set_properties(m);
        else
                assert_not_reached();
        if (r < 0)
                return r;
 
        r = sd_bus_message_close_container(m);
        if (r < 0)
                return bus_log_create_error(r);
 
        r = sd_bus_message_open_container(m, 'a', "(sa(sv))");
        if (r < 0)
                return bus_log_create_error(r);
 
        if (!strv_isempty(arg_cmdline)) {
                r = sd_bus_message_open_container(m, 'r', "sa(sv)");
                if (r < 0)
                        return bus_log_create_error(r);
 
                r = sd_bus_message_append(m, "s", service);
                if (r < 0)
                        return bus_log_create_error(r);
 
                r = sd_bus_message_open_container(m, 'a', "(sv)");
                if (r < 0)
                        return bus_log_create_error(r);
 
                r = transient_service_set_properties(m, /* pty_path= */ NULL, /* pty_fd= */ -EBADF);
                if (r < 0)
                        return r;
 
                r = sd_bus_message_close_container(m);
                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);
        }
 
        r = sd_bus_message_close_container(m);
        if (r < 0)
                return bus_log_create_error(r);
 
        *message = TAKE_PTR(m);
        return 0;
}
 
static int start_transient_trigger(sd_bus *bus, const char *suffix) {
        _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
        _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
        _cleanup_free_ char *trigger = NULL, *service = NULL;
        const char *object = NULL;
        int r;
 
        assert(bus);
        assert(suffix);
 
        if (!arg_no_block) {
                r = bus_wait_for_jobs_new(bus, &w);
                if (r < 0)
                        return log_error_errno(r, "Could not watch jobs: %m");
        }
 
        if (arg_unit) {
                UnitType t = unit_name_to_type(arg_unit);
 
                switch (t) {
 
                case UNIT_SERVICE:
                        service = strdup(arg_unit);
                        if (!service)
                                return log_oom();
 
                        r = unit_name_change_suffix(service, suffix, &trigger);
                        if (r < 0)
                                return log_error_errno(r, "Failed to change unit suffix: %m");
                        break;
 
                case UNIT_PATH:
                case UNIT_SOCKET:
                case UNIT_TIMER:
                        if (!streq(suffix + 1, unit_type_to_string(t)))
                                return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
                                                       "Specified unit '%s' does not match requested %s trigger.",
                                                       arg_unit, suffix + 1);
 
                        trigger = strdup(arg_unit);
                        if (!trigger)
                                return log_oom();
 
                        r = unit_name_change_suffix(trigger, ".service", &service);
                        if (r < 0)
                                return log_error_errno(r, "Failed to change unit suffix: %m");
                        break;
 
                default:
                        r = unit_name_mangle_with_suffix(arg_unit, "as unit",
                                                         (arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN) | UNIT_NAME_MANGLE_STRICT,
                                                         ".service", &service);
                        if (r < 0)
                                return log_error_errno(r, "Failed to mangle unit name: %m");
 
                        r = unit_name_mangle_with_suffix(arg_unit, "as trigger",
                                                         (arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN) | UNIT_NAME_MANGLE_STRICT,
                                                         suffix, &trigger);
                        if (r < 0)
                                return log_error_errno(r, "Failed to mangle unit name: %m");
 
                        break;
                }
        } else {
                r = make_unit_name(UNIT_SERVICE, &service);
                if (r < 0)
                        return r;
 
                r = unit_name_change_suffix(service, suffix, &trigger);
                if (r < 0)
                        return log_error_errno(r, "Failed to change unit suffix: %m");
        }
 
        r = make_transient_trigger_unit(bus, &m, suffix, trigger, service);
        if (r < 0)
                return r;
 
        (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
        (void) ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
 
        r = bus_call_with_hint(bus, m, suffix + 1, &reply);
        if (r < 0)
                return r;
 
        r = sd_bus_message_read(reply, "o", &object);
        if (r < 0)
                return bus_log_parse_error(r);
 
        if (w) {
                r = bus_wait_for_jobs_one(w, object, arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
                                          arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
                if (r < 0)
                        return r;
        }
 
        if (!arg_quiet) {
                log_info("Running %s as unit: %s", suffix + 1, trigger);
                if (!strv_isempty(arg_cmdline))
                        log_info("Will run service as unit: %s", service);
        }
 
        return EXIT_SUCCESS;
}
 
static bool shall_make_executable_absolute(void) {
        if (arg_exec_path)
                return false;
        if (strv_isempty(arg_cmdline))
                return false;
        if (arg_transport != BUS_TRANSPORT_LOCAL)
                return false;
        if (!empty_or_root(arg_root_directory))
                return false;
        /* If we're running in a chroot, our view of the filesystem might be completely different from pid1's
         * view of the filesystem, hence don't try to resolve the executable in that case. */
        if (!arg_root_directory && running_in_chroot() > 0)
                return false;
 
        FOREACH_STRING(f, "RootDirectory=", "RootImage=", "RootMStack=", "ExecSearchPath=", "MountImages=", "ExtensionImages=")
                if (strv_find_startswith(arg_property, f))
                        return false;
 
        return true;
}
 
static int polkit_validate(sd_bus *bus) {
        PolkitFlags flags = POLKIT_ALWAYS_QUERY;
        int r;
 
        if (arg_ask_password)
                flags |= POLKIT_ALLOW_INTERACTIVE;
 
        (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
        r = polkit_check_authorization(bus, (uint32_t) (flags & _POLKIT_MASK_PUBLIC), NULL);
        if (r < 0)
                return r;
        if (r == 0) /* not authorized */
                return 1;
 
        return 0;
}
 
static int run(int argc, char* argv[]) {
        _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
        int r;
 
        log_setup();
 
        if (invoked_as(argv, "run0"))
                r = parse_argv_sudo_mode(argc, argv);
        else
                r = parse_argv(argc, argv);
        if (r <= 0)
                return r;
 
        if (shall_make_executable_absolute()) {
                /* Patch in an absolute path to fail early for user convenience, but only when we can do it
                 * (i.e. we will be running from the same file system). This also uses the user's $PATH,
                 * while we use a fixed search path in the manager. */
 
                _cleanup_free_ char *command = NULL;
                r = find_executable(arg_cmdline[0], &command);
                if (ERRNO_IS_NEG_PRIVILEGE(r))
                        log_debug_errno(r, "Failed to find executable '%s' due to permission problems, leaving path as is: %m", arg_cmdline[0]);
                else if (r < 0)
                        return log_error_errno(r, "Failed to find executable %s: %m", arg_cmdline[0]);
                else
                        free_and_replace(arg_cmdline[0], command);
        }
 
        if (!arg_description) {
                _cleanup_free_ char *t = NULL;
 
                if (strv_isempty(arg_cmdline))
                        t = strdup(arg_unit);
                else if (arg_via_shell) {
                        if (arg_cmdline[1])
                                t = quote_command_line(arg_cmdline + 1, SHELL_ESCAPE_EMPTY);
                        else
                                t = strjoin("LOGIN", arg_exec_user ? ": " : NULL, arg_exec_user);
                } else if (startswith(arg_cmdline[0], "-")) {
                        /* Drop the login shell marker from the command line when generating the description,
                         * in order to minimize user confusion. */
                        _cleanup_strv_free_ char **l = strv_copy(arg_cmdline);
                        if (!l)
                                return log_oom();