1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
12 #include "alloc-util.h"
14 #include "bus-error.h"
15 #include "bus-locator.h"
16 #include "bus-map-properties.h"
17 #include "bus-unit-util.h"
18 #include "bus-wait-for-jobs.h"
19 #include "calendarspec.h"
22 #include "exit-status.h"
24 #include "format-util.h"
25 #include "main-func.h"
26 #include "parse-argument.h"
27 #include "parse-util.h"
28 #include "path-util.h"
29 #include "pretty-print.h"
30 #include "process-util.h"
32 #include "signal-util.h"
33 #include "spawn-polkit-agent.h"
35 #include "terminal-util.h"
37 #include "unit-name.h"
38 #include "user-util.h"
40 static bool arg_ask_password
= true;
41 static bool arg_scope
= false;
42 static bool arg_remain_after_exit
= false;
43 static bool arg_no_block
= false;
44 static bool arg_wait
= false;
45 static const char *arg_unit
= NULL
;
46 static char *arg_description
= NULL
;
47 static const char *arg_slice
= NULL
;
48 static bool arg_slice_inherit
= false;
49 static int arg_expand_environment
= -1;
50 static bool arg_send_sighup
= false;
51 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
52 static const char *arg_host
= NULL
;
53 static RuntimeScope arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
54 static const char *arg_service_type
= NULL
;
55 static const char *arg_exec_user
= NULL
;
56 static const char *arg_exec_group
= NULL
;
57 static int arg_nice
= 0;
58 static bool arg_nice_set
= false;
59 static char **arg_environment
= NULL
;
60 static char **arg_property
= NULL
;
62 ARG_STDIO_NONE
, /* The default, as it is for normal services, stdin connected to /dev/null, and stdout+stderr to the journal */
63 ARG_STDIO_PTY
, /* Interactive behaviour, requested by --pty: we allocate a pty and connect it to the TTY we are invoked from */
64 ARG_STDIO_DIRECT
, /* Directly pass our stdin/stdout/stderr to the activated service, useful for usage in shell pipelines, requested by --pipe */
65 ARG_STDIO_AUTO
, /* If --pipe and --pty are used together we use --pty when invoked on a TTY, and --pipe otherwise */
66 } arg_stdio
= ARG_STDIO_NONE
;
67 static char **arg_path_property
= NULL
;
68 static char **arg_socket_property
= NULL
;
69 static char **arg_timer_property
= NULL
;
70 static bool arg_with_timer
= false;
71 static bool arg_quiet
= false;
72 static bool arg_aggressive_gc
= false;
73 static char *arg_working_directory
= NULL
;
74 static bool arg_shell
= false;
75 static char **arg_cmdline
= NULL
;
76 static char *arg_exec_path
= NULL
;
78 STATIC_DESTRUCTOR_REGISTER(arg_description
, freep
);
79 STATIC_DESTRUCTOR_REGISTER(arg_environment
, strv_freep
);
80 STATIC_DESTRUCTOR_REGISTER(arg_property
, strv_freep
);
81 STATIC_DESTRUCTOR_REGISTER(arg_path_property
, strv_freep
);
82 STATIC_DESTRUCTOR_REGISTER(arg_socket_property
, strv_freep
);
83 STATIC_DESTRUCTOR_REGISTER(arg_timer_property
, strv_freep
);
84 STATIC_DESTRUCTOR_REGISTER(arg_working_directory
, freep
);
85 STATIC_DESTRUCTOR_REGISTER(arg_cmdline
, strv_freep
);
86 STATIC_DESTRUCTOR_REGISTER(arg_exec_path
, freep
);
88 static int help(void) {
89 _cleanup_free_
char *link
= NULL
;
92 r
= terminal_urlify_man("systemd-run", "1", &link
);
96 printf("%1$s [OPTIONS...] COMMAND [ARGUMENTS...]\n"
97 "\n%5$sRun the specified command in a transient scope or service.%6$s\n\n"
98 " -h --help Show this help\n"
99 " --version Show package version\n"
100 " --no-ask-password Do not prompt for password\n"
101 " --user Run as user unit\n"
102 " -H --host=[USER@]HOST Operate on remote host\n"
103 " -M --machine=CONTAINER Operate on local container\n"
104 " --scope Run this as scope rather than service\n"
105 " -u --unit=UNIT Run under the specified unit name\n"
106 " -p --property=NAME=VALUE Set service or scope unit property\n"
107 " --description=TEXT Description for unit\n"
108 " --slice=SLICE Run in the specified slice\n"
109 " --slice-inherit Inherit the slice\n"
110 " --expand-environment=BOOL Control expansion of environment variables\n"
111 " --no-block Do not wait until operation finished\n"
112 " -r --remain-after-exit Leave service around until explicitly stopped\n"
113 " --wait Wait until service stopped again\n"
114 " --send-sighup Send SIGHUP when terminating\n"
115 " --service-type=TYPE Service type\n"
116 " --uid=USER Run as system user\n"
117 " --gid=GROUP Run as system group\n"
118 " --nice=NICE Nice level\n"
119 " --working-directory=PATH Set working directory\n"
120 " -d --same-dir Inherit working directory from caller\n"
121 " -E --setenv=NAME[=VALUE] Set environment variable\n"
122 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
124 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
125 " -q --quiet Suppress information messages during runtime\n"
126 " -G --collect Unload unit after it ran, even when failed\n"
127 " -S --shell Invoke a $SHELL interactively\n"
128 "\n%3$sPath options:%4$s\n"
129 " --path-property=NAME=VALUE Set path unit property\n"
130 "\n%3$sSocket options:%4$s\n"
131 " --socket-property=NAME=VALUE Set socket unit property\n"
132 "\n%3$sTimer options:%4$s\n"
133 " --on-active=SECONDS Run after SECONDS delay\n"
134 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
135 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
136 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
137 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
138 " --on-calendar=SPEC Realtime timer\n"
139 " --on-timezone-change Run when the timezone changes\n"
140 " --on-clock-change Run when the realtime clock jumps\n"
141 " --timer-property=NAME=VALUE Set timer unit property\n"
142 "\nSee the %2$s for details.\n",
143 program_invocation_short_name
,
145 ansi_underline(), ansi_normal(),
146 ansi_highlight(), ansi_normal());
151 static int help_sudo_mode(void) {
152 _cleanup_free_
char *link
= NULL
;
155 r
= terminal_urlify_man("uid0", "1", &link
);
159 printf("%s [OPTIONS...] COMMAND [ARGUMENTS...]\n"
160 "\n%sElevate privileges interactively.%s\n\n"
161 " -h --help Show this help\n"
162 " -V --version Show package version\n"
163 " --no-ask-password Do not prompt for password\n"
164 " --machine=CONTAINER Operate on local container\n"
165 " --unit=UNIT Run under the specified unit name\n"
166 " --property=NAME=VALUE Set service or scope unit property\n"
167 " --description=TEXT Description for unit\n"
168 " --slice=SLICE Run in the specified slice\n"
169 " --slice-inherit Inherit the slice\n"
170 " -u --user=USER Run as system user\n"
171 " -g --group=GROUP Run as system group\n"
172 " --nice=NICE Nice level\n"
173 " -D --chdir=PATH Set working directory\n"
174 " --setenv=NAME[=VALUE] Set environment variable\n"
175 "\nSee the %s for details.\n",
176 program_invocation_short_name
,
184 static int add_timer_property(const char *name
, const char *val
) {
190 p
= strjoin(name
, "=", val
);
194 if (strv_consume(&arg_timer_property
, p
) < 0)
200 static char **make_login_shell_cmdline(const char *shell
) {
201 _cleanup_free_
char *argv0
= NULL
;
205 argv0
= strjoin("-", shell
); /* The - is how shells determine if they shall be consider login shells */
209 return strv_new(argv0
);
212 static int parse_argv(int argc
, char *argv
[]) {
222 ARG_EXPAND_ENVIRONMENT
,
232 ARG_ON_UNIT_INACTIVE
,
234 ARG_ON_TIMEZONE_CHANGE
,
242 ARG_WORKING_DIRECTORY
,
246 static const struct option options
[] = {
247 { "help", no_argument
, NULL
, 'h' },
248 { "version", no_argument
, NULL
, ARG_VERSION
},
249 { "user", no_argument
, NULL
, ARG_USER
},
250 { "system", no_argument
, NULL
, ARG_SYSTEM
},
251 { "scope", no_argument
, NULL
, ARG_SCOPE
},
252 { "unit", required_argument
, NULL
, 'u' },
253 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
254 { "slice", required_argument
, NULL
, ARG_SLICE
},
255 { "slice-inherit", no_argument
, NULL
, ARG_SLICE_INHERIT
},
256 { "remain-after-exit", no_argument
, NULL
, 'r' },
257 { "expand-environment", required_argument
, NULL
, ARG_EXPAND_ENVIRONMENT
},
258 { "send-sighup", no_argument
, NULL
, ARG_SEND_SIGHUP
},
259 { "host", required_argument
, NULL
, 'H' },
260 { "machine", required_argument
, NULL
, 'M' },
261 { "service-type", required_argument
, NULL
, ARG_SERVICE_TYPE
},
262 { "wait", no_argument
, NULL
, ARG_WAIT
},
263 { "uid", required_argument
, NULL
, ARG_EXEC_USER
},
264 { "gid", required_argument
, NULL
, ARG_EXEC_GROUP
},
265 { "nice", required_argument
, NULL
, ARG_NICE
},
266 { "setenv", required_argument
, NULL
, 'E' },
267 { "property", required_argument
, NULL
, 'p' },
268 { "tty", no_argument
, NULL
, 't' }, /* deprecated alias */
269 { "pty", no_argument
, NULL
, 't' },
270 { "pipe", no_argument
, NULL
, 'P' },
271 { "quiet", no_argument
, NULL
, 'q' },
272 { "on-active", required_argument
, NULL
, ARG_ON_ACTIVE
},
273 { "on-boot", required_argument
, NULL
, ARG_ON_BOOT
},
274 { "on-startup", required_argument
, NULL
, ARG_ON_STARTUP
},
275 { "on-unit-active", required_argument
, NULL
, ARG_ON_UNIT_ACTIVE
},
276 { "on-unit-inactive", required_argument
, NULL
, ARG_ON_UNIT_INACTIVE
},
277 { "on-calendar", required_argument
, NULL
, ARG_ON_CALENDAR
},
278 { "on-timezone-change", no_argument
, NULL
, ARG_ON_TIMEZONE_CHANGE
},
279 { "on-clock-change", no_argument
, NULL
, ARG_ON_CLOCK_CHANGE
},
280 { "timer-property", required_argument
, NULL
, ARG_TIMER_PROPERTY
},
281 { "path-property", required_argument
, NULL
, ARG_PATH_PROPERTY
},
282 { "socket-property", required_argument
, NULL
, ARG_SOCKET_PROPERTY
},
283 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
284 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
285 { "collect", no_argument
, NULL
, 'G' },
286 { "working-directory", required_argument
, NULL
, ARG_WORKING_DIRECTORY
},
287 { "same-dir", no_argument
, NULL
, 'd' },
288 { "shell", no_argument
, NULL
, 'S' },
292 bool with_trigger
= false;
298 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
299 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
301 while ((c
= getopt_long(argc
, argv
, "+hrH:M:E:p:tPqGdSu:", options
, NULL
)) >= 0)
311 case ARG_NO_ASK_PASSWORD
:
312 arg_ask_password
= false;
316 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
320 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
331 case ARG_DESCRIPTION
:
332 r
= free_and_strdup(&arg_description
, optarg
);
341 case ARG_SLICE_INHERIT
:
342 arg_slice_inherit
= true;
345 case ARG_EXPAND_ENVIRONMENT
: {
348 r
= parse_boolean_argument("--expand-environment=", optarg
, &b
);
352 arg_expand_environment
= b
;
357 case ARG_SEND_SIGHUP
:
358 arg_send_sighup
= true;
362 arg_remain_after_exit
= true;
366 arg_transport
= BUS_TRANSPORT_REMOTE
;
371 arg_transport
= BUS_TRANSPORT_MACHINE
;
375 case ARG_SERVICE_TYPE
:
376 arg_service_type
= optarg
;
380 arg_exec_user
= optarg
;
384 arg_exec_group
= optarg
;
388 r
= parse_nice(optarg
, &arg_nice
);
390 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
396 r
= strv_env_replace_strdup_passthrough(&arg_environment
, optarg
);
398 return log_error_errno(r
, "Cannot assign environment variable %s: %m", optarg
);
403 if (strv_extend(&arg_property
, optarg
) < 0)
408 case 't': /* --pty */
409 if (IN_SET(arg_stdio
, ARG_STDIO_DIRECT
, ARG_STDIO_AUTO
)) /* if --pipe is already used, upgrade to auto mode */
410 arg_stdio
= ARG_STDIO_AUTO
;
412 arg_stdio
= ARG_STDIO_PTY
;
415 case 'P': /* --pipe */
416 if (IN_SET(arg_stdio
, ARG_STDIO_PTY
, ARG_STDIO_AUTO
)) /* If --pty is already used, upgrade to auto mode */
417 arg_stdio
= ARG_STDIO_AUTO
;
419 arg_stdio
= ARG_STDIO_DIRECT
;
427 r
= add_timer_property("OnActiveSec", optarg
);
431 arg_with_timer
= true;
435 r
= add_timer_property("OnBootSec", optarg
);
439 arg_with_timer
= true;
443 r
= add_timer_property("OnStartupSec", optarg
);
447 arg_with_timer
= true;
450 case ARG_ON_UNIT_ACTIVE
:
451 r
= add_timer_property("OnUnitActiveSec", optarg
);
455 arg_with_timer
= true;
458 case ARG_ON_UNIT_INACTIVE
:
459 r
= add_timer_property("OnUnitInactiveSec", optarg
);
463 arg_with_timer
= true;
466 case ARG_ON_CALENDAR
: {
467 _cleanup_(calendar_spec_freep
) CalendarSpec
*cs
= NULL
;
469 r
= calendar_spec_from_string(optarg
, &cs
);
471 return log_error_errno(r
, "Failed to parse calendar event specification: %m");
473 /* Let's make sure the given calendar event is not in the past */
474 r
= calendar_spec_next_usec(cs
, now(CLOCK_REALTIME
), NULL
);
476 /* The calendar event is in the past — let's warn about this, but install it
477 * anyway as is. The service manager will trigger the service right away.
478 * Moreover, the server side might have a different clock or timezone than we
479 * do, hence it should decide when or whether to run something. */
480 log_warning("Specified calendar expression is in the past, proceeding anyway.");
482 return log_error_errno(r
, "Failed to calculate next time calendar expression elapses: %m");
484 r
= add_timer_property("OnCalendar", optarg
);
488 arg_with_timer
= true;
492 case ARG_ON_TIMEZONE_CHANGE
:
493 r
= add_timer_property("OnTimezoneChange", "yes");
497 arg_with_timer
= true;
500 case ARG_ON_CLOCK_CHANGE
:
501 r
= add_timer_property("OnClockChange", "yes");
505 arg_with_timer
= true;
508 case ARG_TIMER_PROPERTY
:
510 if (strv_extend(&arg_timer_property
, optarg
) < 0)
513 arg_with_timer
= arg_with_timer
||
514 STARTSWITH_SET(optarg
,
519 "OnUnitInactiveSec=",
523 case ARG_PATH_PROPERTY
:
525 if (strv_extend(&arg_path_property
, optarg
) < 0)
530 case ARG_SOCKET_PROPERTY
:
532 if (strv_extend(&arg_socket_property
, optarg
) < 0)
545 case ARG_WORKING_DIRECTORY
:
546 r
= parse_path_argument(optarg
, true, &arg_working_directory
);
553 _cleanup_free_
char *p
= NULL
;
557 return log_error_errno(r
, "Failed to get current working directory: %m");
559 if (empty_or_root(p
))
560 arg_working_directory
= mfree(arg_working_directory
);
562 free_and_replace(arg_working_directory
, p
);
567 arg_aggressive_gc
= true;
578 assert_not_reached();
581 /* If we are talking to the per-user instance PolicyKit isn't going to help */
582 if (arg_runtime_scope
== RUNTIME_SCOPE_USER
)
583 arg_ask_password
= false;
585 with_trigger
= !!arg_path_property
|| !!arg_socket_property
|| arg_with_timer
;
587 /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
588 if ((int) !!arg_path_property
+ (int) !!arg_socket_property
+ (int) arg_with_timer
> 1)
589 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
590 "Only single trigger (path, socket, timer) unit can be created.");
593 /* If --shell is imply --pty --pipe --same-dir --service-type=exec --wait --collect, unless otherwise
597 if (arg_stdio
== ARG_STDIO_NONE
)
598 arg_stdio
= ARG_STDIO_AUTO
;
600 if (!arg_working_directory
) {
601 r
= safe_getcwd(&arg_working_directory
);
603 return log_error_errno(r
, "Failed to get current working directory: %m");
606 if (!arg_service_type
)
607 arg_service_type
= "exec";
612 arg_aggressive_gc
= true;
615 if (arg_stdio
== ARG_STDIO_AUTO
)
616 /* If we both --pty and --pipe are specified we'll automatically pick --pty if we are connected fully
617 * to a TTY and pick direct fd passing otherwise. This way, we automatically adapt to usage in a shell
618 * pipeline, but we are neatly interactive with tty-level isolation otherwise. */
619 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ?
627 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "If --shell is used, no command line is expected.");
629 l
= strv_copy(argv
+ optind
);
633 strv_free_and_replace(arg_cmdline
, l
);
635 } else if (arg_shell
) {
636 _cleanup_free_
char *s
= NULL
;
641 return log_error_errno(r
, "Failed to determine shell: %m");
647 strv_free_and_replace(arg_cmdline
, l
);
649 } else if (!arg_unit
|| !with_trigger
)
650 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Command line to execute required.");
652 if (arg_runtime_scope
== RUNTIME_SCOPE_USER
&& arg_transport
== BUS_TRANSPORT_REMOTE
)
653 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
654 "Execution in user context is not supported on remote systems.");
656 if (arg_scope
&& arg_transport
== BUS_TRANSPORT_REMOTE
)
657 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
658 "Scope execution is not supported on remote systems.");
660 if (arg_scope
&& (arg_remain_after_exit
|| arg_service_type
))
661 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
662 "--remain-after-exit and --service-type= are not supported in --scope mode.");
664 if (arg_stdio
!= ARG_STDIO_NONE
&& (with_trigger
|| arg_scope
))
665 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
666 "--pty/--pipe is not compatible in timer or --scope mode.");
668 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_transport
== BUS_TRANSPORT_REMOTE
)
669 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
670 "--pty/--pipe is only supported when connecting to the local system or containers.");
672 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_no_block
)
673 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
674 "--pty/--pipe is not compatible with --no-block.");
676 if (arg_scope
&& with_trigger
)
677 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
678 "Path, socket or timer options are not supported in --scope mode.");
680 if (arg_timer_property
&& !arg_with_timer
)
681 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
682 "--timer-property= has no effect without any other timer options.");
686 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
687 "--wait may not be combined with --no-block.");
690 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
691 "--wait may not be combined with path, socket or timer operations.");
694 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
695 "--wait may not be combined with --scope.");
701 static int parse_argv_sudo_mode(int argc
, char *argv
[]) {
704 ARG_NO_ASK_PASSWORD
= 0x100,
716 /* If invoked as "uid0" binary, let's expose a more sudo-like interface. We add various extensions
717 * though (but limit the extension to long options). */
719 static const struct option options
[] = {
720 { "help", no_argument
, NULL
, 'h' },
721 { "version", no_argument
, NULL
, 'V' },
722 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
723 { "machine", required_argument
, NULL
, ARG_MACHINE
},
724 { "unit", required_argument
, NULL
, ARG_UNIT
},
725 { "property", required_argument
, NULL
, ARG_PROPERTY
},
726 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
727 { "slice", required_argument
, NULL
, ARG_SLICE
},
728 { "slice-inherit", no_argument
, NULL
, ARG_SLICE_INHERIT
},
729 { "user", required_argument
, NULL
, 'u' },
730 { "group", required_argument
, NULL
, 'g' },
731 { "nice", required_argument
, NULL
, ARG_NICE
},
732 { "chdir", required_argument
, NULL
, 'D' },
733 { "setenv", required_argument
, NULL
, ARG_SETENV
},
742 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
743 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
745 while ((c
= getopt_long(argc
, argv
, "+hVu:g:D:", options
, NULL
)) >= 0)
750 return help_sudo_mode();
755 case ARG_NO_ASK_PASSWORD
:
756 arg_ask_password
= false;
760 arg_transport
= BUS_TRANSPORT_MACHINE
;
769 if (strv_extend(&arg_property
, optarg
) < 0)
774 case ARG_DESCRIPTION
:
775 r
= free_and_strdup_warn(&arg_description
, optarg
);
784 case ARG_SLICE_INHERIT
:
785 arg_slice_inherit
= true;
789 arg_exec_user
= optarg
;
793 arg_exec_group
= optarg
;
797 r
= parse_nice(optarg
, &arg_nice
);
799 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
805 r
= parse_path_argument(optarg
, true, &arg_working_directory
);
812 r
= strv_env_replace_strdup_passthrough(&arg_environment
, optarg
);
814 return log_error_errno(r
, "Cannot assign environment variable %s: %m", optarg
);
822 assert_not_reached();
825 if (!arg_working_directory
) {
827 /* When switching to a specific user, also switch to its home directory. */
828 arg_working_directory
= strdup("~");
829 if (!arg_working_directory
)
832 /* When switching to root without this being specified, then stay in the current directory */
833 r
= safe_getcwd(&arg_working_directory
);
835 return log_error_errno(r
, "Failed to get current working directory: %m");
839 arg_service_type
= "exec";
842 arg_aggressive_gc
= true;
844 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ? ARG_STDIO_PTY
: ARG_STDIO_DIRECT
;
845 arg_expand_environment
= false;
846 arg_send_sighup
= true;
848 _cleanup_strv_free_
char **l
= NULL
;
850 l
= strv_copy(argv
+ optind
);
854 e
= strv_env_get(arg_environment
, "SHELL");
856 arg_exec_path
= strdup(e
);
858 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
859 r
= get_shell(&arg_exec_path
);
861 return log_error_errno(r
, "Failed to determine shell: %m");
863 arg_exec_path
= strdup("/bin/sh");
868 l
= make_login_shell_cmdline(arg_exec_path
);
873 strv_free_and_replace(arg_cmdline
, l
);
876 arg_slice
= strdup("user.slice");
881 _cleanup_free_
char *un
= NULL
;
882 un
= getusername_malloc();
886 /* Set a bunch of environment variables in a roughly sudo-compatible way */
887 r
= strv_env_assign(&arg_environment
, "SUDO_USER", un
);
889 return log_error_errno(r
, "Failed to set $SUDO_USER environment variable: %m");
891 r
= strv_env_assignf(&arg_environment
, "SUDO_UID", UID_FMT
, getuid());
893 return log_error_errno(r
, "Failed to set $SUDO_UID environment variable: %m");
895 r
= strv_env_assignf(&arg_environment
, "SUDO_GID", GID_FMT
, getgid());
897 return log_error_errno(r
, "Failed to set $SUDO_GID environment variable: %m");
899 if (strv_extendf(&arg_property
, "LogExtraFields=ELEVATED_UID=" UID_FMT
, getuid()) < 0)
902 if (strv_extendf(&arg_property
, "LogExtraFields=ELEVATED_GID=" GID_FMT
, getgid()) < 0)
905 if (strv_extendf(&arg_property
, "LogExtraFields=ELEVATED_USER=%s", un
) < 0)
908 if (strv_extend(&arg_property
, "PAMName=systemd-uid0") < 0)
914 static int transient_unit_set_properties(sd_bus_message
*m
, UnitType t
, char **properties
) {
919 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", arg_description
);
921 return bus_log_create_error(r
);
923 if (arg_aggressive_gc
) {
924 r
= sd_bus_message_append(m
, "(sv)", "CollectMode", "s", "inactive-or-failed");
926 return bus_log_create_error(r
);
929 r
= sd_bus_is_bus_client(sd_bus_message_get_bus(m
));
931 return log_error_errno(r
, "Can't determine if bus connection is direct or to broker: %m");
933 /* Pin the object as least as long as we are around. Note that AddRef (currently) only works
934 * if we talk via the bus though. */
935 r
= sd_bus_message_append(m
, "(sv)", "AddRef", "b", 1);
937 return bus_log_create_error(r
);
940 return bus_append_unit_property_assignment_many(m
, t
, properties
);
943 static int transient_cgroup_set_properties(sd_bus_message
*m
) {
944 _cleanup_free_
char *name
= NULL
;
945 _cleanup_free_
char *slice
= NULL
;
949 if (arg_slice_inherit
) {
952 switch (arg_runtime_scope
) {
954 case RUNTIME_SCOPE_USER
:
955 r
= cg_pid_get_user_slice(0, &name
);
958 case RUNTIME_SCOPE_SYSTEM
:
959 r
= cg_pid_get_slice(0, &name
);
963 assert_not_reached();
967 return log_error_errno(r
, "Failed to get PID slice: %m");
969 end
= endswith(name
, ".slice");
975 if (!isempty(arg_slice
) && !strextend_with_separator(&name
, "-", arg_slice
))
981 r
= unit_name_mangle_with_suffix(name
, "as slice",
982 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
985 return log_error_errno(r
, "Failed to mangle name '%s': %m", arg_slice
);
987 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", slice
);
989 return bus_log_create_error(r
);
994 static int transient_kill_set_properties(sd_bus_message
*m
) {
999 if (arg_send_sighup
) {
1000 r
= sd_bus_message_append(m
, "(sv)", "SendSIGHUP", "b", arg_send_sighup
);
1002 return bus_log_create_error(r
);
1008 static int transient_service_set_properties(sd_bus_message
*m
, const char *pty_path
) {
1009 bool send_term
= false;
1012 /* We disable environment expansion on the server side via ExecStartEx=:.
1013 * ExecStartEx was added relatively recently (v243), and some bugs were fixed only later.
1014 * So use that feature only if required. It will fail with older systemds. */
1015 bool use_ex_prop
= arg_expand_environment
== 0;
1019 r
= transient_unit_set_properties(m
, UNIT_SERVICE
, arg_property
);
1023 r
= transient_kill_set_properties(m
);
1027 r
= transient_cgroup_set_properties(m
);
1031 if (arg_remain_after_exit
) {
1032 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit
);
1034 return bus_log_create_error(r
);
1037 if (arg_service_type
) {
1038 r
= sd_bus_message_append(m
, "(sv)", "Type", "s", arg_service_type
);
1040 return bus_log_create_error(r
);
1043 if (arg_exec_user
) {
1044 r
= sd_bus_message_append(m
, "(sv)", "User", "s", arg_exec_user
);
1046 return bus_log_create_error(r
);
1049 if (arg_exec_group
) {
1050 r
= sd_bus_message_append(m
, "(sv)", "Group", "s", arg_exec_group
);
1052 return bus_log_create_error(r
);
1056 r
= sd_bus_message_append(m
, "(sv)", "Nice", "i", arg_nice
);
1058 return bus_log_create_error(r
);
1061 if (arg_working_directory
) {
1062 r
= sd_bus_message_append(m
, "(sv)", "WorkingDirectory", "s", arg_working_directory
);
1064 return bus_log_create_error(r
);
1068 r
= sd_bus_message_append(m
,
1070 "StandardInput", "s", "tty",
1071 "StandardOutput", "s", "tty",
1072 "StandardError", "s", "tty",
1073 "TTYPath", "s", pty_path
);
1075 return bus_log_create_error(r
);
1079 } else if (arg_stdio
== ARG_STDIO_DIRECT
) {
1080 r
= sd_bus_message_append(m
,
1082 "StandardInputFileDescriptor", "h", STDIN_FILENO
,
1083 "StandardOutputFileDescriptor", "h", STDOUT_FILENO
,
1084 "StandardErrorFileDescriptor", "h", STDERR_FILENO
);
1086 return bus_log_create_error(r
);
1088 send_term
= isatty(STDIN_FILENO
) || isatty(STDOUT_FILENO
) || isatty(STDERR_FILENO
);
1096 _cleanup_free_
char *n
= NULL
;
1098 n
= strjoin("TERM=", e
);
1102 r
= sd_bus_message_append(m
,
1104 "Environment", "as", 1, n
);
1106 return bus_log_create_error(r
);
1110 if (!strv_isempty(arg_environment
)) {
1111 r
= sd_bus_message_open_container(m
, 'r', "sv");
1113 return bus_log_create_error(r
);
1115 r
= sd_bus_message_append(m
, "s", "Environment");
1117 return bus_log_create_error(r
);
1119 r
= sd_bus_message_open_container(m
, 'v', "as");
1121 return bus_log_create_error(r
);
1123 r
= sd_bus_message_append_strv(m
, arg_environment
);
1125 return bus_log_create_error(r
);
1127 r
= sd_bus_message_close_container(m
);
1129 return bus_log_create_error(r
);
1131 r
= sd_bus_message_close_container(m
);
1133 return bus_log_create_error(r
);
1136 /* Exec container */
1137 if (!strv_isempty(arg_cmdline
)) {
1138 r
= sd_bus_message_open_container(m
, 'r', "sv");
1140 return bus_log_create_error(r
);
1142 r
= sd_bus_message_append(m
, "s",
1143 use_ex_prop
? "ExecStartEx" : "ExecStart");
1145 return bus_log_create_error(r
);
1147 r
= sd_bus_message_open_container(m
, 'v',
1148 use_ex_prop
? "a(sasas)" : "a(sasb)");
1150 return bus_log_create_error(r
);
1152 r
= sd_bus_message_open_container(m
, 'a',
1153 use_ex_prop
? "(sasas)" : "(sasb)");
1155 return bus_log_create_error(r
);
1157 r
= sd_bus_message_open_container(m
, 'r',
1158 use_ex_prop
? "sasas" : "sasb");
1160 return bus_log_create_error(r
);
1162 r
= sd_bus_message_append(m
, "s", arg_exec_path
?: arg_cmdline
[0]);
1164 return bus_log_create_error(r
);
1166 r
= sd_bus_message_append_strv(m
, arg_cmdline
);
1168 return bus_log_create_error(r
);
1171 r
= sd_bus_message_append_strv(
1173 STRV_MAKE(arg_expand_environment
> 0 ? NULL
: "no-env-expand"));
1175 r
= sd_bus_message_append(m
, "b", false);
1177 return bus_log_create_error(r
);
1179 r
= sd_bus_message_close_container(m
);
1181 return bus_log_create_error(r
);
1183 r
= sd_bus_message_close_container(m
);
1185 return bus_log_create_error(r
);
1187 r
= sd_bus_message_close_container(m
);
1189 return bus_log_create_error(r
);
1191 r
= sd_bus_message_close_container(m
);
1193 return bus_log_create_error(r
);
1199 static int transient_scope_set_properties(sd_bus_message
*m
, bool allow_pidfd
) {
1204 r
= transient_unit_set_properties(m
, UNIT_SCOPE
, arg_property
);
1208 r
= transient_kill_set_properties(m
);
1212 r
= transient_cgroup_set_properties(m
);
1217 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1219 r
= pidref_set_self(&pidref
);
1223 r
= bus_append_scope_pidref(m
, &pidref
);
1225 r
= sd_bus_message_append(
1227 "PIDs", "au", 1, getpid_cached());
1229 return bus_log_create_error(r
);
1234 static int transient_timer_set_properties(sd_bus_message
*m
) {
1239 r
= transient_unit_set_properties(m
, UNIT_TIMER
, arg_timer_property
);
1243 /* Automatically clean up our transient timers */
1244 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterElapse", "b", false);
1246 return bus_log_create_error(r
);
1251 static int make_unit_name(sd_bus
*bus
, UnitType t
, char **ret
) {
1252 const char *unique
, *id
;
1258 assert(t
< _UNIT_TYPE_MAX
);
1260 r
= sd_bus_get_unique_name(bus
, &unique
);
1264 /* We couldn't get the unique name, which is a pretty
1265 * common case if we are connected to systemd
1266 * directly. In that case, just pick a random uuid as
1269 r
= sd_id128_randomize(&rnd
);
1271 return log_error_errno(r
, "Failed to generate random run unit name: %m");
1273 if (asprintf(ret
, "run-r" SD_ID128_FORMAT_STR
".%s", SD_ID128_FORMAT_VAL(rnd
), unit_type_to_string(t
)) < 0)
1279 /* We managed to get the unique name, then let's use that to name our transient units. */
1281 id
= startswith(unique
, ":1."); /* let' strip the usual prefix */
1283 id
= startswith(unique
, ":"); /* the spec only requires things to start with a colon, hence
1284 * let's add a generic fallback for that. */
1286 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1287 "Unique name %s has unexpected format.",
1290 p
= strjoin("run-u", id
, ".", unit_type_to_string(t
));
1298 typedef struct RunContext
{
1301 PTYForward
*forward
;
1304 /* Current state of the unit */
1308 /* The exit data of the unit */
1309 uint64_t inactive_exit_usec
;
1310 uint64_t inactive_enter_usec
;
1312 uint64_t cpu_usage_nsec
;
1313 uint64_t memory_peak
;
1314 uint64_t memory_swap_peak
;
1315 uint64_t ip_ingress_bytes
;
1316 uint64_t ip_egress_bytes
;
1317 uint64_t io_read_bytes
;
1318 uint64_t io_write_bytes
;
1320 uint32_t exit_status
;
1323 static void run_context_free(RunContext
*c
) {
1326 c
->forward
= pty_forward_free(c
->forward
);
1327 c
->match
= sd_bus_slot_unref(c
->match
);
1328 c
->bus
= sd_bus_unref(c
->bus
);
1329 c
->event
= sd_event_unref(c
->event
);
1331 free(c
->active_state
);
1335 static void run_context_check_done(RunContext
*c
) {
1341 done
= STRPTR_IN_SET(c
->active_state
, "inactive", "failed") && !c
->has_job
;
1345 if (c
->forward
&& done
) /* If the service is gone, it's time to drain the output */
1346 done
= pty_forward_drain(c
->forward
);
1349 sd_event_exit(c
->event
, EXIT_SUCCESS
);
1352 static int map_job(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
1358 r
= sd_bus_message_read(m
, "(uo)", &id
, &job
);
1362 *b
= id
!= 0 || !streq(job
, "/");
1366 static int run_context_update(RunContext
*c
, const char *path
) {
1368 static const struct bus_properties_map map
[] = {
1369 { "ActiveState", "s", NULL
, offsetof(RunContext
, active_state
) },
1370 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_exit_usec
) },
1371 { "InactiveEnterTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_enter_usec
) },
1372 { "Result", "s", NULL
, offsetof(RunContext
, result
) },
1373 { "ExecMainCode", "i", NULL
, offsetof(RunContext
, exit_code
) },
1374 { "ExecMainStatus", "i", NULL
, offsetof(RunContext
, exit_status
) },
1375 { "CPUUsageNSec", "t", NULL
, offsetof(RunContext
, cpu_usage_nsec
) },
1376 { "MemoryPeak", "t", NULL
, offsetof(RunContext
, memory_peak
) },
1377 { "MemorySwapPeak", "t", NULL
, offsetof(RunContext
, memory_swap_peak
) },
1378 { "IPIngressBytes", "t", NULL
, offsetof(RunContext
, ip_ingress_bytes
) },
1379 { "IPEgressBytes", "t", NULL
, offsetof(RunContext
, ip_egress_bytes
) },
1380 { "IOReadBytes", "t", NULL
, offsetof(RunContext
, io_read_bytes
) },
1381 { "IOWriteBytes", "t", NULL
, offsetof(RunContext
, io_write_bytes
) },
1382 { "Job", "(uo)", map_job
, offsetof(RunContext
, has_job
) },
1386 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1389 r
= bus_map_all_properties(c
->bus
,
1390 "org.freedesktop.systemd1",
1398 sd_event_exit(c
->event
, EXIT_FAILURE
);
1399 return log_error_errno(r
, "Failed to query unit state: %s", bus_error_message(&error
, r
));
1402 run_context_check_done(c
);
1406 static int on_properties_changed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
1407 RunContext
*c
= ASSERT_PTR(userdata
);
1411 return run_context_update(c
, sd_bus_message_get_path(m
));
1414 static int pty_forward_handler(PTYForward
*f
, int rcode
, void *userdata
) {
1415 RunContext
*c
= userdata
;
1420 sd_event_exit(c
->event
, EXIT_FAILURE
);
1421 return log_error_errno(rcode
, "Error on PTY forwarding logic: %m");
1424 run_context_check_done(c
);
1428 static int make_transient_service_unit(
1430 sd_bus_message
**message
,
1431 const char *service
,
1432 const char *pty_path
) {
1434 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1441 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "StartTransientUnit");
1443 return bus_log_create_error(r
);
1445 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1447 return bus_log_create_error(r
);
1450 r
= sd_bus_message_append(m
, "ss", service
, "fail");
1452 return bus_log_create_error(r
);
1455 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1457 return bus_log_create_error(r
);
1459 r
= transient_service_set_properties(m
, pty_path
);
1463 r
= sd_bus_message_close_container(m
);
1465 return bus_log_create_error(r
);
1467 /* Auxiliary units */
1468 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1470 return bus_log_create_error(r
);
1472 *message
= TAKE_PTR(m
);
1476 static int bus_call_with_hint(
1478 sd_bus_message
*message
,
1480 sd_bus_message
**reply
) {
1482 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1485 r
= sd_bus_call(bus
, message
, 0, &error
, reply
);
1487 log_error_errno(r
, "Failed to start transient %s unit: %s", name
, bus_error_message(&error
, r
));
1489 if (arg_expand_environment
== 0 &&
1490 sd_bus_error_has_names(&error
,
1491 SD_BUS_ERROR_UNKNOWN_PROPERTY
,
1492 SD_BUS_ERROR_PROPERTY_READ_ONLY
))
1493 log_notice_errno(r
, "Hint: --expand-environment=no is not supported by old systemd");
1499 static int acquire_invocation_id(sd_bus
*bus
, const char *unit
, sd_id128_t
*ret
) {
1500 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1501 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1502 _cleanup_free_
char *object
= NULL
;
1511 object
= unit_dbus_path_from_name(unit
);
1516 r
= sd_bus_get_property(bus
,
1517 "org.freedesktop.systemd1",
1518 object
?: "/org/freedesktop/systemd1/unit/self",
1519 "org.freedesktop.systemd1.Unit",
1525 return log_error_errno(r
, "Failed to request invocation ID for unit: %s", bus_error_message(&error
, r
));
1527 r
= sd_bus_message_read_array(reply
, 'y', &p
, &l
);
1529 return bus_log_parse_error(r
);
1532 *ret
= SD_ID128_NULL
;
1533 return 0; /* no uuid set */
1536 if (l
!= sizeof(sd_id128_t
))
1537 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid UUID size, %zu != %zu.", l
, sizeof(sd_id128_t
));
1540 return !sd_id128_is_null(*ret
);
1543 static int start_transient_service(sd_bus
*bus
) {
1544 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1545 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1546 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1547 _cleanup_free_
char *service
= NULL
, *pty_path
= NULL
;
1548 _cleanup_close_
int master
= -EBADF
;
1553 if (arg_stdio
== ARG_STDIO_PTY
) {
1555 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
1556 master
= posix_openpt(O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
1558 return log_error_errno(errno
, "Failed to acquire pseudo tty: %m");
1560 r
= ptsname_malloc(master
, &pty_path
);
1562 return log_error_errno(r
, "Failed to determine tty name: %m");
1564 if (unlockpt(master
) < 0)
1565 return log_error_errno(errno
, "Failed to unlock tty: %m");
1567 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
1568 _cleanup_(sd_bus_unrefp
) sd_bus
*system_bus
= NULL
;
1569 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pty_reply
= NULL
;
1572 r
= sd_bus_default_system(&system_bus
);
1574 return log_error_errno(r
, "Failed to connect to system bus: %m");
1576 r
= bus_call_method(system_bus
,
1583 return log_error_errno(r
, "Failed to get machine PTY: %s", bus_error_message(&error
, r
));
1585 r
= sd_bus_message_read(pty_reply
, "hs", &master
, &s
);
1587 return bus_log_parse_error(r
);
1589 master
= fcntl(master
, F_DUPFD_CLOEXEC
, 3);
1591 return log_error_errno(errno
, "Failed to duplicate master fd: %m");
1593 pty_path
= strdup(s
);
1597 assert_not_reached();
1600 /* Optionally, wait for the start job to complete. If we are supposed to read the service's stdin
1601 * lets skip this however, because we should start that already when the start job is running, and
1602 * there's little point in waiting for the start job to complete in that case anyway, as we'll wait
1603 * for EOF anyway, which is going to be much later. */
1604 if (!arg_no_block
&& arg_stdio
== ARG_STDIO_NONE
) {
1605 r
= bus_wait_for_jobs_new(bus
, &w
);
1607 return log_error_errno(r
, "Could not watch jobs: %m");
1611 r
= unit_name_mangle_with_suffix(arg_unit
, "as unit",
1612 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
1613 ".service", &service
);
1615 return log_error_errno(r
, "Failed to mangle unit name: %m");
1617 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1622 r
= make_transient_service_unit(bus
, &m
, service
, pty_path
);
1626 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1628 r
= bus_call_with_hint(bus
, m
, "service", &reply
);
1635 r
= sd_bus_message_read(reply
, "o", &object
);
1637 return bus_log_parse_error(r
);
1639 r
= bus_wait_for_jobs_one(w
,
1641 arg_quiet
? 0 : BUS_WAIT_JOBS_LOG_ERROR
,
1642 arg_runtime_scope
== RUNTIME_SCOPE_USER
? STRV_MAKE_CONST("--user") : NULL
);
1648 sd_id128_t invocation_id
;
1650 r
= acquire_invocation_id(bus
, service
, &invocation_id
);
1653 if (r
== 0) /* No invocation UUID set */
1654 log_info("Running as unit: %s", service
);
1656 log_info("Running as unit: %s; invocation ID: " SD_ID128_FORMAT_STR
, service
, SD_ID128_FORMAT_VAL(invocation_id
));
1659 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
1660 _cleanup_(run_context_free
) RunContext c
= {
1661 .cpu_usage_nsec
= NSEC_INFINITY
,
1662 .memory_peak
= UINT64_MAX
,
1663 .memory_swap_peak
= UINT64_MAX
,
1664 .ip_ingress_bytes
= UINT64_MAX
,
1665 .ip_egress_bytes
= UINT64_MAX
,
1666 .io_read_bytes
= UINT64_MAX
,
1667 .io_write_bytes
= UINT64_MAX
,
1668 .inactive_exit_usec
= USEC_INFINITY
,
1669 .inactive_enter_usec
= USEC_INFINITY
,
1671 _cleanup_free_
char *path
= NULL
;
1673 c
.bus
= sd_bus_ref(bus
);
1675 r
= sd_event_default(&c
.event
);
1677 return log_error_errno(r
, "Failed to get event loop: %m");
1680 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
1681 (void) sd_event_add_signal(c
.event
, NULL
, SIGINT
, NULL
, NULL
);
1682 (void) sd_event_add_signal(c
.event
, NULL
, SIGTERM
, NULL
, NULL
);
1685 log_info("Press ^] three times within 1s to disconnect TTY.");
1687 r
= pty_forward_new(c
.event
, master
, PTY_FORWARD_IGNORE_INITIAL_VHANGUP
, &c
.forward
);
1689 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
1691 pty_forward_set_handler(c
.forward
, pty_forward_handler
, &c
);
1693 /* Make sure to process any TTY events before we process bus events */
1694 (void) pty_forward_set_priority(c
.forward
, SD_EVENT_PRIORITY_IMPORTANT
);
1697 path
= unit_dbus_path_from_name(service
);
1701 r
= sd_bus_match_signal_async(
1704 "org.freedesktop.systemd1",
1706 "org.freedesktop.DBus.Properties",
1707 "PropertiesChanged",
1708 on_properties_changed
, NULL
, &c
);
1710 return log_error_errno(r
, "Failed to request properties changed signal match: %m");
1712 r
= sd_bus_attach_event(bus
, c
.event
, SD_EVENT_PRIORITY_NORMAL
);
1714 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1716 r
= run_context_update(&c
, path
);
1720 r
= sd_event_loop(c
.event
);
1722 return log_error_errno(r
, "Failed to run event loop: %m");
1727 r
= pty_forward_get_last_char(c
.forward
, &last_char
);
1728 if (r
>= 0 && !arg_quiet
&& last_char
!= '\n')
1729 fputc('\n', stdout
);
1732 if (arg_wait
&& !arg_quiet
) {
1734 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, with its
1735 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1737 c
.forward
= pty_forward_free(c
.forward
);
1739 if (!isempty(c
.result
))
1740 log_info("Finished with result: %s", strna(c
.result
));
1742 if (c
.exit_code
== CLD_EXITED
)
1743 log_info("Main processes terminated with: code=%s/status=%u",
1744 sigchld_code_to_string(c
.exit_code
), c
.exit_status
);
1745 else if (c
.exit_code
> 0)
1746 log_info("Main processes terminated with: code=%s/status=%s",
1747 sigchld_code_to_string(c
.exit_code
), signal_to_string(c
.exit_status
));
1749 if (timestamp_is_set(c
.inactive_enter_usec
) &&
1750 timestamp_is_set(c
.inactive_exit_usec
) &&
1751 c
.inactive_enter_usec
> c
.inactive_exit_usec
)
1752 log_info("Service runtime: %s",
1753 FORMAT_TIMESPAN(c
.inactive_enter_usec
- c
.inactive_exit_usec
, USEC_PER_MSEC
));
1755 if (c
.cpu_usage_nsec
!= NSEC_INFINITY
)
1756 log_info("CPU time consumed: %s",
1757 FORMAT_TIMESPAN(DIV_ROUND_UP(c
.cpu_usage_nsec
, NSEC_PER_USEC
), USEC_PER_MSEC
));
1759 if (c
.memory_peak
!= UINT64_MAX
)
1760 log_info("Memory peak: %s", FORMAT_BYTES(c
.memory_peak
));
1762 if (c
.memory_swap_peak
!= UINT64_MAX
)
1763 log_info("Memory swap peak: %s", FORMAT_BYTES(c
.memory_swap_peak
));
1765 if (c
.ip_ingress_bytes
!= UINT64_MAX
)
1766 log_info("IP traffic received: %s", FORMAT_BYTES(c
.ip_ingress_bytes
));
1768 if (c
.ip_egress_bytes
!= UINT64_MAX
)
1769 log_info("IP traffic sent: %s", FORMAT_BYTES(c
.ip_egress_bytes
));
1771 if (c
.io_read_bytes
!= UINT64_MAX
)
1772 log_info("IO bytes read: %s", FORMAT_BYTES(c
.io_read_bytes
));
1774 if (c
.io_write_bytes
!= UINT64_MAX
)
1775 log_info("IO bytes written: %s", FORMAT_BYTES(c
.io_write_bytes
));
1778 /* Try to propagate the service's return value. But if the service defines
1779 * e.g. SuccessExitStatus, honour this, and return 0 to mean "success". */
1780 if (streq_ptr(c
.result
, "success"))
1781 return EXIT_SUCCESS
;
1782 if (streq_ptr(c
.result
, "exit-code") && c
.exit_status
> 0)
1783 return c
.exit_status
;
1784 if (streq_ptr(c
.result
, "signal"))
1785 return EXIT_EXCEPTION
;
1786 return EXIT_FAILURE
;
1789 return EXIT_SUCCESS
;
1792 static int start_transient_scope(sd_bus
*bus
) {
1793 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1794 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1795 _cleanup_strv_free_
char **env
= NULL
, **user_env
= NULL
;
1796 _cleanup_free_
char *scope
= NULL
;
1797 const char *object
= NULL
;
1798 sd_id128_t invocation_id
;
1799 bool allow_pidfd
= true;
1803 assert(!strv_isempty(arg_cmdline
));
1805 r
= bus_wait_for_jobs_new(bus
, &w
);
1807 return log_error_errno(r
, "Could not watch jobs: %m");
1810 r
= unit_name_mangle_with_suffix(arg_unit
, "as unit",
1811 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
1814 return log_error_errno(r
, "Failed to mangle scope name: %m");
1816 r
= make_unit_name(bus
, UNIT_SCOPE
, &scope
);
1821 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1824 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1825 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1827 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "StartTransientUnit");
1829 return bus_log_create_error(r
);
1831 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1833 return bus_log_create_error(r
);
1836 r
= sd_bus_message_append(m
, "ss", scope
, "fail");
1838 return bus_log_create_error(r
);
1841 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1843 return bus_log_create_error(r
);
1845 r
= transient_scope_set_properties(m
, allow_pidfd
);
1849 r
= sd_bus_message_close_container(m
);
1851 return bus_log_create_error(r
);
1853 /* Auxiliary units */
1854 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1856 return bus_log_create_error(r
);
1858 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1860 if (sd_bus_error_has_names(&error
, SD_BUS_ERROR_UNKNOWN_PROPERTY
, SD_BUS_ERROR_PROPERTY_READ_ONLY
) && allow_pidfd
) {
1861 log_debug("Retrying with classic PIDs.");
1862 allow_pidfd
= false;
1866 return log_error_errno(r
, "Failed to start transient scope unit: %s", bus_error_message(&error
, r
));
1872 r
= sd_bus_message_read(reply
, "o", &object
);
1874 return bus_log_parse_error(r
);
1876 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
? 0 : BUS_WAIT_JOBS_LOG_ERROR
,
1877 arg_runtime_scope
== RUNTIME_SCOPE_USER
? STRV_MAKE_CONST("--user") : NULL
);
1881 r
= acquire_invocation_id(bus
, NULL
, &invocation_id
);
1885 log_debug("No invocation ID set.");
1887 if (strv_extendf(&user_env
, "INVOCATION_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(invocation_id
)) < 0)
1892 if (setpriority(PRIO_PROCESS
, 0, arg_nice
) < 0)
1893 return log_error_errno(errno
, "Failed to set nice level: %m");
1896 if (arg_exec_group
) {
1899 r
= get_group_creds(&arg_exec_group
, &gid
, 0);
1901 return log_error_errno(r
, "Failed to resolve group %s: %m", arg_exec_group
);
1903 if (setresgid(gid
, gid
, gid
) < 0)
1904 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1907 if (arg_exec_user
) {
1908 const char *home
, *shell
;
1912 r
= get_user_creds(&arg_exec_user
, &uid
, &gid
, &home
, &shell
, USER_CREDS_CLEAN
|USER_CREDS_PREFER_NSS
);
1914 return log_error_errno(r
, "Failed to resolve user %s: %m", arg_exec_user
);
1917 r
= strv_extendf(&user_env
, "HOME=%s", home
);
1923 r
= strv_extendf(&user_env
, "SHELL=%s", shell
);
1928 r
= strv_extendf(&user_env
, "USER=%s", arg_exec_user
);
1932 r
= strv_extendf(&user_env
, "LOGNAME=%s", arg_exec_user
);
1936 if (!arg_exec_group
) {
1937 if (setresgid(gid
, gid
, gid
) < 0)
1938 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1941 if (setresuid(uid
, uid
, uid
) < 0)
1942 return log_error_errno(errno
, "Failed to change UID to " UID_FMT
": %m", uid
);
1945 if (arg_working_directory
&& chdir(arg_working_directory
) < 0)
1946 return log_error_errno(errno
, "Failed to change directory to '%s': %m", arg_working_directory
);
1948 env
= strv_env_merge(environ
, user_env
, arg_environment
);
1953 if (sd_id128_is_null(invocation_id
))
1954 log_info("Running as unit: %s", scope
);
1956 log_info("Running as unit: %s; invocation ID: " SD_ID128_FORMAT_STR
, scope
, SD_ID128_FORMAT_VAL(invocation_id
));
1959 if (arg_expand_environment
> 0) {
1960 _cleanup_strv_free_
char **expanded_cmdline
= NULL
, **unset_variables
= NULL
, **bad_variables
= NULL
;
1962 r
= replace_env_argv(arg_cmdline
, env
, &expanded_cmdline
, &unset_variables
, &bad_variables
);
1964 return log_error_errno(r
, "Failed to expand environment variables: %m");
1966 free_and_replace(arg_cmdline
, expanded_cmdline
);
1968 if (!strv_isempty(unset_variables
)) {
1969 _cleanup_free_
char *ju
= strv_join(unset_variables
, ", ");
1970 log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju
));
1973 if (!strv_isempty(bad_variables
)) {
1974 _cleanup_free_
char *jb
= strv_join(bad_variables
, ", ");
1975 log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb
));
1979 execvpe(arg_cmdline
[0], arg_cmdline
, env
);
1981 return log_error_errno(errno
, "Failed to execute: %m");
1984 static int make_transient_trigger_unit(
1986 sd_bus_message
**message
,
1988 const char *trigger
,
1989 const char *service
) {
1991 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
2000 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "StartTransientUnit");
2002 return bus_log_create_error(r
);
2004 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
2006 return bus_log_create_error(r
);
2009 r
= sd_bus_message_append(m
, "ss", trigger
, "fail");
2011 return bus_log_create_error(r
);
2014 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
2016 return bus_log_create_error(r
);
2018 if (streq(suffix
, ".path"))
2019 r
= transient_unit_set_properties(m
, UNIT_PATH
, arg_path_property
);
2020 else if (streq(suffix
, ".socket"))
2021 r
= transient_unit_set_properties(m
, UNIT_SOCKET
, arg_socket_property
);
2022 else if (streq(suffix
, ".timer"))
2023 r
= transient_timer_set_properties(m
);
2025 assert_not_reached();
2029 r
= sd_bus_message_close_container(m
);
2031 return bus_log_create_error(r
);
2033 r
= sd_bus_message_open_container(m
, 'a', "(sa(sv))");
2035 return bus_log_create_error(r
);
2037 if (!strv_isempty(arg_cmdline
)) {
2038 r
= sd_bus_message_open_container(m
, 'r', "sa(sv)");
2040 return bus_log_create_error(r
);
2042 r
= sd_bus_message_append(m
, "s", service
);
2044 return bus_log_create_error(r
);
2046 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
2048 return bus_log_create_error(r
);
2050 r
= transient_service_set_properties(m
, NULL
);
2054 r
= sd_bus_message_close_container(m
);
2056 return bus_log_create_error(r
);
2058 r
= sd_bus_message_close_container(m
);
2060 return bus_log_create_error(r
);
2063 r
= sd_bus_message_close_container(m
);
2065 return bus_log_create_error(r
);
2067 *message
= TAKE_PTR(m
);
2071 static int start_transient_trigger(sd_bus
*bus
, const char *suffix
) {
2072 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
2073 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
2074 _cleanup_free_
char *trigger
= NULL
, *service
= NULL
;
2075 const char *object
= NULL
;
2081 r
= bus_wait_for_jobs_new(bus
, &w
);
2083 return log_error_errno(r
, "Could not watch jobs: %m");
2086 switch (unit_name_to_type(arg_unit
)) {
2089 service
= strdup(arg_unit
);
2093 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
2095 return log_error_errno(r
, "Failed to change unit suffix: %m");
2099 trigger
= strdup(arg_unit
);
2103 r
= unit_name_change_suffix(trigger
, ".service", &service
);
2105 return log_error_errno(r
, "Failed to change unit suffix: %m");
2109 r
= unit_name_mangle_with_suffix(arg_unit
, "as unit",
2110 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2111 ".service", &service
);
2113 return log_error_errno(r
, "Failed to mangle unit name: %m");
2115 r
= unit_name_mangle_with_suffix(arg_unit
, "as trigger",
2116 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2119 return log_error_errno(r
, "Failed to mangle unit name: %m");
2124 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
2128 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
2130 return log_error_errno(r
, "Failed to change unit suffix: %m");
2133 r
= make_transient_trigger_unit(bus
, &m
, suffix
, trigger
, service
);
2137 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
2139 r
= bus_call_with_hint(bus
, m
, suffix
+ 1, &reply
);
2143 r
= sd_bus_message_read(reply
, "o", &object
);
2145 return bus_log_parse_error(r
);
2147 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
? 0 : BUS_WAIT_JOBS_LOG_ERROR
,
2148 arg_runtime_scope
== RUNTIME_SCOPE_USER
? STRV_MAKE_CONST("--user") : NULL
);
2153 log_info("Running %s as unit: %s", suffix
+ 1, trigger
);
2154 if (!strv_isempty(arg_cmdline
))
2155 log_info("Will run service as unit: %s", service
);
2158 return EXIT_SUCCESS
;
2161 static bool shall_make_executable_absolute(void) {
2164 if (strv_isempty(arg_cmdline
))
2166 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
2169 FOREACH_STRING(f
, "RootDirectory=", "RootImage=", "ExecSearchPath=", "MountImages=", "ExtensionImages=")
2170 if (strv_find_startswith(arg_property
, f
))
2176 static int run(int argc
, char* argv
[]) {
2177 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
2180 log_show_color(true);
2181 log_parse_environment();
2184 if (invoked_as(argv
, "uid0"))
2185 r
= parse_argv_sudo_mode(argc
, argv
);
2187 r
= parse_argv(argc
, argv
);
2191 if (shall_make_executable_absolute()) {
2192 /* Patch in an absolute path to fail early for user convenience, but only when we can do it
2193 * (i.e. we will be running from the same file system). This also uses the user's $PATH,
2194 * while we use a fixed search path in the manager. */
2196 _cleanup_free_
char *command
= NULL
;
2197 r
= find_executable(arg_cmdline
[0], &command
);
2199 return log_error_errno(r
, "Failed to find executable %s: %m", arg_cmdline
[0]);
2201 free_and_replace(arg_cmdline
[0], command
);
2204 if (!arg_description
) {
2207 if (strv_isempty(arg_cmdline
))
2208 t
= strdup(arg_unit
);
2210 t
= quote_command_line(arg_cmdline
, SHELL_ESCAPE_EMPTY
);
2214 free_and_replace(arg_description
, t
);
2217 /* For backward compatibility reasons env var expansion is disabled by default for scopes, and
2218 * enabled by default for everything else. Try to detect it and print a warning, so that we can
2219 * change it in the future and harmonize it. */
2220 if (arg_expand_environment
< 0) {
2221 arg_expand_environment
= !arg_scope
;
2223 if (!arg_quiet
&& arg_scope
&& strchr(arg_description
, '$'))
2224 log_warning("Scope command line contains environment variable, which is not expanded"
2225 " by default for now, but will be expanded by default in the future."
2226 " Use --expand-environment=yes/no to explicitly control it as needed.");
2229 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the
2230 * limited direct connection */
2232 arg_stdio
!= ARG_STDIO_NONE
||
2233 (arg_runtime_scope
== RUNTIME_SCOPE_USER
&& arg_transport
!= BUS_TRANSPORT_LOCAL
))
2234 r
= bus_connect_transport(arg_transport
, arg_host
, arg_runtime_scope
, &bus
);
2236 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, arg_runtime_scope
, &bus
);
2238 return bus_log_connect_error(r
, arg_transport
);
2241 return start_transient_scope(bus
);
2242 if (arg_path_property
)
2243 return start_transient_trigger(bus
, ".path");
2244 if (arg_socket_property
)
2245 return start_transient_trigger(bus
, ".socket");
2247 return start_transient_trigger(bus
, ".timer");
2248 return start_transient_service(bus
);
2251 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);