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"
20 #include "color-util.h"
23 #include "exit-status.h"
25 #include "format-util.h"
26 #include "main-func.h"
27 #include "parse-argument.h"
28 #include "parse-util.h"
29 #include "path-util.h"
30 #include "pretty-print.h"
31 #include "process-util.h"
33 #include "signal-util.h"
34 #include "spawn-polkit-agent.h"
36 #include "terminal-util.h"
38 #include "unit-name.h"
39 #include "user-util.h"
41 static bool arg_ask_password
= true;
42 static bool arg_scope
= false;
43 static bool arg_remain_after_exit
= false;
44 static bool arg_no_block
= false;
45 static bool arg_wait
= false;
46 static const char *arg_unit
= NULL
;
47 static char *arg_description
= NULL
;
48 static const char *arg_slice
= NULL
;
49 static bool arg_slice_inherit
= false;
50 static int arg_expand_environment
= -1;
51 static bool arg_send_sighup
= false;
52 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
53 static const char *arg_host
= NULL
;
54 static RuntimeScope arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
55 static const char *arg_service_type
= NULL
;
56 static const char *arg_exec_user
= NULL
;
57 static const char *arg_exec_group
= NULL
;
58 static int arg_nice
= 0;
59 static bool arg_nice_set
= false;
60 static char **arg_environment
= NULL
;
61 static char **arg_property
= NULL
;
63 ARG_STDIO_NONE
, /* The default, as it is for normal services, stdin connected to /dev/null, and stdout+stderr to the journal */
64 ARG_STDIO_PTY
, /* Interactive behaviour, requested by --pty: we allocate a pty and connect it to the TTY we are invoked from */
65 ARG_STDIO_DIRECT
, /* Directly pass our stdin/stdout/stderr to the activated service, useful for usage in shell pipelines, requested by --pipe */
66 ARG_STDIO_AUTO
, /* If --pipe and --pty are used together we use --pty when invoked on a TTY, and --pipe otherwise */
67 } arg_stdio
= ARG_STDIO_NONE
;
68 static char **arg_path_property
= NULL
;
69 static char **arg_socket_property
= NULL
;
70 static char **arg_timer_property
= NULL
;
71 static bool arg_with_timer
= false;
72 static bool arg_quiet
= false;
73 static bool arg_aggressive_gc
= false;
74 static char *arg_working_directory
= NULL
;
75 static bool arg_shell
= false;
76 static char **arg_cmdline
= NULL
;
77 static char *arg_exec_path
= NULL
;
78 static bool arg_ignore_failure
= false;
79 static char *arg_background
= NULL
;
81 STATIC_DESTRUCTOR_REGISTER(arg_description
, freep
);
82 STATIC_DESTRUCTOR_REGISTER(arg_environment
, strv_freep
);
83 STATIC_DESTRUCTOR_REGISTER(arg_property
, strv_freep
);
84 STATIC_DESTRUCTOR_REGISTER(arg_path_property
, strv_freep
);
85 STATIC_DESTRUCTOR_REGISTER(arg_socket_property
, strv_freep
);
86 STATIC_DESTRUCTOR_REGISTER(arg_timer_property
, strv_freep
);
87 STATIC_DESTRUCTOR_REGISTER(arg_working_directory
, freep
);
88 STATIC_DESTRUCTOR_REGISTER(arg_cmdline
, strv_freep
);
89 STATIC_DESTRUCTOR_REGISTER(arg_exec_path
, freep
);
90 STATIC_DESTRUCTOR_REGISTER(arg_background
, freep
);
92 static int help(void) {
93 _cleanup_free_
char *link
= NULL
;
96 r
= terminal_urlify_man("systemd-run", "1", &link
);
100 printf("%1$s [OPTIONS...] COMMAND [ARGUMENTS...]\n"
101 "\n%5$sRun the specified command in a transient scope or service.%6$s\n\n"
102 " -h --help Show this help\n"
103 " --version Show package version\n"
104 " --no-ask-password Do not prompt for password\n"
105 " --user Run as user unit\n"
106 " -H --host=[USER@]HOST Operate on remote host\n"
107 " -M --machine=CONTAINER Operate on local container\n"
108 " --scope Run this as scope rather than service\n"
109 " -u --unit=UNIT Run under the specified unit name\n"
110 " -p --property=NAME=VALUE Set service or scope unit property\n"
111 " --description=TEXT Description for unit\n"
112 " --slice=SLICE Run in the specified slice\n"
113 " --slice-inherit Inherit the slice from the caller\n"
114 " --expand-environment=BOOL Control expansion of environment variables\n"
115 " --no-block Do not wait until operation finished\n"
116 " -r --remain-after-exit Leave service around until explicitly stopped\n"
117 " --wait Wait until service stopped again\n"
118 " --send-sighup Send SIGHUP when terminating\n"
119 " --service-type=TYPE Service type\n"
120 " --uid=USER Run as system user\n"
121 " --gid=GROUP Run as system group\n"
122 " --nice=NICE Nice level\n"
123 " --working-directory=PATH Set working directory\n"
124 " -d --same-dir Inherit working directory from caller\n"
125 " -E --setenv=NAME[=VALUE] Set environment variable\n"
126 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
128 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
129 " -q --quiet Suppress information messages during runtime\n"
130 " -G --collect Unload unit after it ran, even when failed\n"
131 " -S --shell Invoke a $SHELL interactively\n"
132 " --ignore-failure Ignore the exit status of the invoked process\n"
133 " --background=COLOR Set ANSI color for background\n"
134 "\n%3$sPath options:%4$s\n"
135 " --path-property=NAME=VALUE Set path unit property\n"
136 "\n%3$sSocket options:%4$s\n"
137 " --socket-property=NAME=VALUE Set socket unit property\n"
138 "\n%3$sTimer options:%4$s\n"
139 " --on-active=SECONDS Run after SECONDS delay\n"
140 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
141 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
142 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
143 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
144 " --on-calendar=SPEC Realtime timer\n"
145 " --on-timezone-change Run when the timezone changes\n"
146 " --on-clock-change Run when the realtime clock jumps\n"
147 " --timer-property=NAME=VALUE Set timer unit property\n"
148 "\nSee the %2$s for details.\n",
149 program_invocation_short_name
,
151 ansi_underline(), ansi_normal(),
152 ansi_highlight(), ansi_normal());
157 static int help_sudo_mode(void) {
158 _cleanup_free_
char *link
= NULL
;
161 r
= terminal_urlify_man("uid0", "1", &link
);
165 printf("%s [OPTIONS...] COMMAND [ARGUMENTS...]\n"
166 "\n%sElevate privileges interactively.%s\n\n"
167 " -h --help Show this help\n"
168 " -V --version Show package version\n"
169 " --no-ask-password Do not prompt for password\n"
170 " --machine=CONTAINER Operate on local container\n"
171 " --unit=UNIT Run under the specified unit name\n"
172 " --property=NAME=VALUE Set service or scope unit property\n"
173 " --description=TEXT Description for unit\n"
174 " --slice=SLICE Run in the specified slice\n"
175 " --slice-inherit Inherit the slice\n"
176 " -u --user=USER Run as system user\n"
177 " -g --group=GROUP Run as system group\n"
178 " --nice=NICE Nice level\n"
179 " -D --chdir=PATH Set working directory\n"
180 " --setenv=NAME[=VALUE] Set environment variable\n"
181 " --background=COLOR Set ANSI color for background\n"
182 "\nSee the %s for details.\n",
183 program_invocation_short_name
,
191 static int add_timer_property(const char *name
, const char *val
) {
197 p
= strjoin(name
, "=", val
);
201 if (strv_consume(&arg_timer_property
, p
) < 0)
207 static char **make_login_shell_cmdline(const char *shell
) {
208 _cleanup_free_
char *argv0
= NULL
;
212 argv0
= strjoin("-", shell
); /* The - is how shells determine if they shall be consider login shells */
216 return strv_new(argv0
);
219 static int parse_argv(int argc
, char *argv
[]) {
229 ARG_EXPAND_ENVIRONMENT
,
239 ARG_ON_UNIT_INACTIVE
,
241 ARG_ON_TIMEZONE_CHANGE
,
249 ARG_WORKING_DIRECTORY
,
255 static const struct option options
[] = {
256 { "help", no_argument
, NULL
, 'h' },
257 { "version", no_argument
, NULL
, ARG_VERSION
},
258 { "user", no_argument
, NULL
, ARG_USER
},
259 { "system", no_argument
, NULL
, ARG_SYSTEM
},
260 { "scope", no_argument
, NULL
, ARG_SCOPE
},
261 { "unit", required_argument
, NULL
, 'u' },
262 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
263 { "slice", required_argument
, NULL
, ARG_SLICE
},
264 { "slice-inherit", no_argument
, NULL
, ARG_SLICE_INHERIT
},
265 { "remain-after-exit", no_argument
, NULL
, 'r' },
266 { "expand-environment", required_argument
, NULL
, ARG_EXPAND_ENVIRONMENT
},
267 { "send-sighup", no_argument
, NULL
, ARG_SEND_SIGHUP
},
268 { "host", required_argument
, NULL
, 'H' },
269 { "machine", required_argument
, NULL
, 'M' },
270 { "service-type", required_argument
, NULL
, ARG_SERVICE_TYPE
},
271 { "wait", no_argument
, NULL
, ARG_WAIT
},
272 { "uid", required_argument
, NULL
, ARG_EXEC_USER
},
273 { "gid", required_argument
, NULL
, ARG_EXEC_GROUP
},
274 { "nice", required_argument
, NULL
, ARG_NICE
},
275 { "setenv", required_argument
, NULL
, 'E' },
276 { "property", required_argument
, NULL
, 'p' },
277 { "tty", no_argument
, NULL
, 't' }, /* deprecated alias */
278 { "pty", no_argument
, NULL
, 't' },
279 { "pipe", no_argument
, NULL
, 'P' },
280 { "quiet", no_argument
, NULL
, 'q' },
281 { "on-active", required_argument
, NULL
, ARG_ON_ACTIVE
},
282 { "on-boot", required_argument
, NULL
, ARG_ON_BOOT
},
283 { "on-startup", required_argument
, NULL
, ARG_ON_STARTUP
},
284 { "on-unit-active", required_argument
, NULL
, ARG_ON_UNIT_ACTIVE
},
285 { "on-unit-inactive", required_argument
, NULL
, ARG_ON_UNIT_INACTIVE
},
286 { "on-calendar", required_argument
, NULL
, ARG_ON_CALENDAR
},
287 { "on-timezone-change", no_argument
, NULL
, ARG_ON_TIMEZONE_CHANGE
},
288 { "on-clock-change", no_argument
, NULL
, ARG_ON_CLOCK_CHANGE
},
289 { "timer-property", required_argument
, NULL
, ARG_TIMER_PROPERTY
},
290 { "path-property", required_argument
, NULL
, ARG_PATH_PROPERTY
},
291 { "socket-property", required_argument
, NULL
, ARG_SOCKET_PROPERTY
},
292 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
293 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
294 { "collect", no_argument
, NULL
, 'G' },
295 { "working-directory", required_argument
, NULL
, ARG_WORKING_DIRECTORY
},
296 { "same-dir", no_argument
, NULL
, 'd' },
297 { "shell", no_argument
, NULL
, 'S' },
298 { "ignore-failure", no_argument
, NULL
, ARG_IGNORE_FAILURE
},
299 { "background", no_argument
, NULL
, ARG_BACKGROUND
},
303 bool with_trigger
= false;
309 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
310 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
312 while ((c
= getopt_long(argc
, argv
, "+hrH:M:E:p:tPqGdSu:", options
, NULL
)) >= 0)
322 case ARG_NO_ASK_PASSWORD
:
323 arg_ask_password
= false;
327 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
331 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
342 case ARG_DESCRIPTION
:
343 r
= free_and_strdup_warn(&arg_description
, optarg
);
352 case ARG_SLICE_INHERIT
:
353 arg_slice_inherit
= true;
356 case ARG_EXPAND_ENVIRONMENT
: {
359 r
= parse_boolean_argument("--expand-environment=", optarg
, &b
);
363 arg_expand_environment
= b
;
368 case ARG_SEND_SIGHUP
:
369 arg_send_sighup
= true;
373 arg_remain_after_exit
= true;
377 arg_transport
= BUS_TRANSPORT_REMOTE
;
382 arg_transport
= BUS_TRANSPORT_MACHINE
;
386 case ARG_SERVICE_TYPE
:
387 arg_service_type
= optarg
;
391 arg_exec_user
= optarg
;
395 arg_exec_group
= optarg
;
399 r
= parse_nice(optarg
, &arg_nice
);
401 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
407 r
= strv_env_replace_strdup_passthrough(&arg_environment
, optarg
);
409 return log_error_errno(r
, "Cannot assign environment variable %s: %m", optarg
);
414 if (strv_extend(&arg_property
, optarg
) < 0)
419 case 't': /* --pty */
420 if (IN_SET(arg_stdio
, ARG_STDIO_DIRECT
, ARG_STDIO_AUTO
)) /* if --pipe is already used, upgrade to auto mode */
421 arg_stdio
= ARG_STDIO_AUTO
;
423 arg_stdio
= ARG_STDIO_PTY
;
426 case 'P': /* --pipe */
427 if (IN_SET(arg_stdio
, ARG_STDIO_PTY
, ARG_STDIO_AUTO
)) /* If --pty is already used, upgrade to auto mode */
428 arg_stdio
= ARG_STDIO_AUTO
;
430 arg_stdio
= ARG_STDIO_DIRECT
;
438 r
= add_timer_property("OnActiveSec", optarg
);
442 arg_with_timer
= true;
446 r
= add_timer_property("OnBootSec", optarg
);
450 arg_with_timer
= true;
454 r
= add_timer_property("OnStartupSec", optarg
);
458 arg_with_timer
= true;
461 case ARG_ON_UNIT_ACTIVE
:
462 r
= add_timer_property("OnUnitActiveSec", optarg
);
466 arg_with_timer
= true;
469 case ARG_ON_UNIT_INACTIVE
:
470 r
= add_timer_property("OnUnitInactiveSec", optarg
);
474 arg_with_timer
= true;
477 case ARG_ON_CALENDAR
: {
478 _cleanup_(calendar_spec_freep
) CalendarSpec
*cs
= NULL
;
480 r
= calendar_spec_from_string(optarg
, &cs
);
482 return log_error_errno(r
, "Failed to parse calendar event specification: %m");
484 /* Let's make sure the given calendar event is not in the past */
485 r
= calendar_spec_next_usec(cs
, now(CLOCK_REALTIME
), NULL
);
487 /* The calendar event is in the past — let's warn about this, but install it
488 * anyway as is. The service manager will trigger the service right away.
489 * Moreover, the server side might have a different clock or timezone than we
490 * do, hence it should decide when or whether to run something. */
491 log_warning("Specified calendar expression is in the past, proceeding anyway.");
493 return log_error_errno(r
, "Failed to calculate next time calendar expression elapses: %m");
495 r
= add_timer_property("OnCalendar", optarg
);
499 arg_with_timer
= true;
503 case ARG_ON_TIMEZONE_CHANGE
:
504 r
= add_timer_property("OnTimezoneChange", "yes");
508 arg_with_timer
= true;
511 case ARG_ON_CLOCK_CHANGE
:
512 r
= add_timer_property("OnClockChange", "yes");
516 arg_with_timer
= true;
519 case ARG_TIMER_PROPERTY
:
521 if (strv_extend(&arg_timer_property
, optarg
) < 0)
524 arg_with_timer
= arg_with_timer
||
525 STARTSWITH_SET(optarg
,
530 "OnUnitInactiveSec=",
534 case ARG_PATH_PROPERTY
:
536 if (strv_extend(&arg_path_property
, optarg
) < 0)
541 case ARG_SOCKET_PROPERTY
:
543 if (strv_extend(&arg_socket_property
, optarg
) < 0)
556 case ARG_WORKING_DIRECTORY
:
557 r
= parse_path_argument(optarg
, true, &arg_working_directory
);
564 _cleanup_free_
char *p
= NULL
;
568 return log_error_errno(r
, "Failed to get current working directory: %m");
570 if (empty_or_root(p
))
571 arg_working_directory
= mfree(arg_working_directory
);
573 free_and_replace(arg_working_directory
, p
);
578 arg_aggressive_gc
= true;
585 case ARG_IGNORE_FAILURE
:
586 arg_ignore_failure
= true;
590 r
= free_and_strdup_warn(&arg_background
, optarg
);
599 assert_not_reached();
602 /* If we are talking to the per-user instance PolicyKit isn't going to help */
603 if (arg_runtime_scope
== RUNTIME_SCOPE_USER
)
604 arg_ask_password
= false;
606 with_trigger
= !!arg_path_property
|| !!arg_socket_property
|| arg_with_timer
;
608 /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
609 if ((int) !!arg_path_property
+ (int) !!arg_socket_property
+ (int) arg_with_timer
> 1)
610 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
611 "Only single trigger (path, socket, timer) unit can be created.");
614 /* If --shell is imply --pty --pipe --same-dir --service-type=exec --wait --collect, unless otherwise
618 if (arg_stdio
== ARG_STDIO_NONE
)
619 arg_stdio
= ARG_STDIO_AUTO
;
621 if (!arg_working_directory
) {
622 r
= safe_getcwd(&arg_working_directory
);
624 return log_error_errno(r
, "Failed to get current working directory: %m");
627 if (!arg_service_type
)
628 arg_service_type
= "exec";
633 arg_aggressive_gc
= true;
636 if (arg_stdio
== ARG_STDIO_AUTO
)
637 /* If we both --pty and --pipe are specified we'll automatically pick --pty if we are connected fully
638 * to a TTY and pick direct fd passing otherwise. This way, we automatically adapt to usage in a shell
639 * pipeline, but we are neatly interactive with tty-level isolation otherwise. */
640 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ?
648 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "If --shell is used, no command line is expected.");
650 l
= strv_copy(argv
+ optind
);
654 strv_free_and_replace(arg_cmdline
, l
);
656 } else if (arg_shell
) {
657 _cleanup_free_
char *s
= NULL
;
662 return log_error_errno(r
, "Failed to determine shell: %m");
668 strv_free_and_replace(arg_cmdline
, l
);
670 } else if (!arg_unit
|| !with_trigger
)
671 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Command line to execute required.");
673 if (arg_runtime_scope
== RUNTIME_SCOPE_USER
&& arg_transport
== BUS_TRANSPORT_REMOTE
)
674 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
675 "Execution in user context is not supported on remote systems.");
677 if (arg_scope
&& arg_transport
== BUS_TRANSPORT_REMOTE
)
678 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
679 "Scope execution is not supported on remote systems.");
681 if (arg_scope
&& (arg_remain_after_exit
|| arg_service_type
))
682 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
683 "--remain-after-exit and --service-type= are not supported in --scope mode.");
685 if (arg_stdio
!= ARG_STDIO_NONE
&& (with_trigger
|| arg_scope
))
686 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
687 "--pty/--pipe is not compatible in timer or --scope mode.");
689 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_transport
== BUS_TRANSPORT_REMOTE
)
690 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
691 "--pty/--pipe is only supported when connecting to the local system or containers.");
693 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_no_block
)
694 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
695 "--pty/--pipe is not compatible with --no-block.");
697 if (arg_scope
&& with_trigger
)
698 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
699 "Path, socket or timer options are not supported in --scope mode.");
701 if (arg_timer_property
&& !arg_with_timer
)
702 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
703 "--timer-property= has no effect without any other timer options.");
707 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
708 "--wait may not be combined with --no-block.");
711 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
712 "--wait may not be combined with path, socket or timer operations.");
715 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
716 "--wait may not be combined with --scope.");
722 static int parse_argv_sudo_mode(int argc
, char *argv
[]) {
725 ARG_NO_ASK_PASSWORD
= 0x100,
738 /* If invoked as "uid0" binary, let's expose a more sudo-like interface. We add various extensions
739 * though (but limit the extension to long options). */
741 static const struct option options
[] = {
742 { "help", no_argument
, NULL
, 'h' },
743 { "version", no_argument
, NULL
, 'V' },
744 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
745 { "machine", required_argument
, NULL
, ARG_MACHINE
},
746 { "unit", required_argument
, NULL
, ARG_UNIT
},
747 { "property", required_argument
, NULL
, ARG_PROPERTY
},
748 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
749 { "slice", required_argument
, NULL
, ARG_SLICE
},
750 { "slice-inherit", no_argument
, NULL
, ARG_SLICE_INHERIT
},
751 { "user", required_argument
, NULL
, 'u' },
752 { "group", required_argument
, NULL
, 'g' },
753 { "nice", required_argument
, NULL
, ARG_NICE
},
754 { "chdir", required_argument
, NULL
, 'D' },
755 { "setenv", required_argument
, NULL
, ARG_SETENV
},
756 { "background", required_argument
, NULL
, ARG_BACKGROUND
},
765 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
766 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
768 while ((c
= getopt_long(argc
, argv
, "+hVu:g:D:", options
, NULL
)) >= 0)
773 return help_sudo_mode();
778 case ARG_NO_ASK_PASSWORD
:
779 arg_ask_password
= false;
783 arg_transport
= BUS_TRANSPORT_MACHINE
;
792 if (strv_extend(&arg_property
, optarg
) < 0)
797 case ARG_DESCRIPTION
:
798 r
= free_and_strdup_warn(&arg_description
, optarg
);
807 case ARG_SLICE_INHERIT
:
808 arg_slice_inherit
= true;
812 arg_exec_user
= optarg
;
816 arg_exec_group
= optarg
;
820 r
= parse_nice(optarg
, &arg_nice
);
822 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
828 r
= parse_path_argument(optarg
, true, &arg_working_directory
);
835 r
= strv_env_replace_strdup_passthrough(&arg_environment
, optarg
);
837 return log_error_errno(r
, "Cannot assign environment variable %s: %m", optarg
);
842 r
= free_and_strdup_warn(&arg_background
, optarg
);
852 assert_not_reached();
855 if (!arg_working_directory
) {
857 /* When switching to a specific user, also switch to its home directory. */
858 arg_working_directory
= strdup("~");
859 if (!arg_working_directory
)
862 /* When switching to root without this being specified, then stay in the current directory */
863 r
= safe_getcwd(&arg_working_directory
);
865 return log_error_errno(r
, "Failed to get current working directory: %m");
869 arg_service_type
= "exec";
872 arg_aggressive_gc
= true;
874 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ? ARG_STDIO_PTY
: ARG_STDIO_DIRECT
;
875 arg_expand_environment
= false;
876 arg_send_sighup
= true;
878 _cleanup_strv_free_
char **l
= NULL
;
880 l
= strv_copy(argv
+ optind
);
884 e
= strv_env_get(arg_environment
, "SHELL");
886 arg_exec_path
= strdup(e
);
888 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
889 r
= get_shell(&arg_exec_path
);
891 return log_error_errno(r
, "Failed to determine shell: %m");
893 arg_exec_path
= strdup("/bin/sh");
898 l
= make_login_shell_cmdline(arg_exec_path
);
903 strv_free_and_replace(arg_cmdline
, l
);
906 arg_slice
= strdup("user.slice");
911 _cleanup_free_
char *un
= NULL
;
912 un
= getusername_malloc();
916 /* Set a bunch of environment variables in a roughly sudo-compatible way */
917 r
= strv_env_assign(&arg_environment
, "SUDO_USER", un
);
919 return log_error_errno(r
, "Failed to set $SUDO_USER environment variable: %m");
921 r
= strv_env_assignf(&arg_environment
, "SUDO_UID", UID_FMT
, getuid());
923 return log_error_errno(r
, "Failed to set $SUDO_UID environment variable: %m");
925 r
= strv_env_assignf(&arg_environment
, "SUDO_GID", GID_FMT
, getgid());
927 return log_error_errno(r
, "Failed to set $SUDO_GID environment variable: %m");
929 if (strv_extendf(&arg_property
, "LogExtraFields=ELEVATED_UID=" UID_FMT
, getuid()) < 0)
932 if (strv_extendf(&arg_property
, "LogExtraFields=ELEVATED_GID=" GID_FMT
, getgid()) < 0)
935 if (strv_extendf(&arg_property
, "LogExtraFields=ELEVATED_USER=%s", un
) < 0)
938 if (strv_extend(&arg_property
, "PAMName=systemd-uid0") < 0)
941 if (!arg_background
&& arg_stdio
== ARG_STDIO_PTY
) {
942 double red
, green
, blue
;
944 r
= get_default_background_color(&red
, &green
, &blue
);
946 log_debug_errno(r
, "Unable to get terminal background color, not tinting background: %m");
950 rgb_to_hsv(red
, green
, blue
, &h
, &s
, &v
);
952 if (!arg_exec_user
|| STR_IN_SET(arg_exec_user
, "root", "0"))
957 if (v
> 50) /* If the background is bright, then pull down saturation */
959 else /* otherwise pump it up */
962 v
= MAX(30, v
); /* Make sure we don't hide the color in black */
965 hsv_to_rgb(h
, s
, v
, &r8
, &g8
, &b8
);
967 if (asprintf(&arg_background
, "48;2;%u;%u;%u", r8
, g8
, b8
) < 0)
975 static int transient_unit_set_properties(sd_bus_message
*m
, UnitType t
, char **properties
) {
980 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", arg_description
);
982 return bus_log_create_error(r
);
984 if (arg_aggressive_gc
) {
985 r
= sd_bus_message_append(m
, "(sv)", "CollectMode", "s", "inactive-or-failed");
987 return bus_log_create_error(r
);
990 r
= sd_bus_is_bus_client(sd_bus_message_get_bus(m
));
992 return log_error_errno(r
, "Can't determine if bus connection is direct or to broker: %m");
994 /* Pin the object as least as long as we are around. Note that AddRef (currently) only works
995 * if we talk via the bus though. */
996 r
= sd_bus_message_append(m
, "(sv)", "AddRef", "b", 1);
998 return bus_log_create_error(r
);
1001 return bus_append_unit_property_assignment_many(m
, t
, properties
);
1004 static int transient_cgroup_set_properties(sd_bus_message
*m
) {
1005 _cleanup_free_
char *name
= NULL
;
1006 _cleanup_free_
char *slice
= NULL
;
1010 if (arg_slice_inherit
) {
1013 switch (arg_runtime_scope
) {
1015 case RUNTIME_SCOPE_USER
:
1016 r
= cg_pid_get_user_slice(0, &name
);
1019 case RUNTIME_SCOPE_SYSTEM
:
1020 r
= cg_pid_get_slice(0, &name
);
1024 assert_not_reached();
1028 return log_error_errno(r
, "Failed to get PID slice: %m");
1030 end
= endswith(name
, ".slice");
1036 if (!isempty(arg_slice
) && !strextend_with_separator(&name
, "-", arg_slice
))
1042 r
= unit_name_mangle_with_suffix(name
, "as slice",
1043 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
1046 return log_error_errno(r
, "Failed to mangle name '%s': %m", arg_slice
);
1048 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", slice
);
1050 return bus_log_create_error(r
);
1055 static int transient_kill_set_properties(sd_bus_message
*m
) {
1060 if (arg_send_sighup
) {
1061 r
= sd_bus_message_append(m
, "(sv)", "SendSIGHUP", "b", arg_send_sighup
);
1063 return bus_log_create_error(r
);
1069 static int transient_service_set_properties(sd_bus_message
*m
, const char *pty_path
) {
1070 bool send_term
= false;
1073 /* We disable environment expansion on the server side via ExecStartEx=:.
1074 * ExecStartEx was added relatively recently (v243), and some bugs were fixed only later.
1075 * So use that feature only if required. It will fail with older systemds. */
1076 bool use_ex_prop
= arg_expand_environment
== 0;
1080 r
= transient_unit_set_properties(m
, UNIT_SERVICE
, arg_property
);
1084 r
= transient_kill_set_properties(m
);
1088 r
= transient_cgroup_set_properties(m
);
1092 if (arg_remain_after_exit
) {
1093 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit
);
1095 return bus_log_create_error(r
);
1098 if (arg_service_type
) {
1099 r
= sd_bus_message_append(m
, "(sv)", "Type", "s", arg_service_type
);
1101 return bus_log_create_error(r
);
1104 if (arg_exec_user
) {
1105 r
= sd_bus_message_append(m
, "(sv)", "User", "s", arg_exec_user
);
1107 return bus_log_create_error(r
);
1110 if (arg_exec_group
) {
1111 r
= sd_bus_message_append(m
, "(sv)", "Group", "s", arg_exec_group
);
1113 return bus_log_create_error(r
);
1117 r
= sd_bus_message_append(m
, "(sv)", "Nice", "i", arg_nice
);
1119 return bus_log_create_error(r
);
1122 if (arg_working_directory
) {
1123 r
= sd_bus_message_append(m
, "(sv)", "WorkingDirectory", "s", arg_working_directory
);
1125 return bus_log_create_error(r
);
1129 r
= sd_bus_message_append(m
,
1131 "StandardInput", "s", "tty",
1132 "StandardOutput", "s", "tty",
1133 "StandardError", "s", "tty",
1134 "TTYPath", "s", pty_path
);
1136 return bus_log_create_error(r
);
1140 } else if (arg_stdio
== ARG_STDIO_DIRECT
) {
1141 r
= sd_bus_message_append(m
,
1143 "StandardInputFileDescriptor", "h", STDIN_FILENO
,
1144 "StandardOutputFileDescriptor", "h", STDOUT_FILENO
,
1145 "StandardErrorFileDescriptor", "h", STDERR_FILENO
);
1147 return bus_log_create_error(r
);
1149 send_term
= isatty(STDIN_FILENO
) || isatty(STDOUT_FILENO
) || isatty(STDERR_FILENO
);
1157 _cleanup_free_
char *n
= NULL
;
1159 n
= strjoin("TERM=", e
);
1163 r
= sd_bus_message_append(m
,
1165 "Environment", "as", 1, n
);
1167 return bus_log_create_error(r
);
1171 if (!strv_isempty(arg_environment
)) {
1172 r
= sd_bus_message_open_container(m
, 'r', "sv");
1174 return bus_log_create_error(r
);
1176 r
= sd_bus_message_append(m
, "s", "Environment");
1178 return bus_log_create_error(r
);
1180 r
= sd_bus_message_open_container(m
, 'v', "as");
1182 return bus_log_create_error(r
);
1184 r
= sd_bus_message_append_strv(m
, arg_environment
);
1186 return bus_log_create_error(r
);
1188 r
= sd_bus_message_close_container(m
);
1190 return bus_log_create_error(r
);
1192 r
= sd_bus_message_close_container(m
);
1194 return bus_log_create_error(r
);
1197 /* Exec container */
1198 if (!strv_isempty(arg_cmdline
)) {
1199 r
= sd_bus_message_open_container(m
, 'r', "sv");
1201 return bus_log_create_error(r
);
1203 r
= sd_bus_message_append(m
, "s",
1204 use_ex_prop
? "ExecStartEx" : "ExecStart");
1206 return bus_log_create_error(r
);
1208 r
= sd_bus_message_open_container(m
, 'v',
1209 use_ex_prop
? "a(sasas)" : "a(sasb)");
1211 return bus_log_create_error(r
);
1213 r
= sd_bus_message_open_container(m
, 'a',
1214 use_ex_prop
? "(sasas)" : "(sasb)");
1216 return bus_log_create_error(r
);
1218 r
= sd_bus_message_open_container(m
, 'r',
1219 use_ex_prop
? "sasas" : "sasb");
1221 return bus_log_create_error(r
);
1223 r
= sd_bus_message_append(m
, "s", arg_exec_path
?: arg_cmdline
[0]);
1225 return bus_log_create_error(r
);
1227 r
= sd_bus_message_append_strv(m
, arg_cmdline
);
1229 return bus_log_create_error(r
);
1232 r
= sd_bus_message_append_strv(
1234 STRV_MAKE(arg_expand_environment
> 0 ? NULL
: "no-env-expand",
1235 arg_ignore_failure
? "ignore-failure" : NULL
));
1237 r
= sd_bus_message_append(m
, "b", arg_ignore_failure
);
1239 return bus_log_create_error(r
);
1241 r
= sd_bus_message_close_container(m
);
1243 return bus_log_create_error(r
);
1245 r
= sd_bus_message_close_container(m
);
1247 return bus_log_create_error(r
);
1249 r
= sd_bus_message_close_container(m
);
1251 return bus_log_create_error(r
);
1253 r
= sd_bus_message_close_container(m
);
1255 return bus_log_create_error(r
);
1261 static int transient_scope_set_properties(sd_bus_message
*m
, bool allow_pidfd
) {
1266 r
= transient_unit_set_properties(m
, UNIT_SCOPE
, arg_property
);
1270 r
= transient_kill_set_properties(m
);
1274 r
= transient_cgroup_set_properties(m
);
1279 _cleanup_(pidref_done
) PidRef pidref
= PIDREF_NULL
;
1281 r
= pidref_set_self(&pidref
);
1285 r
= bus_append_scope_pidref(m
, &pidref
);
1287 r
= sd_bus_message_append(
1289 "PIDs", "au", 1, getpid_cached());
1291 return bus_log_create_error(r
);
1296 static int transient_timer_set_properties(sd_bus_message
*m
) {
1301 r
= transient_unit_set_properties(m
, UNIT_TIMER
, arg_timer_property
);
1305 /* Automatically clean up our transient timers */
1306 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterElapse", "b", false);
1308 return bus_log_create_error(r
);
1313 static int make_unit_name(sd_bus
*bus
, UnitType t
, char **ret
) {
1314 const char *unique
, *id
;
1320 assert(t
< _UNIT_TYPE_MAX
);
1322 r
= sd_bus_get_unique_name(bus
, &unique
);
1326 /* We couldn't get the unique name, which is a pretty
1327 * common case if we are connected to systemd
1328 * directly. In that case, just pick a random uuid as
1331 r
= sd_id128_randomize(&rnd
);
1333 return log_error_errno(r
, "Failed to generate random run unit name: %m");
1335 if (asprintf(ret
, "run-r" SD_ID128_FORMAT_STR
".%s", SD_ID128_FORMAT_VAL(rnd
), unit_type_to_string(t
)) < 0)
1341 /* We managed to get the unique name, then let's use that to name our transient units. */
1343 id
= startswith(unique
, ":1."); /* let' strip the usual prefix */
1345 id
= startswith(unique
, ":"); /* the spec only requires things to start with a colon, hence
1346 * let's add a generic fallback for that. */
1348 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1349 "Unique name %s has unexpected format.",
1352 p
= strjoin("run-u", id
, ".", unit_type_to_string(t
));
1360 typedef struct RunContext
{
1363 PTYForward
*forward
;
1366 /* Current state of the unit */
1370 /* The exit data of the unit */
1371 uint64_t inactive_exit_usec
;
1372 uint64_t inactive_enter_usec
;
1374 uint64_t cpu_usage_nsec
;
1375 uint64_t memory_peak
;
1376 uint64_t memory_swap_peak
;
1377 uint64_t ip_ingress_bytes
;
1378 uint64_t ip_egress_bytes
;
1379 uint64_t io_read_bytes
;
1380 uint64_t io_write_bytes
;
1382 uint32_t exit_status
;
1385 static void run_context_free(RunContext
*c
) {
1388 c
->forward
= pty_forward_free(c
->forward
);
1389 c
->match
= sd_bus_slot_unref(c
->match
);
1390 c
->bus
= sd_bus_unref(c
->bus
);
1391 c
->event
= sd_event_unref(c
->event
);
1393 free(c
->active_state
);
1397 static void run_context_check_done(RunContext
*c
) {
1403 done
= STRPTR_IN_SET(c
->active_state
, "inactive", "failed") && !c
->has_job
;
1407 if (c
->forward
&& done
) /* If the service is gone, it's time to drain the output */
1408 done
= pty_forward_drain(c
->forward
);
1411 sd_event_exit(c
->event
, EXIT_SUCCESS
);
1414 static int map_job(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
1420 r
= sd_bus_message_read(m
, "(uo)", &id
, &job
);
1424 *b
= id
!= 0 || !streq(job
, "/");
1428 static int run_context_update(RunContext
*c
, const char *path
) {
1430 static const struct bus_properties_map map
[] = {
1431 { "ActiveState", "s", NULL
, offsetof(RunContext
, active_state
) },
1432 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_exit_usec
) },
1433 { "InactiveEnterTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_enter_usec
) },
1434 { "Result", "s", NULL
, offsetof(RunContext
, result
) },
1435 { "ExecMainCode", "i", NULL
, offsetof(RunContext
, exit_code
) },
1436 { "ExecMainStatus", "i", NULL
, offsetof(RunContext
, exit_status
) },
1437 { "CPUUsageNSec", "t", NULL
, offsetof(RunContext
, cpu_usage_nsec
) },
1438 { "MemoryPeak", "t", NULL
, offsetof(RunContext
, memory_peak
) },
1439 { "MemorySwapPeak", "t", NULL
, offsetof(RunContext
, memory_swap_peak
) },
1440 { "IPIngressBytes", "t", NULL
, offsetof(RunContext
, ip_ingress_bytes
) },
1441 { "IPEgressBytes", "t", NULL
, offsetof(RunContext
, ip_egress_bytes
) },
1442 { "IOReadBytes", "t", NULL
, offsetof(RunContext
, io_read_bytes
) },
1443 { "IOWriteBytes", "t", NULL
, offsetof(RunContext
, io_write_bytes
) },
1444 { "Job", "(uo)", map_job
, offsetof(RunContext
, has_job
) },
1448 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1451 r
= bus_map_all_properties(c
->bus
,
1452 "org.freedesktop.systemd1",
1460 sd_event_exit(c
->event
, EXIT_FAILURE
);
1461 return log_error_errno(r
, "Failed to query unit state: %s", bus_error_message(&error
, r
));
1464 run_context_check_done(c
);
1468 static int on_properties_changed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
1469 RunContext
*c
= ASSERT_PTR(userdata
);
1473 return run_context_update(c
, sd_bus_message_get_path(m
));
1476 static int pty_forward_handler(PTYForward
*f
, int rcode
, void *userdata
) {
1477 RunContext
*c
= userdata
;
1482 sd_event_exit(c
->event
, EXIT_FAILURE
);
1483 return log_error_errno(rcode
, "Error on PTY forwarding logic: %m");
1486 run_context_check_done(c
);
1490 static int make_transient_service_unit(
1492 sd_bus_message
**message
,
1493 const char *service
,
1494 const char *pty_path
) {
1496 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1503 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "StartTransientUnit");
1505 return bus_log_create_error(r
);
1507 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1509 return bus_log_create_error(r
);
1512 r
= sd_bus_message_append(m
, "ss", service
, "fail");
1514 return bus_log_create_error(r
);
1517 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1519 return bus_log_create_error(r
);
1521 r
= transient_service_set_properties(m
, pty_path
);
1525 r
= sd_bus_message_close_container(m
);
1527 return bus_log_create_error(r
);
1529 /* Auxiliary units */
1530 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1532 return bus_log_create_error(r
);
1534 *message
= TAKE_PTR(m
);
1538 static int bus_call_with_hint(
1540 sd_bus_message
*message
,
1542 sd_bus_message
**reply
) {
1544 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1547 r
= sd_bus_call(bus
, message
, 0, &error
, reply
);
1549 log_error_errno(r
, "Failed to start transient %s unit: %s", name
, bus_error_message(&error
, r
));
1551 if (arg_expand_environment
== 0 &&
1552 sd_bus_error_has_names(&error
,
1553 SD_BUS_ERROR_UNKNOWN_PROPERTY
,
1554 SD_BUS_ERROR_PROPERTY_READ_ONLY
))
1555 log_notice_errno(r
, "Hint: --expand-environment=no is not supported by old systemd");
1561 static int acquire_invocation_id(sd_bus
*bus
, const char *unit
, sd_id128_t
*ret
) {
1562 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1563 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1564 _cleanup_free_
char *object
= NULL
;
1573 object
= unit_dbus_path_from_name(unit
);
1578 r
= sd_bus_get_property(bus
,
1579 "org.freedesktop.systemd1",
1580 object
?: "/org/freedesktop/systemd1/unit/self",
1581 "org.freedesktop.systemd1.Unit",
1587 return log_error_errno(r
, "Failed to request invocation ID for unit: %s", bus_error_message(&error
, r
));
1589 r
= sd_bus_message_read_array(reply
, 'y', &p
, &l
);
1591 return bus_log_parse_error(r
);
1594 *ret
= SD_ID128_NULL
;
1595 return 0; /* no uuid set */
1598 if (l
!= sizeof(sd_id128_t
))
1599 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid UUID size, %zu != %zu.", l
, sizeof(sd_id128_t
));
1602 return !sd_id128_is_null(*ret
);
1605 static int start_transient_service(sd_bus
*bus
) {
1606 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1607 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1608 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1609 _cleanup_free_
char *service
= NULL
, *pty_path
= NULL
;
1610 _cleanup_close_
int master
= -EBADF
;
1615 if (arg_stdio
== ARG_STDIO_PTY
) {
1617 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
1618 master
= posix_openpt(O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
1620 return log_error_errno(errno
, "Failed to acquire pseudo tty: %m");
1622 r
= ptsname_malloc(master
, &pty_path
);
1624 return log_error_errno(r
, "Failed to determine tty name: %m");
1626 if (unlockpt(master
) < 0)
1627 return log_error_errno(errno
, "Failed to unlock tty: %m");
1629 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
1630 _cleanup_(sd_bus_unrefp
) sd_bus
*system_bus
= NULL
;
1631 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pty_reply
= NULL
;
1634 r
= sd_bus_default_system(&system_bus
);
1636 return log_error_errno(r
, "Failed to connect to system bus: %m");
1638 r
= bus_call_method(system_bus
,
1645 return log_error_errno(r
, "Failed to get machine PTY: %s", bus_error_message(&error
, r
));
1647 r
= sd_bus_message_read(pty_reply
, "hs", &master
, &s
);
1649 return bus_log_parse_error(r
);
1651 master
= fcntl(master
, F_DUPFD_CLOEXEC
, 3);
1653 return log_error_errno(errno
, "Failed to duplicate master fd: %m");
1655 pty_path
= strdup(s
);
1659 assert_not_reached();
1662 /* Optionally, wait for the start job to complete. If we are supposed to read the service's stdin
1663 * lets skip this however, because we should start that already when the start job is running, and
1664 * there's little point in waiting for the start job to complete in that case anyway, as we'll wait
1665 * for EOF anyway, which is going to be much later. */
1666 if (!arg_no_block
&& arg_stdio
== ARG_STDIO_NONE
) {
1667 r
= bus_wait_for_jobs_new(bus
, &w
);
1669 return log_error_errno(r
, "Could not watch jobs: %m");
1673 r
= unit_name_mangle_with_suffix(arg_unit
, "as unit",
1674 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
1675 ".service", &service
);
1677 return log_error_errno(r
, "Failed to mangle unit name: %m");
1679 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1684 r
= make_transient_service_unit(bus
, &m
, service
, pty_path
);
1688 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1690 r
= bus_call_with_hint(bus
, m
, "service", &reply
);
1697 r
= sd_bus_message_read(reply
, "o", &object
);
1699 return bus_log_parse_error(r
);
1701 r
= bus_wait_for_jobs_one(w
,
1703 arg_quiet
? 0 : BUS_WAIT_JOBS_LOG_ERROR
,
1704 arg_runtime_scope
== RUNTIME_SCOPE_USER
? STRV_MAKE_CONST("--user") : NULL
);
1710 sd_id128_t invocation_id
;
1712 r
= acquire_invocation_id(bus
, service
, &invocation_id
);
1715 if (r
== 0) /* No invocation UUID set */
1716 log_info("Running as unit: %s", service
);
1718 log_info("Running as unit: %s; invocation ID: " SD_ID128_FORMAT_STR
, service
, SD_ID128_FORMAT_VAL(invocation_id
));
1721 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
1722 _cleanup_(run_context_free
) RunContext c
= {
1723 .cpu_usage_nsec
= NSEC_INFINITY
,
1724 .memory_peak
= UINT64_MAX
,
1725 .memory_swap_peak
= UINT64_MAX
,
1726 .ip_ingress_bytes
= UINT64_MAX
,
1727 .ip_egress_bytes
= UINT64_MAX
,
1728 .io_read_bytes
= UINT64_MAX
,
1729 .io_write_bytes
= UINT64_MAX
,
1730 .inactive_exit_usec
= USEC_INFINITY
,
1731 .inactive_enter_usec
= USEC_INFINITY
,
1733 _cleanup_free_
char *path
= NULL
;
1735 c
.bus
= sd_bus_ref(bus
);
1737 r
= sd_event_default(&c
.event
);
1739 return log_error_errno(r
, "Failed to get event loop: %m");
1742 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
1743 (void) sd_event_add_signal(c
.event
, NULL
, SIGINT
, NULL
, NULL
);
1744 (void) sd_event_add_signal(c
.event
, NULL
, SIGTERM
, NULL
, NULL
);
1747 log_info("Press ^] three times within 1s to disconnect TTY.");
1749 r
= pty_forward_new(c
.event
, master
, PTY_FORWARD_IGNORE_INITIAL_VHANGUP
, &c
.forward
);
1751 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
1753 pty_forward_set_handler(c
.forward
, pty_forward_handler
, &c
);
1755 /* Make sure to process any TTY events before we process bus events */
1756 (void) pty_forward_set_priority(c
.forward
, SD_EVENT_PRIORITY_IMPORTANT
);
1758 if (!isempty(arg_background
))
1759 (void) pty_forward_set_background_color(c
.forward
, arg_background
);
1762 path
= unit_dbus_path_from_name(service
);
1766 r
= sd_bus_match_signal_async(
1769 "org.freedesktop.systemd1",
1771 "org.freedesktop.DBus.Properties",
1772 "PropertiesChanged",
1773 on_properties_changed
, NULL
, &c
);
1775 return log_error_errno(r
, "Failed to request properties changed signal match: %m");
1777 r
= sd_bus_attach_event(bus
, c
.event
, SD_EVENT_PRIORITY_NORMAL
);
1779 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1781 r
= run_context_update(&c
, path
);
1785 r
= sd_event_loop(c
.event
);
1787 return log_error_errno(r
, "Failed to run event loop: %m");
1792 r
= pty_forward_get_last_char(c
.forward
, &last_char
);
1793 if (r
>= 0 && !arg_quiet
&& last_char
!= '\n')
1794 fputc('\n', stdout
);
1797 if (arg_wait
&& !arg_quiet
) {
1799 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, with its
1800 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1802 c
.forward
= pty_forward_free(c
.forward
);
1804 if (!isempty(c
.result
))
1805 log_info("Finished with result: %s", strna(c
.result
));
1807 if (c
.exit_code
== CLD_EXITED
)
1808 log_info("Main processes terminated with: code=%s/status=%u",
1809 sigchld_code_to_string(c
.exit_code
), c
.exit_status
);
1810 else if (c
.exit_code
> 0)
1811 log_info("Main processes terminated with: code=%s/status=%s",
1812 sigchld_code_to_string(c
.exit_code
), signal_to_string(c
.exit_status
));
1814 if (timestamp_is_set(c
.inactive_enter_usec
) &&
1815 timestamp_is_set(c
.inactive_exit_usec
) &&
1816 c
.inactive_enter_usec
> c
.inactive_exit_usec
)
1817 log_info("Service runtime: %s",
1818 FORMAT_TIMESPAN(c
.inactive_enter_usec
- c
.inactive_exit_usec
, USEC_PER_MSEC
));
1820 if (c
.cpu_usage_nsec
!= NSEC_INFINITY
)
1821 log_info("CPU time consumed: %s",
1822 FORMAT_TIMESPAN(DIV_ROUND_UP(c
.cpu_usage_nsec
, NSEC_PER_USEC
), USEC_PER_MSEC
));
1824 if (c
.memory_peak
!= UINT64_MAX
)
1825 log_info("Memory peak: %s", FORMAT_BYTES(c
.memory_peak
));
1827 if (c
.memory_swap_peak
!= UINT64_MAX
)
1828 log_info("Memory swap peak: %s", FORMAT_BYTES(c
.memory_swap_peak
));
1830 if (c
.ip_ingress_bytes
!= UINT64_MAX
)
1831 log_info("IP traffic received: %s", FORMAT_BYTES(c
.ip_ingress_bytes
));
1833 if (c
.ip_egress_bytes
!= UINT64_MAX
)
1834 log_info("IP traffic sent: %s", FORMAT_BYTES(c
.ip_egress_bytes
));
1836 if (c
.io_read_bytes
!= UINT64_MAX
)
1837 log_info("IO bytes read: %s", FORMAT_BYTES(c
.io_read_bytes
));
1839 if (c
.io_write_bytes
!= UINT64_MAX
)
1840 log_info("IO bytes written: %s", FORMAT_BYTES(c
.io_write_bytes
));
1843 /* Try to propagate the service's return value. But if the service defines
1844 * e.g. SuccessExitStatus, honour this, and return 0 to mean "success". */
1845 if (streq_ptr(c
.result
, "success"))
1846 return EXIT_SUCCESS
;
1847 if (streq_ptr(c
.result
, "exit-code") && c
.exit_status
> 0)
1848 return c
.exit_status
;
1849 if (streq_ptr(c
.result
, "signal"))
1850 return EXIT_EXCEPTION
;
1851 return EXIT_FAILURE
;
1854 return EXIT_SUCCESS
;
1857 static int start_transient_scope(sd_bus
*bus
) {
1858 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1859 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1860 _cleanup_strv_free_
char **env
= NULL
, **user_env
= NULL
;
1861 _cleanup_free_
char *scope
= NULL
;
1862 const char *object
= NULL
;
1863 sd_id128_t invocation_id
;
1864 bool allow_pidfd
= true;
1868 assert(!strv_isempty(arg_cmdline
));
1870 r
= bus_wait_for_jobs_new(bus
, &w
);
1872 return log_error_errno(r
, "Could not watch jobs: %m");
1875 r
= unit_name_mangle_with_suffix(arg_unit
, "as unit",
1876 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
1879 return log_error_errno(r
, "Failed to mangle scope name: %m");
1881 r
= make_unit_name(bus
, UNIT_SCOPE
, &scope
);
1886 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1889 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1890 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1892 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "StartTransientUnit");
1894 return bus_log_create_error(r
);
1896 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1898 return bus_log_create_error(r
);
1901 r
= sd_bus_message_append(m
, "ss", scope
, "fail");
1903 return bus_log_create_error(r
);
1906 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1908 return bus_log_create_error(r
);
1910 r
= transient_scope_set_properties(m
, allow_pidfd
);
1914 r
= sd_bus_message_close_container(m
);
1916 return bus_log_create_error(r
);
1918 /* Auxiliary units */
1919 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1921 return bus_log_create_error(r
);
1923 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1925 if (sd_bus_error_has_names(&error
, SD_BUS_ERROR_UNKNOWN_PROPERTY
, SD_BUS_ERROR_PROPERTY_READ_ONLY
) && allow_pidfd
) {
1926 log_debug("Retrying with classic PIDs.");
1927 allow_pidfd
= false;
1931 return log_error_errno(r
, "Failed to start transient scope unit: %s", bus_error_message(&error
, r
));
1937 r
= sd_bus_message_read(reply
, "o", &object
);
1939 return bus_log_parse_error(r
);
1941 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
? 0 : BUS_WAIT_JOBS_LOG_ERROR
,
1942 arg_runtime_scope
== RUNTIME_SCOPE_USER
? STRV_MAKE_CONST("--user") : NULL
);
1946 r
= acquire_invocation_id(bus
, NULL
, &invocation_id
);
1950 log_debug("No invocation ID set.");
1952 if (strv_extendf(&user_env
, "INVOCATION_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(invocation_id
)) < 0)
1957 if (setpriority(PRIO_PROCESS
, 0, arg_nice
) < 0)
1958 return log_error_errno(errno
, "Failed to set nice level: %m");
1961 if (arg_exec_group
) {
1964 r
= get_group_creds(&arg_exec_group
, &gid
, 0);
1966 return log_error_errno(r
, "Failed to resolve group %s: %m", arg_exec_group
);
1968 if (setresgid(gid
, gid
, gid
) < 0)
1969 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1972 if (arg_exec_user
) {
1973 const char *home
, *shell
;
1977 r
= get_user_creds(&arg_exec_user
, &uid
, &gid
, &home
, &shell
, USER_CREDS_CLEAN
|USER_CREDS_PREFER_NSS
);
1979 return log_error_errno(r
, "Failed to resolve user %s: %m", arg_exec_user
);
1982 r
= strv_extendf(&user_env
, "HOME=%s", home
);
1988 r
= strv_extendf(&user_env
, "SHELL=%s", shell
);
1993 r
= strv_extendf(&user_env
, "USER=%s", arg_exec_user
);
1997 r
= strv_extendf(&user_env
, "LOGNAME=%s", arg_exec_user
);
2001 if (!arg_exec_group
) {
2002 if (setresgid(gid
, gid
, gid
) < 0)
2003 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
2006 if (setresuid(uid
, uid
, uid
) < 0)
2007 return log_error_errno(errno
, "Failed to change UID to " UID_FMT
": %m", uid
);
2010 if (arg_working_directory
&& chdir(arg_working_directory
) < 0)
2011 return log_error_errno(errno
, "Failed to change directory to '%s': %m", arg_working_directory
);
2013 env
= strv_env_merge(environ
, user_env
, arg_environment
);
2018 if (sd_id128_is_null(invocation_id
))
2019 log_info("Running as unit: %s", scope
);
2021 log_info("Running as unit: %s; invocation ID: " SD_ID128_FORMAT_STR
, scope
, SD_ID128_FORMAT_VAL(invocation_id
));
2024 if (arg_expand_environment
> 0) {
2025 _cleanup_strv_free_
char **expanded_cmdline
= NULL
, **unset_variables
= NULL
, **bad_variables
= NULL
;
2027 r
= replace_env_argv(arg_cmdline
, env
, &expanded_cmdline
, &unset_variables
, &bad_variables
);
2029 return log_error_errno(r
, "Failed to expand environment variables: %m");
2031 free_and_replace(arg_cmdline
, expanded_cmdline
);
2033 if (!strv_isempty(unset_variables
)) {
2034 _cleanup_free_
char *ju
= strv_join(unset_variables
, ", ");
2035 log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju
));
2038 if (!strv_isempty(bad_variables
)) {
2039 _cleanup_free_
char *jb
= strv_join(bad_variables
, ", ");
2040 log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb
));
2044 execvpe(arg_cmdline
[0], arg_cmdline
, env
);
2046 return log_error_errno(errno
, "Failed to execute: %m");
2049 static int make_transient_trigger_unit(
2051 sd_bus_message
**message
,
2053 const char *trigger
,
2054 const char *service
) {
2056 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
2065 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "StartTransientUnit");
2067 return bus_log_create_error(r
);
2069 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
2071 return bus_log_create_error(r
);
2074 r
= sd_bus_message_append(m
, "ss", trigger
, "fail");
2076 return bus_log_create_error(r
);
2079 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
2081 return bus_log_create_error(r
);
2083 if (streq(suffix
, ".path"))
2084 r
= transient_unit_set_properties(m
, UNIT_PATH
, arg_path_property
);
2085 else if (streq(suffix
, ".socket"))
2086 r
= transient_unit_set_properties(m
, UNIT_SOCKET
, arg_socket_property
);
2087 else if (streq(suffix
, ".timer"))
2088 r
= transient_timer_set_properties(m
);
2090 assert_not_reached();
2094 r
= sd_bus_message_close_container(m
);
2096 return bus_log_create_error(r
);
2098 r
= sd_bus_message_open_container(m
, 'a', "(sa(sv))");
2100 return bus_log_create_error(r
);
2102 if (!strv_isempty(arg_cmdline
)) {
2103 r
= sd_bus_message_open_container(m
, 'r', "sa(sv)");
2105 return bus_log_create_error(r
);
2107 r
= sd_bus_message_append(m
, "s", service
);
2109 return bus_log_create_error(r
);
2111 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
2113 return bus_log_create_error(r
);
2115 r
= transient_service_set_properties(m
, NULL
);
2119 r
= sd_bus_message_close_container(m
);
2121 return bus_log_create_error(r
);
2123 r
= sd_bus_message_close_container(m
);
2125 return bus_log_create_error(r
);
2128 r
= sd_bus_message_close_container(m
);
2130 return bus_log_create_error(r
);
2132 *message
= TAKE_PTR(m
);
2136 static int start_transient_trigger(sd_bus
*bus
, const char *suffix
) {
2137 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
2138 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
2139 _cleanup_free_
char *trigger
= NULL
, *service
= NULL
;
2140 const char *object
= NULL
;
2146 r
= bus_wait_for_jobs_new(bus
, &w
);
2148 return log_error_errno(r
, "Could not watch jobs: %m");
2151 switch (unit_name_to_type(arg_unit
)) {
2154 service
= strdup(arg_unit
);
2158 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
2160 return log_error_errno(r
, "Failed to change unit suffix: %m");
2164 trigger
= strdup(arg_unit
);
2168 r
= unit_name_change_suffix(trigger
, ".service", &service
);
2170 return log_error_errno(r
, "Failed to change unit suffix: %m");
2174 r
= unit_name_mangle_with_suffix(arg_unit
, "as unit",
2175 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2176 ".service", &service
);
2178 return log_error_errno(r
, "Failed to mangle unit name: %m");
2180 r
= unit_name_mangle_with_suffix(arg_unit
, "as trigger",
2181 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
2184 return log_error_errno(r
, "Failed to mangle unit name: %m");
2189 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
2193 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
2195 return log_error_errno(r
, "Failed to change unit suffix: %m");
2198 r
= make_transient_trigger_unit(bus
, &m
, suffix
, trigger
, service
);
2202 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
2204 r
= bus_call_with_hint(bus
, m
, suffix
+ 1, &reply
);
2208 r
= sd_bus_message_read(reply
, "o", &object
);
2210 return bus_log_parse_error(r
);
2212 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
? 0 : BUS_WAIT_JOBS_LOG_ERROR
,
2213 arg_runtime_scope
== RUNTIME_SCOPE_USER
? STRV_MAKE_CONST("--user") : NULL
);
2218 log_info("Running %s as unit: %s", suffix
+ 1, trigger
);
2219 if (!strv_isempty(arg_cmdline
))
2220 log_info("Will run service as unit: %s", service
);
2223 return EXIT_SUCCESS
;
2226 static bool shall_make_executable_absolute(void) {
2229 if (strv_isempty(arg_cmdline
))
2231 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
2234 FOREACH_STRING(f
, "RootDirectory=", "RootImage=", "ExecSearchPath=", "MountImages=", "ExtensionImages=")
2235 if (strv_find_startswith(arg_property
, f
))
2241 static int run(int argc
, char* argv
[]) {
2242 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
2245 log_show_color(true);
2246 log_parse_environment();
2249 if (invoked_as(argv
, "uid0"))
2250 r
= parse_argv_sudo_mode(argc
, argv
);
2252 r
= parse_argv(argc
, argv
);
2256 if (shall_make_executable_absolute()) {
2257 /* Patch in an absolute path to fail early for user convenience, but only when we can do it
2258 * (i.e. we will be running from the same file system). This also uses the user's $PATH,
2259 * while we use a fixed search path in the manager. */
2261 _cleanup_free_
char *command
= NULL
;
2262 r
= find_executable(arg_cmdline
[0], &command
);
2264 return log_error_errno(r
, "Failed to find executable %s: %m", arg_cmdline
[0]);
2266 free_and_replace(arg_cmdline
[0], command
);
2269 if (!arg_description
) {
2272 if (strv_isempty(arg_cmdline
))
2273 t
= strdup(arg_unit
);
2275 t
= quote_command_line(arg_cmdline
, SHELL_ESCAPE_EMPTY
);
2279 free_and_replace(arg_description
, t
);
2282 /* For backward compatibility reasons env var expansion is disabled by default for scopes, and
2283 * enabled by default for everything else. Try to detect it and print a warning, so that we can
2284 * change it in the future and harmonize it. */
2285 if (arg_expand_environment
< 0) {
2286 arg_expand_environment
= !arg_scope
;
2288 if (!arg_quiet
&& arg_scope
&& strchr(arg_description
, '$'))
2289 log_warning("Scope command line contains environment variable, which is not expanded"
2290 " by default for now, but will be expanded by default in the future."
2291 " Use --expand-environment=yes/no to explicitly control it as needed.");
2294 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the
2295 * limited direct connection */
2297 arg_stdio
!= ARG_STDIO_NONE
||
2298 (arg_runtime_scope
== RUNTIME_SCOPE_USER
&& arg_transport
!= BUS_TRANSPORT_LOCAL
))
2299 r
= bus_connect_transport(arg_transport
, arg_host
, arg_runtime_scope
, &bus
);
2301 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, arg_runtime_scope
, &bus
);
2303 return bus_log_connect_error(r
, arg_transport
);
2306 return start_transient_scope(bus
);
2307 if (arg_path_property
)
2308 return start_transient_trigger(bus
, ".path");
2309 if (arg_socket_property
)
2310 return start_transient_trigger(bus
, ".socket");
2312 return start_transient_trigger(bus
, ".timer");
2313 return start_transient_service(bus
);
2316 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);