HALF ECHO LEARN / REFERENCE COLLECTION
v262.2src/run/run.c
Git blob: b4b5df1634fa3cb574305a65a1bfab1e48a1c5dd
Lines 1–1000 of 3,060
/* SPDX-License-Identifier: LGPL-2.1-or-later */
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/mount.h>
#include <sys/resource.h>
#include <sys/stat.h>
#include <unistd.h>
#include "sd-bus-protocol.h"
#include "sd-bus.h"
#include "sd-daemon.h"
#include "sd-event.h"
#include "sd-json.h"
#include "alloc-util.h"
#include "argv-util.h"
#include "ask-password-agent.h"
#include "build.h"
#include "bus-error.h"
#include "bus-locator.h"
#include "bus-map-properties.h"
#include "bus-message-util.h"
#include "bus-polkit.h"
#include "bus-unit-util.h"
#include "bus-util.h"
#include "bus-wait-for-jobs.h"
#include "calendarspec.h"
#include "capability-util.h"
#include "capsule-util.h"
#include "chase.h"
#include "env-util.h"
#include "errno-util.h"
#include "escape.h"
#include "event-util.h"
#include "exec-util.h"
#include "exit-status.h"
#include "fd-util.h"
#include "fork-notify.h"
#include "format-table.h"
#include "format-util.h"
#include "fs-util.h"
#include "hostname-util.h"
#include "log.h"
#include "main-func.h"
#include "osc-context.h"
#include "pager.h"
#include "parse-argument.h"
#include "parse-util.h"
#include "path-util.h"
#include "pidref.h"
#include "polkit-agent.h"
#include "pretty-print.h"
#include "process-util.h"
#include "ptyfwd.h"
#include "run-polkit.h"
#include "runtime-scope.h"
#include "signal-util.h"
#include "special.h"
#include "string-table.h"
#include "string-util.h"
#include "strv.h"
#include "terminal-util.h"
#include "time-util.h"
#include "unit-def.h"
#include "unit-name.h"
#include "user-util.h"
#include "verbs.h"
#include "virt.h"
static bool arg_ask_password = true;
static bool arg_scope = false;
static bool arg_remain_after_exit = false;
static bool arg_no_block = false;
static bool arg_wait = false;
static bool arg_default_command = false;
static bool arg_remove_timestamp = false;
static bool arg_reset_timestamp = false;
static bool arg_validate = false;
static const char *arg_unit = NULL;
static char *arg_description = NULL;
static char *arg_slice = NULL;
static bool arg_slice_inherit = false;
static bool arg_expand_environment = true;
static bool arg_send_sighup = false;
static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
static const char *arg_host = NULL;
static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
static const char *arg_service_type = NULL;
static char *arg_exec_user = NULL;
static const char *arg_exec_group = NULL;
static int arg_nice = 0;
static bool arg_nice_set = false;
static char **arg_environment = NULL;
static char **arg_property = NULL;
static enum {
ARG_STDIO_NONE = 0, /* The default, as it is for normal services, stdin connected to
* /dev/null, and stdout+stderr to the journal */
ARG_STDIO_PTY = 1 << 0, /* Interactive behaviour, requested by --pty/--pty-late: we allocate a pty
* and connect it to the TTY we are invoked from */
ARG_STDIO_DIRECT = 1 << 1, /* Directly pass our stdin/stdout/stderr to the activated service, useful
* for usage in shell pipelines, requested by --pipe */
ARG_STDIO_AUTO = ARG_STDIO_PTY | ARG_STDIO_DIRECT,
/* If --pipe and --pty/--pty-late are used together we use --pty/--pty-late
* when invoked on a TTY, and --pipe otherwise */
} arg_stdio = ARG_STDIO_NONE;
static int arg_pty_late = -1; /* tristate */
static char **arg_path_property = NULL;
static char **arg_socket_property = NULL;
static char **arg_timer_property = NULL;
static bool arg_quiet = false;
static bool arg_verbose = false;
static OutputMode arg_output = _OUTPUT_MODE_INVALID;
static bool arg_aggressive_gc = false;
static char *arg_working_directory = NULL;
static char *arg_root_directory = NULL;
static bool arg_shell = false;
static JobMode arg_job_mode = JOB_FAIL;
static char **arg_cmdline = NULL;
static char *arg_exec_path = NULL;
static bool arg_ignore_failure = false;
static char *arg_background = NULL;
static PagerFlags arg_pager_flags = 0;
static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
static char *arg_shell_prompt_prefix = NULL;
static int arg_lightweight = -1;
static char *arg_area = NULL;
static bool arg_via_shell = false;
static bool arg_empower = false;
STATIC_DESTRUCTOR_REGISTER(arg_description, freep);
STATIC_DESTRUCTOR_REGISTER(arg_slice, freep);
STATIC_DESTRUCTOR_REGISTER(arg_exec_user, freep);
STATIC_DESTRUCTOR_REGISTER(arg_environment, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_property, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_path_property, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_socket_property, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_timer_property, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_working_directory, freep);
STATIC_DESTRUCTOR_REGISTER(arg_cmdline, strv_freep);
STATIC_DESTRUCTOR_REGISTER(arg_exec_path, freep);
STATIC_DESTRUCTOR_REGISTER(arg_background, freep);
STATIC_DESTRUCTOR_REGISTER(arg_shell_prompt_prefix, freep);
STATIC_DESTRUCTOR_REGISTER(arg_area, freep);
COMMAND(
"systemd-run\0",
"Run the specified command in a transient scope or service.",
.argspec = "COMMAND [ARGUMENTS…]\0",
.man_pages = "systemd-run(1)\0",
.option_namespace = "systemd-run",
.pager_flags = &arg_pager_flags,
);
static bool become_root(void) {
if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM)
return false;
if (!arg_exec_user) {
assert(!arg_empower); /* assume default user has been set */
return true;
}
return STR_IN_SET(arg_exec_user, "root", "0");
}
static int add_timer_property(const char *name, const char *val) {
char *p;
assert(name);
assert(val);
p = strjoin(name, "=", val);
if (!p)
return log_oom();
if (strv_consume(&arg_timer_property, p) < 0)
return log_oom();
return 0;
}
static char** make_login_shell_cmdline(const char *shell) {
_cleanup_free_ char *argv0 = NULL;
assert(shell);
argv0 = strjoin("-", shell); /* The - is how shells determine if they shall be consider login shells */
if (!argv0)
return NULL;
return strv_new(argv0);
}
static int parse_argv(int argc, char *argv[]) {
bool with_trigger = false, same_dir = false;
int r;
assert(argc >= 0);
assert(argv);
OptionParser opts = { argc, argv, OPTION_PARSER_STOP_AT_FIRST_NONOPTION, "systemd-run" };
FOREACH_OPTION_OR_RETURN(c, &opts)
switch (c) {
OPTION_NAMESPACE("systemd-run"): {}
OPTION_COMMON_HELP:
return command_print_help_name("systemd-run");
OPTION_COMMON_VERSION:
return version();
OPTION_COMMON_NO_ASK_PASSWORD:
arg_ask_password = false;
break;
OPTION_LONG("user", NULL, "Run as user unit"):
arg_runtime_scope = RUNTIME_SCOPE_USER;
break;
OPTION_LONG("system", NULL, "Talk to the service manager (implied default)"):
arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
break;
OPTION_COMMON_HOST:
arg_transport = BUS_TRANSPORT_REMOTE;
arg_host = opts.arg;
break;
OPTION_COMMON_MACHINE:
r = parse_machine_argument(opts.arg, &arg_host, &arg_transport);
if (r < 0)
return r;
break;
OPTION('C', "capsule", "NAME", "Operate on specified capsule"):
r = capsule_name_is_valid(opts.arg);
if (r < 0)
return log_error_errno(r, "Unable to validate capsule name '%s': %m", opts.arg);
if (r == 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid capsule name: %s", opts.arg);
arg_host = opts.arg;
arg_transport = BUS_TRANSPORT_CAPSULE;
arg_runtime_scope = RUNTIME_SCOPE_USER;
break;
OPTION_LONG("scope", NULL, "Run this as scope rather than service"):
arg_scope = true;
break;
OPTION('u', "unit", "UNIT", "Run under the specified unit name"):
arg_unit = opts.arg;
break;
OPTION('p', "property", "NAME=VALUE", "Set service or scope unit property"):
if (strv_extend(&arg_property, opts.arg) < 0)
return log_oom();
break;
OPTION_LONG("description", "TEXT", "Description for unit"):
r = free_and_strdup_warn(&arg_description, opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("slice", "SLICE", "Run in the specified slice"):
r = free_and_strdup_warn(&arg_slice, opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("slice-inherit", NULL, "Inherit the slice from the caller"):
arg_slice_inherit = true;
break;
OPTION_LONG("expand-environment", "BOOL",
"Control expansion of environment variables"):
r = parse_boolean_argument("--expand-environment=", opts.arg, &arg_expand_environment);
if (r < 0)
return r;
break;
OPTION_LONG("no-block", NULL, "Do not wait until operation finished"):
arg_no_block = true;
break;
OPTION('r', "remain-after-exit", NULL,
"Leave service around until explicitly stopped"):
arg_remain_after_exit = true;
break;
OPTION_LONG("wait", NULL, "Wait until service stopped again"):
arg_wait = true;
break;
OPTION_LONG("send-sighup", NULL, "Send SIGHUP when terminating"):
arg_send_sighup = true;
break;
OPTION_LONG("service-type", "TYPE", "Service type"):
arg_service_type = opts.arg;
break;
OPTION_LONG("uid", "USER", "Run as system user"):
r = free_and_strdup_warn(&arg_exec_user, opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("gid", "GROUP", "Run as system group"):
arg_exec_group = opts.arg;
break;
OPTION_LONG("nice", "NICE", "Nice level"):
r = parse_nice(opts.arg, &arg_nice);
if (r < 0)
return log_error_errno(r, "Failed to parse nice value: %s", opts.arg);
arg_nice_set = true;
break;
OPTION_LONG("working-directory", "PATH", "Set working directory"):
r = parse_path_argument(opts.arg, true, &arg_working_directory);
if (r < 0)
return r;
same_dir = false;
break;
OPTION('d', "same-dir", NULL, "Inherit working directory from caller"): {
_cleanup_free_ char *p = NULL;
r = safe_getcwd(&p);
if (r < 0)
return log_error_errno(r, "Failed to get current working directory: %m");
if (empty_or_root(p))
arg_working_directory = mfree(arg_working_directory);
else
free_and_replace(arg_working_directory, p);
same_dir = true;
break;
}
OPTION_LONG("root-directory", "PATH", "Set root directory"):
r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_root_directory);
if (r < 0)
return r;
break;
OPTION('R', "same-root-dir", NULL, "Inherit root directory from caller"):
r = free_and_strdup_warn(&arg_root_directory, "/");
if (r < 0)
return r;
break;
OPTION('E', "setenv", "NAME[=VALUE]", "Set environment variable"):
r = strv_env_replace_strdup_passthrough(&arg_environment, opts.arg);
if (r < 0)
return log_error_errno(r, "Cannot assign environment variable %s: %m", opts.arg);
break;
OPTION_LONG("tty", NULL, NULL): {} /* deprecated alias for --pty */
OPTION('t', "pty", NULL,
"Run service on pseudo TTY as STDIN/STDOUT/STDERR"): {}
OPTION('T', "pty-late", NULL,
"Just like --pty, but leave TTY access to agents until unit is started up"):
arg_stdio |= ARG_STDIO_PTY;
arg_pty_late = opts.opt->short_code == 'T';
break;
OPTION('P', "pipe", NULL, "Pass STDIN/STDOUT/STDERR directly to service"):
arg_stdio |= ARG_STDIO_DIRECT;
break;
OPTION('q', "quiet", NULL, "Suppress information messages during runtime"):
arg_quiet = true;
break;
OPTION('v', "verbose", NULL, "Show unit logs while executing operation"):
arg_verbose = true;
break;
OPTION_LONG("output", "MODE",
"Controls formatting of verbose logs, see journalctl for valid values"):
if (streq(opts.arg, "help"))
return DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
arg_output = output_mode_from_string(opts.arg);
if (arg_output < 0)
return log_error_errno(arg_output, "Unknown output format '%s'.", opts.arg);
break;
OPTION_COMMON_JSON:
r = parse_json_argument(opts.arg, &arg_json_format_flags);
if (r <= 0)
return r;
break;
OPTION('G', "collect", NULL, "Unload unit after it ran, even when failed"):
arg_aggressive_gc = true;
break;
OPTION('S', "shell", NULL, "Invoke a $SHELL interactively"):
arg_shell = true;
break;
OPTION_LONG("job-mode", "MODE",
"Specify how to deal with already queued jobs, when queueing a new job"):
if (streq(opts.arg, "help"))
return DUMP_STRING_TABLE(job_mode, JobMode, _JOB_MODE_MAX);
r = job_mode_from_string(opts.arg);
if (r < 0)
return log_error_errno(r, "Invalid job mode: %s", opts.arg);
arg_job_mode = r;
break;
OPTION_LONG("ignore-failure", NULL, "Ignore the exit status of the invoked process"):
arg_ignore_failure = true;
break;
OPTION_LONG("background", "COLOR", "Set ANSI color for background"):
r = parse_background_argument(opts.arg, &arg_background);
if (r < 0)
return r;
break;
OPTION_COMMON_NO_PAGER:
arg_pager_flags |= PAGER_DISABLE;
break;
OPTION_GROUP("Path options"): {}
OPTION_LONG("path-property", "NAME=VALUE", "Set path unit property"):
if (strv_extend(&arg_path_property, opts.arg) < 0)
return log_oom();
break;
OPTION_GROUP("Socket options"): {}
OPTION_LONG("socket-property", "NAME=VALUE", "Set socket unit property"):
if (strv_extend(&arg_socket_property, opts.arg) < 0)
return log_oom();
break;
OPTION_GROUP("Timer options"): {}
OPTION_LONG("on-active", "SECONDS", "Run after SECONDS delay"):
r = add_timer_property("OnActiveSec", opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("on-boot", "SECONDS", "Run SECONDS after machine was booted up"):
r = add_timer_property("OnBootSec", opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("on-startup", "SECONDS", "Run SECONDS after systemd activation"):
r = add_timer_property("OnStartupSec", opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("on-unit-active", "SECONDS", "Run SECONDS after the last activation"):
r = add_timer_property("OnUnitActiveSec", opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("on-unit-inactive", "SECONDS",
"Run SECONDS after the last deactivation"):
r = add_timer_property("OnUnitInactiveSec", opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("on-calendar", "SPEC", "Realtime timer"): {
_cleanup_(calendar_spec_freep) CalendarSpec *cs = NULL;
r = calendar_spec_from_string_full(opts.arg, &cs, /* warn_on_weekday_mismatch= */ true);
if (r < 0)
return log_error_errno(r, "Failed to parse calendar event specification: %m");
/* Let's make sure the given calendar event is not in the past */
r = calendar_spec_next_usec(cs, now(CLOCK_REALTIME), NULL);
if (r == -ENOENT) {
/* The calendar event might be in the past, so let's warn about this, but
* install it anyway as is. The service manager will trigger the service
* right away. Moreover, the server side might have a different clock or
* timezone than we do, hence it should decide when or whether to run
* something.
*
* However, a mismatching weekday for a fixed date also results in -ENOENT,
* and was already warned about when parsing. */
if (!calendar_spec_weekday_conflicts(cs, NULL))
log_warning("Specified calendar expression is in the past, proceeding anyway.");
} else if (r < 0)
return log_error_errno(r, "Failed to calculate next time calendar expression elapses: %m");
r = add_timer_property("OnCalendar", opts.arg);
if (r < 0)
return r;
break;
}
OPTION_LONG("on-timezone-change", NULL, "Run when the timezone changes"):
r = add_timer_property("OnTimezoneChange", "yes");
if (r < 0)
return r;
break;
OPTION_LONG("on-clock-change", NULL, "Run when the realtime clock jumps"):
r = add_timer_property("OnClockChange", "yes");
if (r < 0)
return r;
break;
OPTION_LONG("timer-property", "NAME=VALUE", "Set timer unit property"):
if (strv_extend(&arg_timer_property, opts.arg) < 0)
return log_oom();
break;
OPTION_COMMON_INTROSPECT_CLI:
return introspect_cli(arg_json_format_flags);
}
/* If we are talking to the per-user instance PolicyKit isn't going to help */
if (arg_runtime_scope == RUNTIME_SCOPE_USER)
arg_ask_password = false;
size_t n_timer_triggers = 0, n_other_timer_properties = 0;
STRV_FOREACH(i, arg_timer_property)
if (STARTSWITH_SET(*i,
"OnActiveSec=",
"OnBootSec=",
"OnStartupSec=",
"OnUnitActiveSec=",
"OnUnitInactiveSec=",
"OnCalendar=",
"OnClockChange=",
"OnTimezoneChange="))
n_timer_triggers++;
else
n_other_timer_properties++;
if (n_other_timer_properties > 0 && n_timer_triggers == 0)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "--timer-property= set without any timer trigger expression (i.e. On*= setting), refusing.");
with_trigger = arg_path_property || arg_socket_property || arg_timer_property;
/* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
if (!!arg_path_property + !!arg_socket_property + !!arg_timer_property > 1)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Only single trigger (path, socket, timer) unit can be created.");
if (arg_shell) {
/* If --shell is imply --pty --pipe --same-dir --service-type=exec --wait --collect, unless otherwise
* specified. */
if (!arg_scope) {
if (arg_stdio == ARG_STDIO_NONE)
arg_stdio = ARG_STDIO_AUTO;
if (!arg_working_directory) {
r = safe_getcwd(&arg_working_directory);
if (r < 0)
return log_error_errno(r, "Failed to get current working directory: %m");
}
if (!arg_service_type)
arg_service_type = "exec";
arg_wait = true;
}
arg_aggressive_gc = true;
}
if (arg_stdio == ARG_STDIO_AUTO)
/* If we both --pty/--pty-late and --pipe are specified we'll automatically pick --pty/--pty-late if we
* are connected fully to a TTY and pick direct fd passing otherwise. This way, we
* automatically adapt to usage in a shell pipeline, but we are neatly interactive with
* tty-level isolation otherwise. */
arg_stdio = isatty_safe(STDIN_FILENO) && isatty_safe(STDOUT_FILENO) && isatty_safe(STDERR_FILENO) ?
ARG_STDIO_PTY :
ARG_STDIO_DIRECT;
if (arg_pty_late < 0)
arg_pty_late = false; /* For systemd-run this defaults to false, for compat reasons */
char **args = option_parser_get_args(&opts);
if (!strv_isempty(args)) {
char **l;
if (arg_shell)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "If --shell is used, no command line is expected.");
l = strv_copy(args);
if (!l)
return log_oom();
strv_free_and_replace(arg_cmdline, l);
} else if (arg_shell) {
_cleanup_free_ char *s = NULL;
char **l;
r = get_shell(&s);
if (r < 0)
return log_error_errno(r, "Failed to determine shell: %m");
l = strv_new(s);
if (!l)
return log_oom();
strv_free_and_replace(arg_cmdline, l);
} else if (!arg_unit || !with_trigger)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Command line to execute required.");
if (arg_runtime_scope == RUNTIME_SCOPE_USER && arg_transport == BUS_TRANSPORT_REMOTE)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Execution in user context is not supported on remote systems.");
if (arg_scope && arg_transport == BUS_TRANSPORT_REMOTE)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Scope execution is not supported on remote systems.");
if (arg_scope && (arg_remain_after_exit || arg_service_type || arg_ignore_failure))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--remain-after-exit, --service-type= and --ignore-failure are not supported in --scope mode.");
if (arg_scope && arg_no_block)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--no-block is not supported in --scope mode.");
if (arg_stdio != ARG_STDIO_NONE) {
if (with_trigger || arg_scope)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--pty/--pty-late/--pipe is not compatible in trigger (path/socket/timer units) or --scope mode.");
if (arg_transport == BUS_TRANSPORT_REMOTE)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--pty/--pty-late/--pipe is only supported when connecting to the local system or containers.");
if (arg_no_block)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--pty/--pty-late/--pipe is not compatible with --no-block.");
if (arg_remain_after_exit)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--pty/--pty-late/--pipe is not compatible with --remain-after-exit.");
}
if (arg_stdio == ARG_STDIO_PTY && arg_pty_late && streq_ptr(arg_service_type, "oneshot"))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--pty-late is not compatible with --service-type=oneshot.");
if (arg_scope && with_trigger)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"Path, socket or timer options are not supported in --scope mode.");
if (sd_json_format_enabled(arg_json_format_flags)) {
if (arg_scope)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--json= is not supported in --scope mode.");
if (arg_stdio != ARG_STDIO_NONE)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--json= is not compatible with --pty/--pty-late/--pipe.");
if (arg_verbose)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--json= is not compatible with --verbose.");
if (with_trigger)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--json= is not compatible with path, socket or timer operations.");
}
if (arg_wait) {
if (arg_no_block)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--wait may not be combined with --no-block.");
if (with_trigger)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--wait may not be combined with path, socket or timer operations.");
if (arg_scope)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--wait may not be combined with --scope.");
if (arg_remain_after_exit)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--wait may not be combined with --remain-after-exit.");
}
if (arg_scope && arg_root_directory)
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--root-directory= is not supported in --scope mode.");
if (same_dir && arg_root_directory && !path_equal(arg_root_directory, "/"))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
"--same-dir cannot be used with a root directory other than '/'");
return 1;
}
static double shell_prompt_hue(void) {
if (become_root())
return 0; /* red */
if (arg_empower)
return 30; /* orange */
return 60; /* yellow */
}
static Glyph shell_prompt_glyph(void) {
if (become_root())
return GLYPH_SUPERHERO;
if (arg_empower)
return GLYPH_PUMPKIN;
return GLYPH_IDCARD;
}
static Glyph pty_window_glyph(void) {
if (become_root())
return GLYPH_RED_CIRCLE;
if (arg_empower)
return GLYPH_ORANGE_CIRCLE;
return GLYPH_YELLOW_CIRCLE;
}
COMMAND(
"run0\0",
"Elevate privileges interactively.",
.argspec = "COMMAND [ARGUMENTS…]\0",
.man_pages = "run0(1)\0",
.option_namespace = "run0",
.pager_flags = &arg_pager_flags,
);
static int parse_argv_sudo_mode(int argc, char *argv[]) {
int r;
/* If invoked as "run0" binary, let's expose a more sudo-like interface. We add various extensions
* though (but limit the extension to long options).
*
* NB: Let's not go overboard with short options: we try to keep a modicum of compatibility with
* sudo's short switches, hence please do not introduce new short switches unless they have a roughly
* equivalent purpose on sudo. Use long options for everything private to run0. */
assert(argc >= 0);
assert(argv);
OptionParser opts = { argc, argv, OPTION_PARSER_STOP_AT_FIRST_NONOPTION, "run0" };
FOREACH_OPTION_OR_RETURN(c, &opts)
switch (c) {
OPTION_NAMESPACE("run0"): {}
OPTION_COMMON_HELP:
return command_print_help_name("run0");
OPTION_COMMON_VERSION_WITH_V:
return version();
OPTION_COMMON_NO_ASK_PASSWORD:
arg_ask_password = false;
break;
OPTION('n', "non-interactive", NULL, "Do not prompt for password"):
arg_ask_password = false;
break;
OPTION_COMMON_NO_PAGER:
arg_pager_flags |= PAGER_DISABLE;
break;
OPTION_LONG("machine", "CONTAINER", "Operate on local container"):
r = parse_machine_argument(opts.arg, &arg_host, &arg_transport);
if (r < 0)
return r;
break;
OPTION_LONG("unit", "UNIT", "Run under the specified unit name"):
arg_unit = opts.arg;
break;
OPTION_LONG("property", "NAME=VALUE", "Set service or scope unit property"):
if (strv_extend(&arg_property, opts.arg) < 0)
return log_oom();
break;
OPTION_LONG("description", "TEXT", "Description for unit"):
r = free_and_strdup_warn(&arg_description, opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("slice", "SLICE", "Run in the specified slice"):
r = free_and_strdup_warn(&arg_slice, opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("slice-inherit", NULL, "Inherit the slice"):
arg_slice_inherit = true;
break;
OPTION('k', "reset-timestamp", NULL, "Revoke temporary authorization in polkit"):
arg_reset_timestamp = true;
break;
OPTION('K', "remove-timestamp", NULL, "Revoke all temporary authorizations for this user session in polkit"):
arg_remove_timestamp = true;
break;
OPTION('v', "validate", NULL, "Request temporary authorization from polkit"):
arg_validate = true;
break;
OPTION('u', "user", "USER", "Run as system user"):
r = free_and_strdup_warn(&arg_exec_user, opts.arg);
if (r < 0)
return r;
break;
OPTION('g', "group", "GROUP", "Run as system group"):
arg_exec_group = opts.arg;
break;
OPTION_LONG("nice", "NICE", "Nice level"):
r = parse_nice(opts.arg, &arg_nice);
if (r < 0)
return log_error_errno(r, "Failed to parse nice value: %s", opts.arg);
arg_nice_set = true;
break;
OPTION('D', "chdir", "PATH", "Set working directory"):
if (streq(opts.arg, "~"))
r = free_and_strdup_warn(&arg_working_directory, opts.arg);
else
/* Root will be manually suppressed later. */
r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_working_directory);
if (r < 0)
return r;
break;
OPTION_LONG("via-shell", NULL, "Invoke command via target user's login shell"):
arg_via_shell = true;
break;
OPTION_LONG("login", NULL, NULL): {} /* hidden compat alias for -i */
OPTION_SHORT('i', NULL, "Shortcut for --via-shell --chdir='~'"):
r = free_and_strdup_warn(&arg_working_directory, "~");
if (r < 0)
return r;
arg_via_shell = true;
break;
OPTION_LONG("setenv", "NAME[=VALUE]", "Set environment variable"):
r = strv_env_replace_strdup_passthrough(&arg_environment, opts.arg);
if (r < 0)
return log_error_errno(r, "Cannot assign environment variable %s: %m", opts.arg);
break;
OPTION_LONG("background", "COLOR", "Set ANSI color for background"):
r = parse_background_argument(opts.arg, &arg_background);
if (r < 0)
return r;
break;
OPTION_LONG("pty", NULL, "Request allocation of a pseudo TTY for stdio"): {}
OPTION_LONG("pty-late", NULL,
"Just like --pty, but leave TTY access to agents until unit is started up"):
arg_stdio |= ARG_STDIO_PTY;
arg_pty_late = streq(opts.opt->long_code, "pty-late");
break;
OPTION_LONG("pipe", NULL, "Request direct pipe for stdio"):
arg_stdio |= ARG_STDIO_DIRECT;
break;
OPTION_LONG("shell-prompt-prefix", "PREFIX", "Set $SHELL_PROMPT_PREFIX"):
r = free_and_strdup_warn(&arg_shell_prompt_prefix, opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("lightweight", "BOOLEAN",
"Control whether to register a session with service manager or without"):
r = parse_tristate_argument_with_auto("--lightweight=", opts.arg, &arg_lightweight);
if (r < 0)
return r;
break;
OPTION_LONG("area", "AREA", "Home area to log into"):
/* We allow an empty --area= specification to allow logging into the primary home directory */
if (!isempty(opts.arg) && !filename_is_valid(opts.arg))
return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid area name, refusing: %s", opts.arg);
r = free_and_strdup_warn(&arg_area, opts.arg);
if (r < 0)
return r;
break;
OPTION_LONG("empower", NULL, "Give privileges to selected or current user"):
arg_empower = true;
break;
OPTION_LONG("same-root-dir", NULL, NULL): /* hidden */
r = free_and_strdup_warn(&arg_root_directory, "/");
if (r < 0)
return r;
break;
OPTION_COMMON_INTROSPECT_CLI:
return introspect_cli(arg_json_format_flags);
}
if (!arg_working_directory) {
if (arg_exec_user || arg_area) {
/* When switching to a specific user or an area, also switch to its home directory. */
arg_working_directory = strdup("~");
if (!arg_working_directory)
return log_oom();
} else {
/* When elevating privileges without this being specified, then stay in the current directory */
r = safe_getcwd(&arg_working_directory);
if (r < 0)
return log_error_errno(r, "Failed to get current working directory: %m");
}
} else {
/* Root was not suppressed earlier, to allow the above check to work properly. */
if (empty_or_root(arg_working_directory))
arg_working_directory = mfree(arg_working_directory);
}
if (!arg_exec_user) {
/* If the user specifies --area= but not --user= then consider this an area switch request,
* and default to logging into our own account.
*
* If the user specifies --empower but not --user= then consider this a request to empower
* the current user.
*
* If neither --user=, --area= nor --empower is specified, default to switching to root
* explicitly. */
if (arg_area || arg_empower)
arg_exec_user = getusername_malloc();
else
arg_exec_user = strdup("root");
if (!arg_exec_user)
return log_oom();
}
arg_service_type = "exec";
arg_quiet = true;
arg_wait = true;
arg_aggressive_gc = true;
if (IN_SET(arg_stdio, ARG_STDIO_NONE, ARG_STDIO_AUTO))
arg_stdio = isatty_safe(STDIN_FILENO) && isatty_safe(STDOUT_FILENO) && isatty_safe(STDERR_FILENO) ? ARG_STDIO_PTY : ARG_STDIO_DIRECT;
log_debug("Using %s stdio mode.", arg_stdio == ARG_STDIO_PTY ? "pty" : "direct");
if (arg_pty_late < 0)
arg_pty_late = arg_ask_password; /* for run0 this defaults to on, except if --no-ask-password is used */
arg_expand_environment = false;
arg_send_sighup = true;
_cleanup_strv_free_ char **l = NULL;
char **args = option_parser_get_args(&opts);
bool custom_slice = arg_slice_inherit || arg_slice;