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"
21 #include "exit-status.h"
23 #include "format-util.h"
24 #include "main-func.h"
25 #include "parse-argument.h"
26 #include "parse-util.h"
27 #include "path-util.h"
28 #include "pretty-print.h"
29 #include "process-util.h"
31 #include "signal-util.h"
32 #include "spawn-polkit-agent.h"
34 #include "terminal-util.h"
36 #include "unit-name.h"
37 #include "user-util.h"
39 static bool arg_ask_password
= true;
40 static bool arg_scope
= false;
41 static bool arg_remain_after_exit
= false;
42 static bool arg_no_block
= false;
43 static bool arg_wait
= false;
44 static const char *arg_unit
= NULL
;
45 static const char *arg_description
= NULL
;
46 static const char *arg_slice
= NULL
;
47 static bool arg_slice_inherit
= false;
48 static bool arg_expand_environment
= true;
49 static bool arg_send_sighup
= false;
50 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
51 static const char *arg_host
= NULL
;
52 static RuntimeScope arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
53 static const char *arg_service_type
= NULL
;
54 static const char *arg_exec_user
= NULL
;
55 static const char *arg_exec_group
= NULL
;
56 static int arg_nice
= 0;
57 static bool arg_nice_set
= false;
58 static char **arg_environment
= NULL
;
59 static char **arg_property
= NULL
;
61 ARG_STDIO_NONE
, /* The default, as it is for normal services, stdin connected to /dev/null, and stdout+stderr to the journal */
62 ARG_STDIO_PTY
, /* Interactive behaviour, requested by --pty: we allocate a pty and connect it to the TTY we are invoked from */
63 ARG_STDIO_DIRECT
, /* Directly pass our stdin/stdout/stderr to the activated service, useful for usage in shell pipelines, requested by --pipe */
64 ARG_STDIO_AUTO
, /* If --pipe and --pty are used together we use --pty when invoked on a TTY, and --pipe otherwise */
65 } arg_stdio
= ARG_STDIO_NONE
;
66 static char **arg_path_property
= NULL
;
67 static char **arg_socket_property
= NULL
;
68 static char **arg_timer_property
= NULL
;
69 static bool arg_with_timer
= false;
70 static bool arg_quiet
= false;
71 static bool arg_aggressive_gc
= false;
72 static char *arg_working_directory
= NULL
;
73 static bool arg_shell
= false;
74 static char **arg_cmdline
= NULL
;
76 STATIC_DESTRUCTOR_REGISTER(arg_environment
, strv_freep
);
77 STATIC_DESTRUCTOR_REGISTER(arg_property
, strv_freep
);
78 STATIC_DESTRUCTOR_REGISTER(arg_path_property
, strv_freep
);
79 STATIC_DESTRUCTOR_REGISTER(arg_socket_property
, strv_freep
);
80 STATIC_DESTRUCTOR_REGISTER(arg_timer_property
, strv_freep
);
81 STATIC_DESTRUCTOR_REGISTER(arg_working_directory
, freep
);
82 STATIC_DESTRUCTOR_REGISTER(arg_cmdline
, strv_freep
);
84 static int help(void) {
85 _cleanup_free_
char *link
= NULL
;
88 r
= terminal_urlify_man("systemd-run", "1", &link
);
92 printf("%s [OPTIONS...] COMMAND [ARGUMENTS...]\n"
93 "\n%sRun the specified command in a transient scope or service.%s\n\n"
94 " -h --help Show this help\n"
95 " --version Show package version\n"
96 " --no-ask-password Do not prompt for password\n"
97 " --user Run as user unit\n"
98 " -H --host=[USER@]HOST Operate on remote host\n"
99 " -M --machine=CONTAINER Operate on local container\n"
100 " --scope Run this as scope rather than service\n"
101 " -u --unit=UNIT Run under the specified unit name\n"
102 " -p --property=NAME=VALUE Set service or scope unit property\n"
103 " --description=TEXT Description for unit\n"
104 " --slice=SLICE Run in the specified slice\n"
105 " --slice-inherit Inherit the slice\n"
106 " --expand-environment=BOOL Control expansion of environment variables\n"
107 " --no-block Do not wait until operation finished\n"
108 " -r --remain-after-exit Leave service around until explicitly stopped\n"
109 " --wait Wait until service stopped again\n"
110 " --send-sighup Send SIGHUP when terminating\n"
111 " --service-type=TYPE Service type\n"
112 " --uid=USER Run as system user\n"
113 " --gid=GROUP Run as system group\n"
114 " --nice=NICE Nice level\n"
115 " --working-directory=PATH Set working directory\n"
116 " -d --same-dir Inherit working directory from caller\n"
117 " -E --setenv=NAME[=VALUE] Set environment variable\n"
118 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
120 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
121 " -q --quiet Suppress information messages during runtime\n"
122 " -G --collect Unload unit after it ran, even when failed\n"
123 " -S --shell Invoke a $SHELL interactively\n\n"
125 " --path-property=NAME=VALUE Set path unit property\n\n"
127 " --socket-property=NAME=VALUE Set socket unit property\n\n"
129 " --on-active=SECONDS Run after SECONDS delay\n"
130 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
131 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
132 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
133 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
134 " --on-calendar=SPEC Realtime timer\n"
135 " --on-timezone-change Run when the timezone changes\n"
136 " --on-clock-change Run when the realtime clock jumps\n"
137 " --timer-property=NAME=VALUE Set timer unit property\n"
138 "\nSee the %s for details.\n",
139 program_invocation_short_name
,
147 static int add_timer_property(const char *name
, const char *val
) {
153 p
= strjoin(name
, "=", val
);
157 if (strv_consume(&arg_timer_property
, p
) < 0)
163 static int parse_argv(int argc
, char *argv
[]) {
173 ARG_EXPAND_ENVIRONMENT
,
183 ARG_ON_UNIT_INACTIVE
,
185 ARG_ON_TIMEZONE_CHANGE
,
193 ARG_WORKING_DIRECTORY
,
197 static const struct option options
[] = {
198 { "help", no_argument
, NULL
, 'h' },
199 { "version", no_argument
, NULL
, ARG_VERSION
},
200 { "user", no_argument
, NULL
, ARG_USER
},
201 { "system", no_argument
, NULL
, ARG_SYSTEM
},
202 { "scope", no_argument
, NULL
, ARG_SCOPE
},
203 { "unit", required_argument
, NULL
, 'u' },
204 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
205 { "slice", required_argument
, NULL
, ARG_SLICE
},
206 { "slice-inherit", no_argument
, NULL
, ARG_SLICE_INHERIT
},
207 { "remain-after-exit", no_argument
, NULL
, 'r' },
208 { "expand-environment", required_argument
, NULL
, ARG_EXPAND_ENVIRONMENT
},
209 { "send-sighup", no_argument
, NULL
, ARG_SEND_SIGHUP
},
210 { "host", required_argument
, NULL
, 'H' },
211 { "machine", required_argument
, NULL
, 'M' },
212 { "service-type", required_argument
, NULL
, ARG_SERVICE_TYPE
},
213 { "wait", no_argument
, NULL
, ARG_WAIT
},
214 { "uid", required_argument
, NULL
, ARG_EXEC_USER
},
215 { "gid", required_argument
, NULL
, ARG_EXEC_GROUP
},
216 { "nice", required_argument
, NULL
, ARG_NICE
},
217 { "setenv", required_argument
, NULL
, 'E' },
218 { "property", required_argument
, NULL
, 'p' },
219 { "tty", no_argument
, NULL
, 't' }, /* deprecated alias */
220 { "pty", no_argument
, NULL
, 't' },
221 { "pipe", no_argument
, NULL
, 'P' },
222 { "quiet", no_argument
, NULL
, 'q' },
223 { "on-active", required_argument
, NULL
, ARG_ON_ACTIVE
},
224 { "on-boot", required_argument
, NULL
, ARG_ON_BOOT
},
225 { "on-startup", required_argument
, NULL
, ARG_ON_STARTUP
},
226 { "on-unit-active", required_argument
, NULL
, ARG_ON_UNIT_ACTIVE
},
227 { "on-unit-inactive", required_argument
, NULL
, ARG_ON_UNIT_INACTIVE
},
228 { "on-calendar", required_argument
, NULL
, ARG_ON_CALENDAR
},
229 { "on-timezone-change", no_argument
, NULL
, ARG_ON_TIMEZONE_CHANGE
},
230 { "on-clock-change", no_argument
, NULL
, ARG_ON_CLOCK_CHANGE
},
231 { "timer-property", required_argument
, NULL
, ARG_TIMER_PROPERTY
},
232 { "path-property", required_argument
, NULL
, ARG_PATH_PROPERTY
},
233 { "socket-property", required_argument
, NULL
, ARG_SOCKET_PROPERTY
},
234 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
235 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
236 { "collect", no_argument
, NULL
, 'G' },
237 { "working-directory", required_argument
, NULL
, ARG_WORKING_DIRECTORY
},
238 { "same-dir", no_argument
, NULL
, 'd' },
239 { "shell", no_argument
, NULL
, 'S' },
243 bool with_trigger
= false;
249 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
250 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
252 while ((c
= getopt_long(argc
, argv
, "+hrH:M:E:p:tPqGdSu:", options
, NULL
)) >= 0)
262 case ARG_NO_ASK_PASSWORD
:
263 arg_ask_password
= false;
267 arg_runtime_scope
= RUNTIME_SCOPE_USER
;
271 arg_runtime_scope
= RUNTIME_SCOPE_SYSTEM
;
282 case ARG_DESCRIPTION
:
283 arg_description
= optarg
;
290 case ARG_SLICE_INHERIT
:
291 arg_slice_inherit
= true;
294 case ARG_EXPAND_ENVIRONMENT
:
295 r
= parse_boolean_argument("--expand-environment=", optarg
, &arg_expand_environment
);
300 case ARG_SEND_SIGHUP
:
301 arg_send_sighup
= true;
305 arg_remain_after_exit
= true;
309 arg_transport
= BUS_TRANSPORT_REMOTE
;
314 arg_transport
= BUS_TRANSPORT_MACHINE
;
318 case ARG_SERVICE_TYPE
:
319 arg_service_type
= optarg
;
323 arg_exec_user
= optarg
;
327 arg_exec_group
= optarg
;
331 r
= parse_nice(optarg
, &arg_nice
);
333 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
339 r
= strv_env_replace_strdup_passthrough(&arg_environment
, optarg
);
341 return log_error_errno(r
, "Cannot assign environment variable %s: %m", optarg
);
346 if (strv_extend(&arg_property
, optarg
) < 0)
351 case 't': /* --pty */
352 if (IN_SET(arg_stdio
, ARG_STDIO_DIRECT
, ARG_STDIO_AUTO
)) /* if --pipe is already used, upgrade to auto mode */
353 arg_stdio
= ARG_STDIO_AUTO
;
355 arg_stdio
= ARG_STDIO_PTY
;
358 case 'P': /* --pipe */
359 if (IN_SET(arg_stdio
, ARG_STDIO_PTY
, ARG_STDIO_AUTO
)) /* If --pty is already used, upgrade to auto mode */
360 arg_stdio
= ARG_STDIO_AUTO
;
362 arg_stdio
= ARG_STDIO_DIRECT
;
370 r
= add_timer_property("OnActiveSec", optarg
);
374 arg_with_timer
= true;
378 r
= add_timer_property("OnBootSec", optarg
);
382 arg_with_timer
= true;
386 r
= add_timer_property("OnStartupSec", optarg
);
390 arg_with_timer
= true;
393 case ARG_ON_UNIT_ACTIVE
:
394 r
= add_timer_property("OnUnitActiveSec", optarg
);
398 arg_with_timer
= true;
401 case ARG_ON_UNIT_INACTIVE
:
402 r
= add_timer_property("OnUnitInactiveSec", optarg
);
406 arg_with_timer
= true;
409 case ARG_ON_CALENDAR
: {
410 _cleanup_(calendar_spec_freep
) CalendarSpec
*cs
= NULL
;
412 r
= calendar_spec_from_string(optarg
, &cs
);
414 return log_error_errno(r
, "Failed to parse calendar event specification: %m");
416 /* Let's make sure the given calendar event is not in the past */
417 r
= calendar_spec_next_usec(cs
, now(CLOCK_REALTIME
), NULL
);
419 /* The calendar event is in the past — let's warn about this, but install it
420 * anyway as is. The service manager will trigger the service right away.
421 * Moreover, the server side might have a different clock or timezone than we
422 * do, hence it should decide when or whether to run something. */
423 log_warning("Specified calendar expression is in the past, proceeding anyway.");
425 return log_error_errno(r
, "Failed to calculate next time calendar expression elapses: %m");
427 r
= add_timer_property("OnCalendar", optarg
);
431 arg_with_timer
= true;
435 case ARG_ON_TIMEZONE_CHANGE
:
436 r
= add_timer_property("OnTimezoneChange", "yes");
440 arg_with_timer
= true;
443 case ARG_ON_CLOCK_CHANGE
:
444 r
= add_timer_property("OnClockChange", "yes");
448 arg_with_timer
= true;
451 case ARG_TIMER_PROPERTY
:
453 if (strv_extend(&arg_timer_property
, optarg
) < 0)
456 arg_with_timer
= arg_with_timer
||
457 STARTSWITH_SET(optarg
,
462 "OnUnitInactiveSec=",
466 case ARG_PATH_PROPERTY
:
468 if (strv_extend(&arg_path_property
, optarg
) < 0)
473 case ARG_SOCKET_PROPERTY
:
475 if (strv_extend(&arg_socket_property
, optarg
) < 0)
488 case ARG_WORKING_DIRECTORY
:
489 r
= parse_path_argument(optarg
, true, &arg_working_directory
);
496 _cleanup_free_
char *p
= NULL
;
500 return log_error_errno(r
, "Failed to get current working directory: %m");
502 if (empty_or_root(p
))
503 arg_working_directory
= mfree(arg_working_directory
);
505 free_and_replace(arg_working_directory
, p
);
510 arg_aggressive_gc
= true;
521 assert_not_reached();
524 /* If we are talking to the per-user instance PolicyKit isn't going to help */
525 if (arg_runtime_scope
== RUNTIME_SCOPE_USER
)
526 arg_ask_password
= false;
528 with_trigger
= !!arg_path_property
|| !!arg_socket_property
|| arg_with_timer
;
530 /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
531 if ((int) !!arg_path_property
+ (int) !!arg_socket_property
+ (int) arg_with_timer
> 1)
532 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
533 "Only single trigger (path, socket, timer) unit can be created.");
536 /* If --shell is imply --pty --pipe --same-dir --service-type=exec --wait --collect, unless otherwise
540 if (arg_stdio
== ARG_STDIO_NONE
)
541 arg_stdio
= ARG_STDIO_AUTO
;
543 if (!arg_working_directory
) {
544 r
= safe_getcwd(&arg_working_directory
);
546 return log_error_errno(r
, "Failed to get current working directory: %m");
549 if (!arg_service_type
) {
550 arg_service_type
= strdup("exec");
551 if (!arg_service_type
)
558 arg_aggressive_gc
= true;
561 if (arg_stdio
== ARG_STDIO_AUTO
)
562 /* If we both --pty and --pipe are specified we'll automatically pick --pty if we are connected fully
563 * to a TTY and pick direct fd passing otherwise. This way, we automatically adapt to usage in a shell
564 * pipeline, but we are neatly interactive with tty-level isolation otherwise. */
565 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ?
573 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "If --shell is used, no command line is expected.");
575 l
= strv_copy(argv
+ optind
);
579 strv_free_and_replace(arg_cmdline
, l
);
581 } else if (arg_shell
) {
582 _cleanup_free_
char *s
= NULL
;
587 return log_error_errno(r
, "Failed to determine shell: %m");
593 strv_free_and_replace(arg_cmdline
, l
);
595 } else if (!arg_unit
|| !with_trigger
)
596 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Command line to execute required.");
598 if (arg_runtime_scope
== RUNTIME_SCOPE_USER
&& arg_transport
== BUS_TRANSPORT_REMOTE
)
599 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
600 "Execution in user context is not supported on remote systems.");
602 if (arg_scope
&& arg_transport
== BUS_TRANSPORT_REMOTE
)
603 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
604 "Scope execution is not supported on remote systems.");
606 if (arg_scope
&& (arg_remain_after_exit
|| arg_service_type
))
607 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
608 "--remain-after-exit and --service-type= are not supported in --scope mode.");
610 if (arg_stdio
!= ARG_STDIO_NONE
&& (with_trigger
|| arg_scope
))
611 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
612 "--pty/--pipe is not compatible in timer or --scope mode.");
614 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_transport
== BUS_TRANSPORT_REMOTE
)
615 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
616 "--pty/--pipe is only supported when connecting to the local system or containers.");
618 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_no_block
)
619 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
620 "--pty/--pipe is not compatible with --no-block.");
622 if (arg_scope
&& with_trigger
)
623 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
624 "Path, socket or timer options are not supported in --scope mode.");
626 if (arg_timer_property
&& !arg_with_timer
)
627 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
628 "--timer-property= has no effect without any other timer options.");
632 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
633 "--wait may not be combined with --no-block.");
636 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
637 "--wait may not be combined with path, socket or timer operations.");
640 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
641 "--wait may not be combined with --scope.");
647 static int transient_unit_set_properties(sd_bus_message
*m
, UnitType t
, char **properties
) {
650 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", arg_description
);
652 return bus_log_create_error(r
);
654 if (arg_aggressive_gc
) {
655 r
= sd_bus_message_append(m
, "(sv)", "CollectMode", "s", "inactive-or-failed");
657 return bus_log_create_error(r
);
660 return bus_append_unit_property_assignment_many(m
, t
, properties
);
663 static int transient_cgroup_set_properties(sd_bus_message
*m
) {
664 _cleanup_free_
char *name
= NULL
;
665 _cleanup_free_
char *slice
= NULL
;
669 if (arg_slice_inherit
) {
672 switch (arg_runtime_scope
) {
674 case RUNTIME_SCOPE_USER
:
675 r
= cg_pid_get_user_slice(0, &name
);
678 case RUNTIME_SCOPE_SYSTEM
:
679 r
= cg_pid_get_slice(0, &name
);
683 assert_not_reached();
687 return log_error_errno(r
, "Failed to get PID slice: %m");
689 end
= endswith(name
, ".slice");
695 if (!isempty(arg_slice
) && !strextend_with_separator(&name
, "-", arg_slice
))
701 r
= unit_name_mangle_with_suffix(name
, "as slice",
702 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
705 return log_error_errno(r
, "Failed to mangle name '%s': %m", arg_slice
);
707 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", slice
);
709 return bus_log_create_error(r
);
714 static int transient_kill_set_properties(sd_bus_message
*m
) {
719 if (arg_send_sighup
) {
720 r
= sd_bus_message_append(m
, "(sv)", "SendSIGHUP", "b", arg_send_sighup
);
722 return bus_log_create_error(r
);
728 static int transient_service_set_properties(sd_bus_message
*m
, const char *pty_path
) {
729 bool send_term
= false;
732 /* We disable environment expansion on the server side via ExecStartEx=:.
733 * ExecStartEx was added relatively recently (v243), and some bugs were fixed only later.
734 * So use that feature only if required. It will fail with older systemds. */
735 bool use_ex_prop
= !arg_expand_environment
;
739 r
= transient_unit_set_properties(m
, UNIT_SERVICE
, arg_property
);
743 r
= transient_kill_set_properties(m
);
747 r
= transient_cgroup_set_properties(m
);
751 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
752 r
= sd_bus_message_append(m
, "(sv)", "AddRef", "b", 1);
754 return bus_log_create_error(r
);
757 if (arg_remain_after_exit
) {
758 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit
);
760 return bus_log_create_error(r
);
763 if (arg_service_type
) {
764 r
= sd_bus_message_append(m
, "(sv)", "Type", "s", arg_service_type
);
766 return bus_log_create_error(r
);
770 r
= sd_bus_message_append(m
, "(sv)", "User", "s", arg_exec_user
);
772 return bus_log_create_error(r
);
775 if (arg_exec_group
) {
776 r
= sd_bus_message_append(m
, "(sv)", "Group", "s", arg_exec_group
);
778 return bus_log_create_error(r
);
782 r
= sd_bus_message_append(m
, "(sv)", "Nice", "i", arg_nice
);
784 return bus_log_create_error(r
);
787 if (arg_working_directory
) {
788 r
= sd_bus_message_append(m
, "(sv)", "WorkingDirectory", "s", arg_working_directory
);
790 return bus_log_create_error(r
);
794 r
= sd_bus_message_append(m
,
796 "StandardInput", "s", "tty",
797 "StandardOutput", "s", "tty",
798 "StandardError", "s", "tty",
799 "TTYPath", "s", pty_path
);
801 return bus_log_create_error(r
);
805 } else if (arg_stdio
== ARG_STDIO_DIRECT
) {
806 r
= sd_bus_message_append(m
,
808 "StandardInputFileDescriptor", "h", STDIN_FILENO
,
809 "StandardOutputFileDescriptor", "h", STDOUT_FILENO
,
810 "StandardErrorFileDescriptor", "h", STDERR_FILENO
);
812 return bus_log_create_error(r
);
814 send_term
= isatty(STDIN_FILENO
) || isatty(STDOUT_FILENO
) || isatty(STDERR_FILENO
);
822 _cleanup_free_
char *n
= NULL
;
824 n
= strjoin("TERM=", e
);
828 r
= sd_bus_message_append(m
,
830 "Environment", "as", 1, n
);
832 return bus_log_create_error(r
);
836 if (!strv_isempty(arg_environment
)) {
837 r
= sd_bus_message_open_container(m
, 'r', "sv");
839 return bus_log_create_error(r
);
841 r
= sd_bus_message_append(m
, "s", "Environment");
843 return bus_log_create_error(r
);
845 r
= sd_bus_message_open_container(m
, 'v', "as");
847 return bus_log_create_error(r
);
849 r
= sd_bus_message_append_strv(m
, arg_environment
);
851 return bus_log_create_error(r
);
853 r
= sd_bus_message_close_container(m
);
855 return bus_log_create_error(r
);
857 r
= sd_bus_message_close_container(m
);
859 return bus_log_create_error(r
);
863 if (!strv_isempty(arg_cmdline
)) {
864 r
= sd_bus_message_open_container(m
, 'r', "sv");
866 return bus_log_create_error(r
);
868 r
= sd_bus_message_append(m
, "s",
869 use_ex_prop
? "ExecStartEx" : "ExecStart");
871 return bus_log_create_error(r
);
873 r
= sd_bus_message_open_container(m
, 'v',
874 use_ex_prop
? "a(sasas)" : "a(sasb)");
876 return bus_log_create_error(r
);
878 r
= sd_bus_message_open_container(m
, 'a',
879 use_ex_prop
? "(sasas)" : "(sasb)");
881 return bus_log_create_error(r
);
883 r
= sd_bus_message_open_container(m
, 'r',
884 use_ex_prop
? "sasas" : "sasb");
886 return bus_log_create_error(r
);
888 r
= sd_bus_message_append(m
, "s", arg_cmdline
[0]);
890 return bus_log_create_error(r
);
892 r
= sd_bus_message_append_strv(m
, arg_cmdline
);
894 return bus_log_create_error(r
);
897 r
= sd_bus_message_append_strv(
899 STRV_MAKE(arg_expand_environment
? NULL
: "no-env-expand"));
901 r
= sd_bus_message_append(m
, "b", false);
903 return bus_log_create_error(r
);
905 r
= sd_bus_message_close_container(m
);
907 return bus_log_create_error(r
);
909 r
= sd_bus_message_close_container(m
);
911 return bus_log_create_error(r
);
913 r
= sd_bus_message_close_container(m
);
915 return bus_log_create_error(r
);
917 r
= sd_bus_message_close_container(m
);
919 return bus_log_create_error(r
);
925 static int transient_scope_set_properties(sd_bus_message
*m
) {
930 r
= transient_unit_set_properties(m
, UNIT_SCOPE
, arg_property
);
934 r
= transient_kill_set_properties(m
);
938 r
= transient_cgroup_set_properties(m
);
942 r
= sd_bus_message_append(m
, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached());
944 return bus_log_create_error(r
);
949 static int transient_timer_set_properties(sd_bus_message
*m
) {
954 r
= transient_unit_set_properties(m
, UNIT_TIMER
, arg_timer_property
);
958 /* Automatically clean up our transient timers */
959 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterElapse", "b", false);
961 return bus_log_create_error(r
);
966 static int make_unit_name(sd_bus
*bus
, UnitType t
, char **ret
) {
967 const char *unique
, *id
;
973 assert(t
< _UNIT_TYPE_MAX
);
975 r
= sd_bus_get_unique_name(bus
, &unique
);
979 /* We couldn't get the unique name, which is a pretty
980 * common case if we are connected to systemd
981 * directly. In that case, just pick a random uuid as
984 r
= sd_id128_randomize(&rnd
);
986 return log_error_errno(r
, "Failed to generate random run unit name: %m");
988 if (asprintf(ret
, "run-r" SD_ID128_FORMAT_STR
".%s", SD_ID128_FORMAT_VAL(rnd
), unit_type_to_string(t
)) < 0)
994 /* We managed to get the unique name, then let's use that to name our transient units. */
996 id
= startswith(unique
, ":1."); /* let' strip the usual prefix */
998 id
= startswith(unique
, ":"); /* the spec only requires things to start with a colon, hence
999 * let's add a generic fallback for that. */
1001 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
1002 "Unique name %s has unexpected format.",
1005 p
= strjoin("run-u", id
, ".", unit_type_to_string(t
));
1013 typedef struct RunContext
{
1016 PTYForward
*forward
;
1019 /* Current state of the unit */
1023 /* The exit data of the unit */
1024 uint64_t inactive_exit_usec
;
1025 uint64_t inactive_enter_usec
;
1027 uint64_t cpu_usage_nsec
;
1028 uint64_t ip_ingress_bytes
;
1029 uint64_t ip_egress_bytes
;
1030 uint64_t io_read_bytes
;
1031 uint64_t io_write_bytes
;
1033 uint32_t exit_status
;
1036 static void run_context_free(RunContext
*c
) {
1039 c
->forward
= pty_forward_free(c
->forward
);
1040 c
->match
= sd_bus_slot_unref(c
->match
);
1041 c
->bus
= sd_bus_unref(c
->bus
);
1042 c
->event
= sd_event_unref(c
->event
);
1044 free(c
->active_state
);
1048 static void run_context_check_done(RunContext
*c
) {
1054 done
= STRPTR_IN_SET(c
->active_state
, "inactive", "failed") && !c
->has_job
;
1058 if (c
->forward
&& done
) /* If the service is gone, it's time to drain the output */
1059 done
= pty_forward_drain(c
->forward
);
1062 sd_event_exit(c
->event
, EXIT_SUCCESS
);
1065 static int map_job(sd_bus
*bus
, const char *member
, sd_bus_message
*m
, sd_bus_error
*error
, void *userdata
) {
1071 r
= sd_bus_message_read(m
, "(uo)", &id
, &job
);
1075 *b
= id
!= 0 || !streq(job
, "/");
1079 static int run_context_update(RunContext
*c
, const char *path
) {
1081 static const struct bus_properties_map map
[] = {
1082 { "ActiveState", "s", NULL
, offsetof(RunContext
, active_state
) },
1083 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_exit_usec
) },
1084 { "InactiveEnterTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_enter_usec
) },
1085 { "Result", "s", NULL
, offsetof(RunContext
, result
) },
1086 { "ExecMainCode", "i", NULL
, offsetof(RunContext
, exit_code
) },
1087 { "ExecMainStatus", "i", NULL
, offsetof(RunContext
, exit_status
) },
1088 { "CPUUsageNSec", "t", NULL
, offsetof(RunContext
, cpu_usage_nsec
) },
1089 { "IPIngressBytes", "t", NULL
, offsetof(RunContext
, ip_ingress_bytes
) },
1090 { "IPEgressBytes", "t", NULL
, offsetof(RunContext
, ip_egress_bytes
) },
1091 { "IOReadBytes", "t", NULL
, offsetof(RunContext
, io_read_bytes
) },
1092 { "IOWriteBytes", "t", NULL
, offsetof(RunContext
, io_write_bytes
) },
1093 { "Job", "(uo)", map_job
, offsetof(RunContext
, has_job
) },
1097 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1100 r
= bus_map_all_properties(c
->bus
,
1101 "org.freedesktop.systemd1",
1109 sd_event_exit(c
->event
, EXIT_FAILURE
);
1110 return log_error_errno(r
, "Failed to query unit state: %s", bus_error_message(&error
, r
));
1113 run_context_check_done(c
);
1117 static int on_properties_changed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
1118 RunContext
*c
= ASSERT_PTR(userdata
);
1122 return run_context_update(c
, sd_bus_message_get_path(m
));
1125 static int pty_forward_handler(PTYForward
*f
, int rcode
, void *userdata
) {
1126 RunContext
*c
= userdata
;
1131 sd_event_exit(c
->event
, EXIT_FAILURE
);
1132 return log_error_errno(rcode
, "Error on PTY forwarding logic: %m");
1135 run_context_check_done(c
);
1139 static int make_transient_service_unit(
1141 sd_bus_message
**message
,
1142 const char *service
,
1143 const char *pty_path
) {
1145 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1152 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "StartTransientUnit");
1154 return bus_log_create_error(r
);
1156 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1158 return bus_log_create_error(r
);
1161 r
= sd_bus_message_append(m
, "ss", service
, "fail");
1163 return bus_log_create_error(r
);
1166 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1168 return bus_log_create_error(r
);
1170 r
= transient_service_set_properties(m
, pty_path
);
1174 r
= sd_bus_message_close_container(m
);
1176 return bus_log_create_error(r
);
1178 /* Auxiliary units */
1179 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1181 return bus_log_create_error(r
);
1183 *message
= TAKE_PTR(m
);
1187 static int bus_call_with_hint(
1189 sd_bus_message
*message
,
1191 sd_bus_message
**reply
) {
1193 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1196 r
= sd_bus_call(bus
, message
, 0, &error
, reply
);
1198 log_error_errno(r
, "Failed to start transient %s unit: %s", name
, bus_error_message(&error
, r
));
1200 if (!arg_expand_environment
&&
1201 sd_bus_error_has_names(&error
,
1202 SD_BUS_ERROR_UNKNOWN_PROPERTY
,
1203 SD_BUS_ERROR_PROPERTY_READ_ONLY
))
1204 log_notice_errno(r
, "Hint: --expand-environment=no is not supported by old systemd");
1210 static int start_transient_service(sd_bus
*bus
) {
1211 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1212 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1213 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1214 _cleanup_free_
char *service
= NULL
, *pty_path
= NULL
;
1215 _cleanup_close_
int master
= -EBADF
;
1220 if (arg_stdio
== ARG_STDIO_PTY
) {
1222 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
1223 master
= posix_openpt(O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
1225 return log_error_errno(errno
, "Failed to acquire pseudo tty: %m");
1227 r
= ptsname_malloc(master
, &pty_path
);
1229 return log_error_errno(r
, "Failed to determine tty name: %m");
1231 if (unlockpt(master
) < 0)
1232 return log_error_errno(errno
, "Failed to unlock tty: %m");
1234 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
1235 _cleanup_(sd_bus_unrefp
) sd_bus
*system_bus
= NULL
;
1236 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pty_reply
= NULL
;
1239 r
= sd_bus_default_system(&system_bus
);
1241 return log_error_errno(r
, "Failed to connect to system bus: %m");
1243 r
= sd_bus_call_method(system_bus
,
1244 "org.freedesktop.machine1",
1245 "/org/freedesktop/machine1",
1246 "org.freedesktop.machine1.Manager",
1252 return log_error_errno(r
, "Failed to get machine PTY: %s", bus_error_message(&error
, r
));
1254 r
= sd_bus_message_read(pty_reply
, "hs", &master
, &s
);
1256 return bus_log_parse_error(r
);
1258 master
= fcntl(master
, F_DUPFD_CLOEXEC
, 3);
1260 return log_error_errno(errno
, "Failed to duplicate master fd: %m");
1262 pty_path
= strdup(s
);
1266 assert_not_reached();
1269 /* Optionally, wait for the start job to complete. If we are supposed to read the service's stdin
1270 * lets skip this however, because we should start that already when the start job is running, and
1271 * there's little point in waiting for the start job to complete in that case anyway, as we'll wait
1272 * for EOF anyway, which is going to be much later. */
1273 if (!arg_no_block
&& arg_stdio
== ARG_STDIO_NONE
) {
1274 r
= bus_wait_for_jobs_new(bus
, &w
);
1276 return log_error_errno(r
, "Could not watch jobs: %m");
1280 r
= unit_name_mangle_with_suffix(arg_unit
, "as unit",
1281 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
1282 ".service", &service
);
1284 return log_error_errno(r
, "Failed to mangle unit name: %m");
1286 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1291 r
= make_transient_service_unit(bus
, &m
, service
, pty_path
);
1295 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1297 r
= bus_call_with_hint(bus
, m
, "service", &reply
);
1304 r
= sd_bus_message_read(reply
, "o", &object
);
1306 return bus_log_parse_error(r
);
1308 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
, arg_runtime_scope
== RUNTIME_SCOPE_USER
? STRV_MAKE_CONST("--user") : NULL
);
1314 log_info("Running as unit: %s", service
);
1316 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
1317 _cleanup_(run_context_free
) RunContext c
= {
1318 .cpu_usage_nsec
= NSEC_INFINITY
,
1319 .ip_ingress_bytes
= UINT64_MAX
,
1320 .ip_egress_bytes
= UINT64_MAX
,
1321 .io_read_bytes
= UINT64_MAX
,
1322 .io_write_bytes
= UINT64_MAX
,
1323 .inactive_exit_usec
= USEC_INFINITY
,
1324 .inactive_enter_usec
= USEC_INFINITY
,
1326 _cleanup_free_
char *path
= NULL
;
1328 c
.bus
= sd_bus_ref(bus
);
1330 r
= sd_event_default(&c
.event
);
1332 return log_error_errno(r
, "Failed to get event loop: %m");
1335 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
1336 (void) sd_event_add_signal(c
.event
, NULL
, SIGINT
, NULL
, NULL
);
1337 (void) sd_event_add_signal(c
.event
, NULL
, SIGTERM
, NULL
, NULL
);
1340 log_info("Press ^] three times within 1s to disconnect TTY.");
1342 r
= pty_forward_new(c
.event
, master
, PTY_FORWARD_IGNORE_INITIAL_VHANGUP
, &c
.forward
);
1344 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
1346 pty_forward_set_handler(c
.forward
, pty_forward_handler
, &c
);
1348 /* Make sure to process any TTY events before we process bus events */
1349 (void) pty_forward_set_priority(c
.forward
, SD_EVENT_PRIORITY_IMPORTANT
);
1352 path
= unit_dbus_path_from_name(service
);
1356 r
= sd_bus_match_signal_async(
1359 "org.freedesktop.systemd1",
1361 "org.freedesktop.DBus.Properties",
1362 "PropertiesChanged",
1363 on_properties_changed
, NULL
, &c
);
1365 return log_error_errno(r
, "Failed to request properties changed signal match: %m");
1367 r
= sd_bus_attach_event(bus
, c
.event
, SD_EVENT_PRIORITY_NORMAL
);
1369 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1371 r
= run_context_update(&c
, path
);
1375 r
= sd_event_loop(c
.event
);
1377 return log_error_errno(r
, "Failed to run event loop: %m");
1382 r
= pty_forward_get_last_char(c
.forward
, &last_char
);
1383 if (r
>= 0 && !arg_quiet
&& last_char
!= '\n')
1384 fputc('\n', stdout
);
1387 if (arg_wait
&& !arg_quiet
) {
1389 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, with its
1390 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1392 c
.forward
= pty_forward_free(c
.forward
);
1394 if (!isempty(c
.result
))
1395 log_info("Finished with result: %s", strna(c
.result
));
1397 if (c
.exit_code
== CLD_EXITED
)
1398 log_info("Main processes terminated with: code=%s/status=%u",
1399 sigchld_code_to_string(c
.exit_code
), c
.exit_status
);
1400 else if (c
.exit_code
> 0)
1401 log_info("Main processes terminated with: code=%s/status=%s",
1402 sigchld_code_to_string(c
.exit_code
), signal_to_string(c
.exit_status
));
1404 if (timestamp_is_set(c
.inactive_enter_usec
) &&
1405 timestamp_is_set(c
.inactive_exit_usec
) &&
1406 c
.inactive_enter_usec
> c
.inactive_exit_usec
)
1407 log_info("Service runtime: %s",
1408 FORMAT_TIMESPAN(c
.inactive_enter_usec
- c
.inactive_exit_usec
, USEC_PER_MSEC
));
1410 if (c
.cpu_usage_nsec
!= NSEC_INFINITY
)
1411 log_info("CPU time consumed: %s",
1412 FORMAT_TIMESPAN(DIV_ROUND_UP(c
.cpu_usage_nsec
, NSEC_PER_USEC
), USEC_PER_MSEC
));
1414 if (c
.ip_ingress_bytes
!= UINT64_MAX
)
1415 log_info("IP traffic received: %s", FORMAT_BYTES(c
.ip_ingress_bytes
));
1417 if (c
.ip_egress_bytes
!= UINT64_MAX
)
1418 log_info("IP traffic sent: %s", FORMAT_BYTES(c
.ip_egress_bytes
));
1420 if (c
.io_read_bytes
!= UINT64_MAX
)
1421 log_info("IO bytes read: %s", FORMAT_BYTES(c
.io_read_bytes
));
1423 if (c
.io_write_bytes
!= UINT64_MAX
)
1424 log_info("IO bytes written: %s", FORMAT_BYTES(c
.io_write_bytes
));
1427 /* Try to propagate the service's return value. But if the service defines
1428 * e.g. SuccessExitStatus, honour this, and return 0 to mean "success". */
1429 if (streq_ptr(c
.result
, "success"))
1430 return EXIT_SUCCESS
;
1431 if (streq_ptr(c
.result
, "exit-code") && c
.exit_status
> 0)
1432 return c
.exit_status
;
1433 if (streq_ptr(c
.result
, "signal"))
1434 return EXIT_EXCEPTION
;
1435 return EXIT_FAILURE
;
1438 return EXIT_SUCCESS
;
1441 static int acquire_invocation_id(sd_bus
*bus
, sd_id128_t
*ret
) {
1442 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1443 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1451 r
= sd_bus_get_property(bus
,
1452 "org.freedesktop.systemd1",
1453 "/org/freedesktop/systemd1/unit/self",
1454 "org.freedesktop.systemd1.Unit",
1460 return log_error_errno(r
, "Failed to request invocation ID for scope: %s", bus_error_message(&error
, r
));
1462 r
= sd_bus_message_read_array(reply
, 'y', &p
, &l
);
1464 return bus_log_parse_error(r
);
1466 if (l
!= sizeof(sd_id128_t
))
1467 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid UUID size, %zu != %zu.", l
, sizeof(sd_id128_t
));
1473 static int start_transient_scope(sd_bus
*bus
) {
1474 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1475 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1476 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1477 _cleanup_strv_free_
char **env
= NULL
, **user_env
= NULL
, **expanded_cmdline
= NULL
;
1478 _cleanup_free_
char *scope
= NULL
;
1479 const char *object
= NULL
;
1480 sd_id128_t invocation_id
;
1484 assert(!strv_isempty(arg_cmdline
));
1486 r
= bus_wait_for_jobs_new(bus
, &w
);
1491 r
= unit_name_mangle_with_suffix(arg_unit
, "as unit",
1492 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
1495 return log_error_errno(r
, "Failed to mangle scope name: %m");
1497 r
= make_unit_name(bus
, UNIT_SCOPE
, &scope
);
1502 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "StartTransientUnit");
1504 return bus_log_create_error(r
);
1506 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1508 return bus_log_create_error(r
);
1511 r
= sd_bus_message_append(m
, "ss", scope
, "fail");
1513 return bus_log_create_error(r
);
1516 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1518 return bus_log_create_error(r
);
1520 r
= transient_scope_set_properties(m
);
1524 r
= sd_bus_message_close_container(m
);
1526 return bus_log_create_error(r
);
1528 /* Auxiliary units */
1529 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1531 return bus_log_create_error(r
);
1533 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1535 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1537 return log_error_errno(r
, "Failed to start transient scope unit: %s", bus_error_message(&error
, r
));
1539 r
= sd_bus_message_read(reply
, "o", &object
);
1541 return bus_log_parse_error(r
);
1543 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
, arg_runtime_scope
== RUNTIME_SCOPE_USER
? STRV_MAKE_CONST("--user") : NULL
);
1547 r
= acquire_invocation_id(bus
, &invocation_id
);
1551 r
= strv_extendf(&user_env
, "INVOCATION_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(invocation_id
));
1556 if (setpriority(PRIO_PROCESS
, 0, arg_nice
) < 0)
1557 return log_error_errno(errno
, "Failed to set nice level: %m");
1560 if (arg_exec_group
) {
1563 r
= get_group_creds(&arg_exec_group
, &gid
, 0);
1565 return log_error_errno(r
, "Failed to resolve group %s: %m", arg_exec_group
);
1567 if (setresgid(gid
, gid
, gid
) < 0)
1568 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1571 if (arg_exec_user
) {
1572 const char *home
, *shell
;
1576 r
= get_user_creds(&arg_exec_user
, &uid
, &gid
, &home
, &shell
, USER_CREDS_CLEAN
|USER_CREDS_PREFER_NSS
);
1578 return log_error_errno(r
, "Failed to resolve user %s: %m", arg_exec_user
);
1581 r
= strv_extendf(&user_env
, "HOME=%s", home
);
1587 r
= strv_extendf(&user_env
, "SHELL=%s", shell
);
1592 r
= strv_extendf(&user_env
, "USER=%s", arg_exec_user
);
1596 r
= strv_extendf(&user_env
, "LOGNAME=%s", arg_exec_user
);
1600 if (!arg_exec_group
) {
1601 if (setresgid(gid
, gid
, gid
) < 0)
1602 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1605 if (setresuid(uid
, uid
, uid
) < 0)
1606 return log_error_errno(errno
, "Failed to change UID to " UID_FMT
": %m", uid
);
1609 if (arg_working_directory
&& chdir(arg_working_directory
) < 0)
1610 return log_error_errno(errno
, "Failed to change directory to '%s': %m", arg_working_directory
);
1612 env
= strv_env_merge(environ
, user_env
, arg_environment
);
1617 log_info("Running scope as unit: %s", scope
);
1619 if (arg_expand_environment
) {
1620 expanded_cmdline
= replace_env_argv(arg_cmdline
, env
);
1621 if (!expanded_cmdline
)
1623 arg_cmdline
= expanded_cmdline
;
1626 execvpe(arg_cmdline
[0], arg_cmdline
, env
);
1628 return log_error_errno(errno
, "Failed to execute: %m");
1631 static int make_transient_trigger_unit(
1633 sd_bus_message
**message
,
1635 const char *trigger
,
1636 const char *service
) {
1638 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
;
1647 r
= bus_message_new_method_call(bus
, &m
, bus_systemd_mgr
, "StartTransientUnit");
1649 return bus_log_create_error(r
);
1651 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1653 return bus_log_create_error(r
);
1656 r
= sd_bus_message_append(m
, "ss", trigger
, "fail");
1658 return bus_log_create_error(r
);
1661 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1663 return bus_log_create_error(r
);
1665 if (streq(suffix
, ".path"))
1666 r
= transient_unit_set_properties(m
, UNIT_PATH
, arg_path_property
);
1667 else if (streq(suffix
, ".socket"))
1668 r
= transient_unit_set_properties(m
, UNIT_SOCKET
, arg_socket_property
);
1669 else if (streq(suffix
, ".timer"))
1670 r
= transient_timer_set_properties(m
);
1672 assert_not_reached();
1676 r
= sd_bus_message_close_container(m
);
1678 return bus_log_create_error(r
);
1680 r
= sd_bus_message_open_container(m
, 'a', "(sa(sv))");
1682 return bus_log_create_error(r
);
1684 if (!strv_isempty(arg_cmdline
)) {
1685 r
= sd_bus_message_open_container(m
, 'r', "sa(sv)");
1687 return bus_log_create_error(r
);
1689 r
= sd_bus_message_append(m
, "s", service
);
1691 return bus_log_create_error(r
);
1693 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1695 return bus_log_create_error(r
);
1697 r
= transient_service_set_properties(m
, NULL
);
1701 r
= sd_bus_message_close_container(m
);
1703 return bus_log_create_error(r
);
1705 r
= sd_bus_message_close_container(m
);
1707 return bus_log_create_error(r
);
1710 r
= sd_bus_message_close_container(m
);
1712 return bus_log_create_error(r
);
1714 *message
= TAKE_PTR(m
);
1718 static int start_transient_trigger(sd_bus
*bus
, const char *suffix
) {
1719 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1720 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1721 _cleanup_free_
char *trigger
= NULL
, *service
= NULL
;
1722 const char *object
= NULL
;
1728 r
= bus_wait_for_jobs_new(bus
, &w
);
1733 switch (unit_name_to_type(arg_unit
)) {
1736 service
= strdup(arg_unit
);
1740 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1742 return log_error_errno(r
, "Failed to change unit suffix: %m");
1746 trigger
= strdup(arg_unit
);
1750 r
= unit_name_change_suffix(trigger
, ".service", &service
);
1752 return log_error_errno(r
, "Failed to change unit suffix: %m");
1756 r
= unit_name_mangle_with_suffix(arg_unit
, "as unit",
1757 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
1758 ".service", &service
);
1760 return log_error_errno(r
, "Failed to mangle unit name: %m");
1762 r
= unit_name_mangle_with_suffix(arg_unit
, "as trigger",
1763 arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
,
1766 return log_error_errno(r
, "Failed to mangle unit name: %m");
1771 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1775 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1777 return log_error_errno(r
, "Failed to change unit suffix: %m");
1780 r
= make_transient_trigger_unit(bus
, &m
, suffix
, trigger
, service
);
1784 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1786 r
= bus_call_with_hint(bus
, m
, suffix
+ 1, &reply
);
1790 r
= sd_bus_message_read(reply
, "o", &object
);
1792 return bus_log_parse_error(r
);
1794 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
, arg_runtime_scope
== RUNTIME_SCOPE_USER
? STRV_MAKE_CONST("--user") : NULL
);
1799 log_info("Running %s as unit: %s", suffix
+ 1, trigger
);
1800 if (!strv_isempty(arg_cmdline
))
1801 log_info("Will run service as unit: %s", service
);
1804 return EXIT_SUCCESS
;
1807 static bool shall_make_executable_absolute(void) {
1808 if (strv_isempty(arg_cmdline
))
1810 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
1813 FOREACH_STRING(f
, "RootDirectory=", "RootImage=", "ExecSearchPath=", "MountImages=", "ExtensionImages=")
1814 if (strv_find_startswith(arg_property
, f
))
1820 static int run(int argc
, char* argv
[]) {
1821 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
1822 _cleanup_free_
char *description
= NULL
;
1825 log_show_color(true);
1826 log_parse_environment();
1829 r
= parse_argv(argc
, argv
);
1833 if (shall_make_executable_absolute()) {
1834 /* Patch in an absolute path to fail early for user convenience, but only when we can do it
1835 * (i.e. we will be running from the same file system). This also uses the user's $PATH,
1836 * while we use a fixed search path in the manager. */
1838 _cleanup_free_
char *command
= NULL
;
1839 r
= find_executable(arg_cmdline
[0], &command
);
1841 return log_error_errno(r
, "Failed to find executable %s: %m", arg_cmdline
[0]);
1843 free_and_replace(arg_cmdline
[0], command
);
1846 if (!arg_description
) {
1847 description
= strv_join(arg_cmdline
, " ");
1851 if (arg_unit
&& isempty(description
)) {
1852 r
= free_and_strdup(&description
, arg_unit
);
1857 arg_description
= description
;
1860 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the limited direct
1862 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
|| (arg_runtime_scope
== RUNTIME_SCOPE_USER
&& arg_transport
!= BUS_TRANSPORT_LOCAL
))
1863 r
= bus_connect_transport(arg_transport
, arg_host
, arg_runtime_scope
, &bus
);
1865 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, arg_runtime_scope
, &bus
);
1867 return bus_log_connect_error(r
, arg_transport
);
1870 return start_transient_scope(bus
);
1871 if (arg_path_property
)
1872 return start_transient_trigger(bus
, ".path");
1873 if (arg_socket_property
)
1874 return start_transient_trigger(bus
, ".socket");
1876 return start_transient_trigger(bus
, ".timer");
1877 return start_transient_service(bus
);
1880 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);