1 /* SPDX-License-Identifier: LGPL-2.1+ */
9 #include "alloc-util.h"
10 #include "bus-error.h"
11 #include "bus-unit-util.h"
13 #include "calendarspec.h"
16 #include "format-util.h"
17 #include "main-func.h"
18 #include "parse-util.h"
19 #include "path-util.h"
20 #include "pretty-print.h"
21 #include "process-util.h"
23 #include "signal-util.h"
24 #include "spawn-polkit-agent.h"
26 #include "terminal-util.h"
28 #include "unit-name.h"
29 #include "user-util.h"
31 static bool arg_ask_password
= true;
32 static bool arg_scope
= false;
33 static bool arg_remain_after_exit
= false;
34 static bool arg_no_block
= false;
35 static bool arg_wait
= false;
36 static const char *arg_unit
= NULL
;
37 static const char *arg_description
= NULL
;
38 static const char *arg_slice
= NULL
;
39 static bool arg_send_sighup
= false;
40 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
41 static const char *arg_host
= NULL
;
42 static bool arg_user
= false;
43 static const char *arg_service_type
= NULL
;
44 static const char *arg_exec_user
= NULL
;
45 static const char *arg_exec_group
= NULL
;
46 static int arg_nice
= 0;
47 static bool arg_nice_set
= false;
48 static char **arg_environment
= NULL
;
49 static char **arg_property
= NULL
;
51 ARG_STDIO_NONE
, /* The default, as it is for normal services, stdin connected to /dev/null, and stdout+stderr to the journal */
52 ARG_STDIO_PTY
, /* Interactive behaviour, requested by --pty: we allocate a pty and connect it to the TTY we are invoked from */
53 ARG_STDIO_DIRECT
, /* Directly pass our stdin/stdout/stderr to the activated service, useful for usage in shell pipelines, requested by --pipe */
54 ARG_STDIO_AUTO
, /* If --pipe and --pty are used together we use --pty when invoked on a TTY, and --pipe otherwise */
55 } arg_stdio
= ARG_STDIO_NONE
;
56 static char **arg_path_property
= NULL
;
57 static char **arg_socket_property
= NULL
;
58 static char **arg_timer_property
= NULL
;
59 static bool with_timer
= false;
60 static bool arg_quiet
= false;
61 static bool arg_aggressive_gc
= false;
62 static char *arg_working_directory
= NULL
;
63 static bool arg_shell
= false;
64 static char **arg_cmdline
= NULL
;
66 STATIC_DESTRUCTOR_REGISTER(arg_environment
, strv_freep
);
67 STATIC_DESTRUCTOR_REGISTER(arg_property
, strv_freep
);
68 STATIC_DESTRUCTOR_REGISTER(arg_path_property
, strv_freep
);
69 STATIC_DESTRUCTOR_REGISTER(arg_socket_property
, strv_freep
);
70 STATIC_DESTRUCTOR_REGISTER(arg_timer_property
, strv_freep
);
71 STATIC_DESTRUCTOR_REGISTER(arg_working_directory
, freep
);
72 STATIC_DESTRUCTOR_REGISTER(arg_cmdline
, strv_freep
);
74 static int help(void) {
75 _cleanup_free_
char *link
= NULL
;
78 r
= terminal_urlify_man("systemd-run", "1", &link
);
82 printf("%s [OPTIONS...] {COMMAND} [ARGS...]\n\n"
83 "Run the specified command in a transient scope or service.\n\n"
84 " -h --help Show this help\n"
85 " --version Show package version\n"
86 " --no-ask-password Do not prompt for password\n"
87 " --user Run as user unit\n"
88 " -H --host=[USER@]HOST Operate on remote host\n"
89 " -M --machine=CONTAINER Operate on local container\n"
90 " --scope Run this as scope rather than service\n"
91 " --unit=UNIT Run under the specified unit name\n"
92 " -p --property=NAME=VALUE Set service or scope unit property\n"
93 " --description=TEXT Description for unit\n"
94 " --slice=SLICE Run in the specified slice\n"
95 " --no-block Do not wait until operation finished\n"
96 " -r --remain-after-exit Leave service around until explicitly stopped\n"
97 " --wait Wait until service stopped again\n"
98 " --send-sighup Send SIGHUP when terminating\n"
99 " --service-type=TYPE Service type\n"
100 " --uid=USER Run as system user\n"
101 " --gid=GROUP Run as system group\n"
102 " --nice=NICE Nice level\n"
103 " --working-directory=PATH Set working directory\n"
104 " -d --same-dir Inherit working directory from caller\n"
105 " -E --setenv=NAME=VALUE Set environment\n"
106 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
108 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
109 " -q --quiet Suppress information messages during runtime\n"
110 " -G --collect Unload unit after it ran, even when failed\n"
111 " -S --shell Invoke a $SHELL interactively\n\n"
113 " --path-property=NAME=VALUE Set path unit property\n\n"
115 " --socket-property=NAME=VALUE Set socket unit property\n\n"
117 " --on-active=SECONDS Run after SECONDS delay\n"
118 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
119 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
120 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
121 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
122 " --on-calendar=SPEC Realtime timer\n"
123 " --timer-property=NAME=VALUE Set timer unit property\n"
124 "\nSee the %s for details.\n"
125 , program_invocation_short_name
132 static int add_timer_property(const char *name
, const char *val
) {
138 p
= strjoin(name
, "=", val
);
142 if (strv_consume(&arg_timer_property
, p
) < 0)
148 static int parse_argv(int argc
, char *argv
[]) {
167 ARG_ON_UNIT_INACTIVE
,
175 ARG_WORKING_DIRECTORY
,
179 static const struct option options
[] = {
180 { "help", no_argument
, NULL
, 'h' },
181 { "version", no_argument
, NULL
, ARG_VERSION
},
182 { "user", no_argument
, NULL
, ARG_USER
},
183 { "system", no_argument
, NULL
, ARG_SYSTEM
},
184 { "scope", no_argument
, NULL
, ARG_SCOPE
},
185 { "unit", required_argument
, NULL
, ARG_UNIT
},
186 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
187 { "slice", required_argument
, NULL
, ARG_SLICE
},
188 { "remain-after-exit", no_argument
, NULL
, 'r' },
189 { "send-sighup", no_argument
, NULL
, ARG_SEND_SIGHUP
},
190 { "host", required_argument
, NULL
, 'H' },
191 { "machine", required_argument
, NULL
, 'M' },
192 { "service-type", required_argument
, NULL
, ARG_SERVICE_TYPE
},
193 { "wait", no_argument
, NULL
, ARG_WAIT
},
194 { "uid", required_argument
, NULL
, ARG_EXEC_USER
},
195 { "gid", required_argument
, NULL
, ARG_EXEC_GROUP
},
196 { "nice", required_argument
, NULL
, ARG_NICE
},
197 { "setenv", required_argument
, NULL
, 'E' },
198 { "property", required_argument
, NULL
, 'p' },
199 { "tty", no_argument
, NULL
, 't' }, /* deprecated alias */
200 { "pty", no_argument
, NULL
, 't' },
201 { "pipe", no_argument
, NULL
, 'P' },
202 { "quiet", no_argument
, NULL
, 'q' },
203 { "on-active", required_argument
, NULL
, ARG_ON_ACTIVE
},
204 { "on-boot", required_argument
, NULL
, ARG_ON_BOOT
},
205 { "on-startup", required_argument
, NULL
, ARG_ON_STARTUP
},
206 { "on-unit-active", required_argument
, NULL
, ARG_ON_UNIT_ACTIVE
},
207 { "on-unit-inactive", required_argument
, NULL
, ARG_ON_UNIT_INACTIVE
},
208 { "on-calendar", required_argument
, NULL
, ARG_ON_CALENDAR
},
209 { "timer-property", required_argument
, NULL
, ARG_TIMER_PROPERTY
},
210 { "path-property", required_argument
, NULL
, ARG_PATH_PROPERTY
},
211 { "socket-property", required_argument
, NULL
, ARG_SOCKET_PROPERTY
},
212 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
213 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
214 { "collect", no_argument
, NULL
, 'G' },
215 { "working-directory", required_argument
, NULL
, ARG_WORKING_DIRECTORY
},
216 { "same-dir", no_argument
, NULL
, 'd' },
217 { "shell", no_argument
, NULL
, 'S' },
221 bool with_trigger
= false;
227 while ((c
= getopt_long(argc
, argv
, "+hrH:M:E:p:tPqGdS", options
, NULL
)) >= 0)
237 case ARG_NO_ASK_PASSWORD
:
238 arg_ask_password
= false;
257 case ARG_DESCRIPTION
:
258 arg_description
= optarg
;
265 case ARG_SEND_SIGHUP
:
266 arg_send_sighup
= true;
270 arg_remain_after_exit
= true;
274 arg_transport
= BUS_TRANSPORT_REMOTE
;
279 arg_transport
= BUS_TRANSPORT_MACHINE
;
283 case ARG_SERVICE_TYPE
:
284 arg_service_type
= optarg
;
288 arg_exec_user
= optarg
;
292 arg_exec_group
= optarg
;
296 r
= parse_nice(optarg
, &arg_nice
);
298 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
304 if (strv_extend(&arg_environment
, optarg
) < 0)
310 if (strv_extend(&arg_property
, optarg
) < 0)
315 case 't': /* --pty */
316 if (IN_SET(arg_stdio
, ARG_STDIO_DIRECT
, ARG_STDIO_AUTO
)) /* if --pipe is already used, upgrade to auto mode */
317 arg_stdio
= ARG_STDIO_AUTO
;
319 arg_stdio
= ARG_STDIO_PTY
;
322 case 'P': /* --pipe */
323 if (IN_SET(arg_stdio
, ARG_STDIO_PTY
, ARG_STDIO_AUTO
)) /* If --pty is already used, upgrade to auto mode */
324 arg_stdio
= ARG_STDIO_AUTO
;
326 arg_stdio
= ARG_STDIO_DIRECT
;
334 r
= add_timer_property("OnActiveSec", optarg
);
342 r
= add_timer_property("OnBootSec", optarg
);
350 r
= add_timer_property("OnStartupSec", optarg
);
357 case ARG_ON_UNIT_ACTIVE
:
358 r
= add_timer_property("OnUnitActiveSec", optarg
);
365 case ARG_ON_UNIT_INACTIVE
:
366 r
= add_timer_property("OnUnitInactiveSec", optarg
);
373 case ARG_ON_CALENDAR
:
374 r
= add_timer_property("OnCalendar", optarg
);
381 case ARG_TIMER_PROPERTY
:
383 if (strv_extend(&arg_timer_property
, optarg
) < 0)
386 with_timer
= with_timer
||
387 STARTSWITH_SET(optarg
,
392 "OnUnitInactiveSec=",
396 case ARG_PATH_PROPERTY
:
398 if (strv_extend(&arg_path_property
, optarg
) < 0)
403 case ARG_SOCKET_PROPERTY
:
405 if (strv_extend(&arg_socket_property
, optarg
) < 0)
418 case ARG_WORKING_DIRECTORY
:
419 r
= parse_path_argument_and_warn(optarg
, true, &arg_working_directory
);
426 _cleanup_free_
char *p
= NULL
;
430 return log_error_errno(r
, "Failed to get current working directory: %m");
432 if (empty_or_root(p
))
433 arg_working_directory
= mfree(arg_working_directory
);
435 free_and_replace(arg_working_directory
, p
);
440 arg_aggressive_gc
= true;
451 assert_not_reached("Unhandled option");
454 with_trigger
= !!arg_path_property
|| !!arg_socket_property
|| with_timer
;
456 /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
457 if ((int) !!arg_path_property
+ (int) !!arg_socket_property
+ (int) with_timer
> 1)
458 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
459 "Only single trigger (path, socket, timer) unit can be created.");
462 /* If --shell is imply --pty --pipe --same-dir --service-type=exec --wait --collect, unless otherwise
466 if (arg_stdio
== ARG_STDIO_NONE
)
467 arg_stdio
= ARG_STDIO_AUTO
;
469 if (!arg_working_directory
) {
470 r
= safe_getcwd(&arg_working_directory
);
472 return log_error_errno(r
, "Failed to get current working directory: %m");
475 if (!arg_service_type
) {
476 arg_service_type
= strdup("exec");
477 if (!arg_service_type
)
484 arg_aggressive_gc
= true;
487 if (arg_stdio
== ARG_STDIO_AUTO
) {
488 /* If we both --pty and --pipe are specified we'll automatically pick --pty if we are connected fully
489 * to a TTY and pick direct fd passing otherwise. This way, we automatically adapt to usage in a shell
490 * pipeline, but we are neatly interactive with tty-level isolation otherwise. */
491 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ?
500 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "If --shell is used, no command line is expected.");
502 l
= strv_copy(argv
+ optind
);
506 strv_free_and_replace(arg_cmdline
, l
);
508 } else if (arg_shell
) {
509 _cleanup_free_
char *s
= NULL
;
514 return log_error_errno(r
, "Failed to determine shell: %m");
520 strv_free_and_replace(arg_cmdline
, l
);
522 } else if (!arg_unit
|| !with_trigger
)
523 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Command line to execute required.");
525 if (arg_user
&& arg_transport
!= BUS_TRANSPORT_LOCAL
)
526 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
527 "Execution in user context is not supported on non-local systems.");
529 if (arg_scope
&& arg_transport
!= BUS_TRANSPORT_LOCAL
)
530 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
531 "Scope execution is not supported on non-local systems.");
533 if (arg_scope
&& (arg_remain_after_exit
|| arg_service_type
))
534 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
535 "--remain-after-exit and --service-type= are not supported in --scope mode.");
537 if (arg_stdio
!= ARG_STDIO_NONE
&& (with_trigger
|| arg_scope
))
538 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
539 "--pty/--pipe is not compatible in timer or --scope mode.");
541 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_transport
== BUS_TRANSPORT_REMOTE
)
542 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
543 "--pty/--pipe is only supported when connecting to the local system or containers.");
545 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_no_block
)
546 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
547 "--pty/--pipe is not compatible with --no-block.");
549 if (arg_scope
&& with_trigger
)
550 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
551 "Path, socket or timer options are not supported in --scope mode.");
553 if (arg_timer_property
&& !with_timer
)
554 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
555 "--timer-property= has no effect without any other timer options.");
559 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
560 "--wait may not be combined with --no-block.");
563 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
564 "--wait may not be combined with path, socket or timer operations.");
567 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
568 "--wait may not be combined with --scope.");
574 static int transient_unit_set_properties(sd_bus_message
*m
, UnitType t
, char **properties
) {
577 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", arg_description
);
579 return bus_log_create_error(r
);
581 if (arg_aggressive_gc
) {
582 r
= sd_bus_message_append(m
, "(sv)", "CollectMode", "s", "inactive-or-failed");
584 return bus_log_create_error(r
);
587 r
= bus_append_unit_property_assignment_many(m
, t
, properties
);
594 static int transient_cgroup_set_properties(sd_bus_message
*m
) {
598 if (!isempty(arg_slice
)) {
599 _cleanup_free_
char *slice
= NULL
;
601 r
= unit_name_mangle_with_suffix(arg_slice
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".slice", &slice
);
603 return log_error_errno(r
, "Failed to mangle name '%s': %m", arg_slice
);
605 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", slice
);
607 return bus_log_create_error(r
);
613 static int transient_kill_set_properties(sd_bus_message
*m
) {
618 if (arg_send_sighup
) {
619 r
= sd_bus_message_append(m
, "(sv)", "SendSIGHUP", "b", arg_send_sighup
);
621 return bus_log_create_error(r
);
627 static int transient_service_set_properties(sd_bus_message
*m
, const char *pty_path
) {
628 bool send_term
= false;
633 r
= transient_unit_set_properties(m
, UNIT_SERVICE
, arg_property
);
637 r
= transient_kill_set_properties(m
);
641 r
= transient_cgroup_set_properties(m
);
645 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
646 r
= sd_bus_message_append(m
, "(sv)", "AddRef", "b", 1);
648 return bus_log_create_error(r
);
651 if (arg_remain_after_exit
) {
652 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit
);
654 return bus_log_create_error(r
);
657 if (arg_service_type
) {
658 r
= sd_bus_message_append(m
, "(sv)", "Type", "s", arg_service_type
);
660 return bus_log_create_error(r
);
664 r
= sd_bus_message_append(m
, "(sv)", "User", "s", arg_exec_user
);
666 return bus_log_create_error(r
);
669 if (arg_exec_group
) {
670 r
= sd_bus_message_append(m
, "(sv)", "Group", "s", arg_exec_group
);
672 return bus_log_create_error(r
);
676 r
= sd_bus_message_append(m
, "(sv)", "Nice", "i", arg_nice
);
678 return bus_log_create_error(r
);
681 if (arg_working_directory
) {
682 r
= sd_bus_message_append(m
, "(sv)", "WorkingDirectory", "s", arg_working_directory
);
684 return bus_log_create_error(r
);
688 r
= sd_bus_message_append(m
,
690 "StandardInput", "s", "tty",
691 "StandardOutput", "s", "tty",
692 "StandardError", "s", "tty",
693 "TTYPath", "s", pty_path
);
695 return bus_log_create_error(r
);
699 } else if (arg_stdio
== ARG_STDIO_DIRECT
) {
700 r
= sd_bus_message_append(m
,
702 "StandardInputFileDescriptor", "h", STDIN_FILENO
,
703 "StandardOutputFileDescriptor", "h", STDOUT_FILENO
,
704 "StandardErrorFileDescriptor", "h", STDERR_FILENO
);
706 return bus_log_create_error(r
);
708 send_term
= isatty(STDIN_FILENO
) || isatty(STDOUT_FILENO
) || isatty(STDERR_FILENO
);
718 n
= strjoina("TERM=", e
);
719 r
= sd_bus_message_append(m
,
721 "Environment", "as", 1, n
);
723 return bus_log_create_error(r
);
727 if (!strv_isempty(arg_environment
)) {
728 r
= sd_bus_message_open_container(m
, 'r', "sv");
730 return bus_log_create_error(r
);
732 r
= sd_bus_message_append(m
, "s", "Environment");
734 return bus_log_create_error(r
);
736 r
= sd_bus_message_open_container(m
, 'v', "as");
738 return bus_log_create_error(r
);
740 r
= sd_bus_message_append_strv(m
, arg_environment
);
742 return bus_log_create_error(r
);
744 r
= sd_bus_message_close_container(m
);
746 return bus_log_create_error(r
);
748 r
= sd_bus_message_close_container(m
);
750 return bus_log_create_error(r
);
754 if (!strv_isempty(arg_cmdline
)) {
755 r
= sd_bus_message_open_container(m
, 'r', "sv");
757 return bus_log_create_error(r
);
759 r
= sd_bus_message_append(m
, "s", "ExecStart");
761 return bus_log_create_error(r
);
763 r
= sd_bus_message_open_container(m
, 'v', "a(sasb)");
765 return bus_log_create_error(r
);
767 r
= sd_bus_message_open_container(m
, 'a', "(sasb)");
769 return bus_log_create_error(r
);
771 r
= sd_bus_message_open_container(m
, 'r', "sasb");
773 return bus_log_create_error(r
);
775 r
= sd_bus_message_append(m
, "s", arg_cmdline
[0]);
777 return bus_log_create_error(r
);
779 r
= sd_bus_message_append_strv(m
, arg_cmdline
);
781 return bus_log_create_error(r
);
783 r
= sd_bus_message_append(m
, "b", false);
785 return bus_log_create_error(r
);
787 r
= sd_bus_message_close_container(m
);
789 return bus_log_create_error(r
);
791 r
= sd_bus_message_close_container(m
);
793 return bus_log_create_error(r
);
795 r
= sd_bus_message_close_container(m
);
797 return bus_log_create_error(r
);
799 r
= sd_bus_message_close_container(m
);
801 return bus_log_create_error(r
);
807 static int transient_scope_set_properties(sd_bus_message
*m
) {
812 r
= transient_unit_set_properties(m
, UNIT_SCOPE
, arg_property
);
816 r
= transient_kill_set_properties(m
);
820 r
= transient_cgroup_set_properties(m
);
824 r
= sd_bus_message_append(m
, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached());
826 return bus_log_create_error(r
);
831 static int transient_timer_set_properties(sd_bus_message
*m
) {
836 r
= transient_unit_set_properties(m
, UNIT_TIMER
, arg_timer_property
);
840 /* Automatically clean up our transient timers */
841 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterElapse", "b", false);
843 return bus_log_create_error(r
);
848 static int make_unit_name(sd_bus
*bus
, UnitType t
, char **ret
) {
849 const char *unique
, *id
;
855 assert(t
< _UNIT_TYPE_MAX
);
857 r
= sd_bus_get_unique_name(bus
, &unique
);
861 /* We couldn't get the unique name, which is a pretty
862 * common case if we are connected to systemd
863 * directly. In that case, just pick a random uuid as
866 r
= sd_id128_randomize(&rnd
);
868 return log_error_errno(r
, "Failed to generate random run unit name: %m");
870 if (asprintf(ret
, "run-r" SD_ID128_FORMAT_STR
".%s", SD_ID128_FORMAT_VAL(rnd
), unit_type_to_string(t
)) < 0)
876 /* We managed to get the unique name, then let's use that to
877 * name our transient units. */
879 id
= startswith(unique
, ":1.");
881 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
),
882 "Unique name %s has unexpected format.",
885 p
= strjoin("run-u", id
, ".", unit_type_to_string(t
));
893 typedef struct RunContext
{
899 /* The exit data of the unit */
901 uint64_t inactive_exit_usec
;
902 uint64_t inactive_enter_usec
;
904 uint64_t cpu_usage_nsec
;
905 uint64_t ip_ingress_bytes
;
906 uint64_t ip_egress_bytes
;
908 uint32_t exit_status
;
911 static void run_context_free(RunContext
*c
) {
914 c
->forward
= pty_forward_free(c
->forward
);
915 c
->match
= sd_bus_slot_unref(c
->match
);
916 c
->bus
= sd_bus_unref(c
->bus
);
917 c
->event
= sd_event_unref(c
->event
);
919 free(c
->active_state
);
923 static void run_context_check_done(RunContext
*c
) {
929 done
= STRPTR_IN_SET(c
->active_state
, "inactive", "failed");
933 if (c
->forward
&& done
) /* If the service is gone, it's time to drain the output */
934 done
= pty_forward_drain(c
->forward
);
937 sd_event_exit(c
->event
, EXIT_SUCCESS
);
940 static int run_context_update(RunContext
*c
, const char *path
) {
942 static const struct bus_properties_map map
[] = {
943 { "ActiveState", "s", NULL
, offsetof(RunContext
, active_state
) },
944 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_exit_usec
) },
945 { "InactiveEnterTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_enter_usec
) },
946 { "Result", "s", NULL
, offsetof(RunContext
, result
) },
947 { "ExecMainCode", "i", NULL
, offsetof(RunContext
, exit_code
) },
948 { "ExecMainStatus", "i", NULL
, offsetof(RunContext
, exit_status
) },
949 { "CPUUsageNSec", "t", NULL
, offsetof(RunContext
, cpu_usage_nsec
) },
950 { "IPIngressBytes", "t", NULL
, offsetof(RunContext
, ip_ingress_bytes
) },
951 { "IPEgressBytes", "t", NULL
, offsetof(RunContext
, ip_egress_bytes
) },
955 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
958 r
= bus_map_all_properties(c
->bus
,
959 "org.freedesktop.systemd1",
967 sd_event_exit(c
->event
, EXIT_FAILURE
);
968 return log_error_errno(r
, "Failed to query unit state: %s", bus_error_message(&error
, r
));
971 run_context_check_done(c
);
975 static int on_properties_changed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
976 RunContext
*c
= userdata
;
981 return run_context_update(c
, sd_bus_message_get_path(m
));
984 static int pty_forward_handler(PTYForward
*f
, int rcode
, void *userdata
) {
985 RunContext
*c
= userdata
;
990 sd_event_exit(c
->event
, EXIT_FAILURE
);
991 return log_error_errno(rcode
, "Error on PTY forwarding logic: %m");
994 run_context_check_done(c
);
998 static int start_transient_service(
1002 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1003 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1004 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1005 _cleanup_free_
char *service
= NULL
, *pty_path
= NULL
;
1006 _cleanup_close_
int master
= -1;
1012 if (arg_stdio
== ARG_STDIO_PTY
) {
1014 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
1015 master
= posix_openpt(O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
1017 return log_error_errno(errno
, "Failed to acquire pseudo tty: %m");
1019 r
= ptsname_malloc(master
, &pty_path
);
1021 return log_error_errno(r
, "Failed to determine tty name: %m");
1023 if (unlockpt(master
) < 0)
1024 return log_error_errno(errno
, "Failed to unlock tty: %m");
1026 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
1027 _cleanup_(sd_bus_unrefp
) sd_bus
*system_bus
= NULL
;
1028 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pty_reply
= NULL
;
1031 r
= sd_bus_default_system(&system_bus
);
1033 return log_error_errno(r
, "Failed to connect to system bus: %m");
1035 r
= sd_bus_call_method(system_bus
,
1036 "org.freedesktop.machine1",
1037 "/org/freedesktop/machine1",
1038 "org.freedesktop.machine1.Manager",
1044 return log_error_errno(r
, "Failed to get machine PTY: %s", bus_error_message(&error
, -r
));
1046 r
= sd_bus_message_read(pty_reply
, "hs", &master
, &s
);
1048 return bus_log_parse_error(r
);
1050 master
= fcntl(master
, F_DUPFD_CLOEXEC
, 3);
1052 return log_error_errno(errno
, "Failed to duplicate master fd: %m");
1054 pty_path
= strdup(s
);
1058 assert_not_reached("Can't allocate tty via ssh");
1061 if (!arg_no_block
) {
1062 r
= bus_wait_for_jobs_new(bus
, &w
);
1064 return log_error_errno(r
, "Could not watch jobs: %m");
1068 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".service", &service
);
1070 return log_error_errno(r
, "Failed to mangle unit name: %m");
1072 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1077 r
= sd_bus_message_new_method_call(
1080 "org.freedesktop.systemd1",
1081 "/org/freedesktop/systemd1",
1082 "org.freedesktop.systemd1.Manager",
1083 "StartTransientUnit");
1085 return bus_log_create_error(r
);
1087 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1089 return bus_log_create_error(r
);
1092 r
= sd_bus_message_append(m
, "ss", service
, "fail");
1094 return bus_log_create_error(r
);
1097 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1099 return bus_log_create_error(r
);
1101 r
= transient_service_set_properties(m
, pty_path
);
1105 r
= sd_bus_message_close_container(m
);
1107 return bus_log_create_error(r
);
1109 /* Auxiliary units */
1110 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1112 return bus_log_create_error(r
);
1114 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1116 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1118 return log_error_errno(r
, "Failed to start transient service unit: %s", bus_error_message(&error
, r
));
1123 r
= sd_bus_message_read(reply
, "o", &object
);
1125 return bus_log_parse_error(r
);
1127 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1133 log_info("Running as unit: %s", service
);
1135 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
1136 _cleanup_(run_context_free
) RunContext c
= {
1137 .cpu_usage_nsec
= NSEC_INFINITY
,
1138 .ip_ingress_bytes
= UINT64_MAX
,
1139 .ip_egress_bytes
= UINT64_MAX
,
1140 .inactive_exit_usec
= USEC_INFINITY
,
1141 .inactive_enter_usec
= USEC_INFINITY
,
1143 _cleanup_free_
char *path
= NULL
;
1145 c
.bus
= sd_bus_ref(bus
);
1147 r
= sd_event_default(&c
.event
);
1149 return log_error_errno(r
, "Failed to get event loop: %m");
1152 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
1153 (void) sd_event_add_signal(c
.event
, NULL
, SIGINT
, NULL
, NULL
);
1154 (void) sd_event_add_signal(c
.event
, NULL
, SIGTERM
, NULL
, NULL
);
1157 log_info("Press ^] three times within 1s to disconnect TTY.");
1159 r
= pty_forward_new(c
.event
, master
, PTY_FORWARD_IGNORE_INITIAL_VHANGUP
, &c
.forward
);
1161 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
1163 pty_forward_set_handler(c
.forward
, pty_forward_handler
, &c
);
1165 /* Make sure to process any TTY events before we process bus events */
1166 (void) pty_forward_set_priority(c
.forward
, SD_EVENT_PRIORITY_IMPORTANT
);
1169 path
= unit_dbus_path_from_name(service
);
1173 r
= sd_bus_match_signal_async(
1176 "org.freedesktop.systemd1",
1178 "org.freedesktop.DBus.Properties",
1179 "PropertiesChanged",
1180 on_properties_changed
, NULL
, &c
);
1182 return log_error_errno(r
, "Failed to request properties changed signal match: %m");
1184 r
= sd_bus_attach_event(bus
, c
.event
, SD_EVENT_PRIORITY_NORMAL
);
1186 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1188 r
= run_context_update(&c
, path
);
1192 r
= sd_event_loop(c
.event
);
1194 return log_error_errno(r
, "Failed to run event loop: %m");
1199 r
= pty_forward_get_last_char(c
.forward
, &last_char
);
1200 if (r
>= 0 && !arg_quiet
&& last_char
!= '\n')
1201 fputc('\n', stdout
);
1204 if (arg_wait
&& !arg_quiet
) {
1206 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, in its
1207 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1209 c
.forward
= pty_forward_free(c
.forward
);
1211 if (!isempty(c
.result
))
1212 log_info("Finished with result: %s", strna(c
.result
));
1214 if (c
.exit_code
== CLD_EXITED
)
1215 log_info("Main processes terminated with: code=%s/status=%i", sigchld_code_to_string(c
.exit_code
), c
.exit_status
);
1216 else if (c
.exit_code
> 0)
1217 log_info("Main processes terminated with: code=%s/status=%s", sigchld_code_to_string(c
.exit_code
), signal_to_string(c
.exit_status
));
1219 if (c
.inactive_enter_usec
> 0 && c
.inactive_enter_usec
!= USEC_INFINITY
&&
1220 c
.inactive_exit_usec
> 0 && c
.inactive_exit_usec
!= USEC_INFINITY
&&
1221 c
.inactive_enter_usec
> c
.inactive_exit_usec
) {
1222 char ts
[FORMAT_TIMESPAN_MAX
];
1223 log_info("Service runtime: %s", format_timespan(ts
, sizeof(ts
), c
.inactive_enter_usec
- c
.inactive_exit_usec
, USEC_PER_MSEC
));
1226 if (c
.cpu_usage_nsec
!= NSEC_INFINITY
) {
1227 char ts
[FORMAT_TIMESPAN_MAX
];
1228 log_info("CPU time consumed: %s", format_timespan(ts
, sizeof(ts
), (c
.cpu_usage_nsec
+ NSEC_PER_USEC
- 1) / NSEC_PER_USEC
, USEC_PER_MSEC
));
1231 if (c
.ip_ingress_bytes
!= UINT64_MAX
) {
1232 char bytes
[FORMAT_BYTES_MAX
];
1233 log_info("IP traffic received: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_ingress_bytes
));
1235 if (c
.ip_egress_bytes
!= UINT64_MAX
) {
1236 char bytes
[FORMAT_BYTES_MAX
];
1237 log_info("IP traffic sent: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_egress_bytes
));
1241 /* Try to propagate the service's return value */
1242 if (c
.result
&& STR_IN_SET(c
.result
, "success", "exit-code") && c
.exit_code
== CLD_EXITED
)
1243 *retval
= c
.exit_status
;
1245 *retval
= EXIT_FAILURE
;
1251 static int acquire_invocation_id(sd_bus
*bus
, sd_id128_t
*ret
) {
1252 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1253 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*reply
= NULL
;
1261 r
= sd_bus_get_property(bus
,
1262 "org.freedesktop.systemd1",
1263 "/org/freedesktop/systemd1/unit/self",
1264 "org.freedesktop.systemd1.Unit",
1270 return log_error_errno(r
, "Failed to request invocation ID for scope: %s", bus_error_message(&error
, r
));
1272 r
= sd_bus_message_read_array(reply
, 'y', &p
, &l
);
1274 return bus_log_parse_error(r
);
1276 if (l
!= sizeof(sd_id128_t
))
1277 return log_error_errno(SYNTHETIC_ERRNO(EINVAL
), "Invalid UUID size, %zu != %zu.", l
, sizeof(sd_id128_t
));
1283 static int start_transient_scope(sd_bus
*bus
) {
1284 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1285 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1286 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1287 _cleanup_strv_free_
char **env
= NULL
, **user_env
= NULL
;
1288 _cleanup_free_
char *scope
= NULL
;
1289 const char *object
= NULL
;
1290 sd_id128_t invocation_id
;
1294 assert(!strv_isempty(arg_cmdline
));
1296 r
= bus_wait_for_jobs_new(bus
, &w
);
1301 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".scope", &scope
);
1303 return log_error_errno(r
, "Failed to mangle scope name: %m");
1305 r
= make_unit_name(bus
, UNIT_SCOPE
, &scope
);
1310 r
= sd_bus_message_new_method_call(
1313 "org.freedesktop.systemd1",
1314 "/org/freedesktop/systemd1",
1315 "org.freedesktop.systemd1.Manager",
1316 "StartTransientUnit");
1318 return bus_log_create_error(r
);
1320 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1322 return bus_log_create_error(r
);
1325 r
= sd_bus_message_append(m
, "ss", scope
, "fail");
1327 return bus_log_create_error(r
);
1330 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1332 return bus_log_create_error(r
);
1334 r
= transient_scope_set_properties(m
);
1338 r
= sd_bus_message_close_container(m
);
1340 return bus_log_create_error(r
);
1342 /* Auxiliary units */
1343 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1345 return bus_log_create_error(r
);
1347 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1349 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1351 return log_error_errno(r
, "Failed to start transient scope unit: %s", bus_error_message(&error
, -r
));
1353 r
= sd_bus_message_read(reply
, "o", &object
);
1355 return bus_log_parse_error(r
);
1357 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1361 r
= acquire_invocation_id(bus
, &invocation_id
);
1365 r
= strv_extendf(&user_env
, "INVOCATION_ID=" SD_ID128_FORMAT_STR
, SD_ID128_FORMAT_VAL(invocation_id
));
1370 if (setpriority(PRIO_PROCESS
, 0, arg_nice
) < 0)
1371 return log_error_errno(errno
, "Failed to set nice level: %m");
1374 if (arg_exec_group
) {
1377 r
= get_group_creds(&arg_exec_group
, &gid
, 0);
1379 return log_error_errno(r
, "Failed to resolve group %s: %m", arg_exec_group
);
1381 if (setresgid(gid
, gid
, gid
) < 0)
1382 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1385 if (arg_exec_user
) {
1386 const char *home
, *shell
;
1390 r
= get_user_creds(&arg_exec_user
, &uid
, &gid
, &home
, &shell
, USER_CREDS_CLEAN
|USER_CREDS_PREFER_NSS
);
1392 return log_error_errno(r
, "Failed to resolve user %s: %m", arg_exec_user
);
1395 r
= strv_extendf(&user_env
, "HOME=%s", home
);
1401 r
= strv_extendf(&user_env
, "SHELL=%s", shell
);
1406 r
= strv_extendf(&user_env
, "USER=%s", arg_exec_user
);
1410 r
= strv_extendf(&user_env
, "LOGNAME=%s", arg_exec_user
);
1414 if (!arg_exec_group
) {
1415 if (setresgid(gid
, gid
, gid
) < 0)
1416 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1419 if (setresuid(uid
, uid
, uid
) < 0)
1420 return log_error_errno(errno
, "Failed to change UID to " UID_FMT
": %m", uid
);
1423 env
= strv_env_merge(3, environ
, user_env
, arg_environment
);
1428 log_info("Running scope as unit: %s", scope
);
1430 execvpe(arg_cmdline
[0], arg_cmdline
, env
);
1432 return log_error_errno(errno
, "Failed to execute: %m");
1435 static int start_transient_trigger(
1437 const char *suffix
) {
1439 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1440 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1441 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1442 _cleanup_free_
char *trigger
= NULL
, *service
= NULL
;
1443 const char *object
= NULL
;
1448 r
= bus_wait_for_jobs_new(bus
, &w
);
1453 switch (unit_name_to_type(arg_unit
)) {
1456 service
= strdup(arg_unit
);
1460 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1462 return log_error_errno(r
, "Failed to change unit suffix: %m");
1466 trigger
= strdup(arg_unit
);
1470 r
= unit_name_change_suffix(trigger
, ".service", &service
);
1472 return log_error_errno(r
, "Failed to change unit suffix: %m");
1476 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".service", &service
);
1478 return log_error_errno(r
, "Failed to mangle unit name: %m");
1480 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, suffix
, &trigger
);
1482 return log_error_errno(r
, "Failed to mangle unit name: %m");
1487 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1491 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1493 return log_error_errno(r
, "Failed to change unit suffix: %m");
1496 r
= sd_bus_message_new_method_call(
1499 "org.freedesktop.systemd1",
1500 "/org/freedesktop/systemd1",
1501 "org.freedesktop.systemd1.Manager",
1502 "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", trigger
, "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 if (streq(suffix
, ".path"))
1521 r
= transient_unit_set_properties(m
, UNIT_PATH
, arg_path_property
);
1522 else if (streq(suffix
, ".socket"))
1523 r
= transient_unit_set_properties(m
, UNIT_SOCKET
, arg_socket_property
);
1524 else if (streq(suffix
, ".timer"))
1525 r
= transient_timer_set_properties(m
);
1527 assert_not_reached("Invalid suffix");
1531 r
= sd_bus_message_close_container(m
);
1533 return bus_log_create_error(r
);
1535 r
= sd_bus_message_open_container(m
, 'a', "(sa(sv))");
1537 return bus_log_create_error(r
);
1539 if (!strv_isempty(arg_cmdline
)) {
1540 r
= sd_bus_message_open_container(m
, 'r', "sa(sv)");
1542 return bus_log_create_error(r
);
1544 r
= sd_bus_message_append(m
, "s", service
);
1546 return bus_log_create_error(r
);
1548 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1550 return bus_log_create_error(r
);
1552 r
= transient_service_set_properties(m
, NULL
);
1556 r
= sd_bus_message_close_container(m
);
1558 return bus_log_create_error(r
);
1560 r
= sd_bus_message_close_container(m
);
1562 return bus_log_create_error(r
);
1565 r
= sd_bus_message_close_container(m
);
1567 return bus_log_create_error(r
);
1569 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1571 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1573 return log_error_errno(r
, "Failed to start transient %s unit: %s", suffix
+ 1, bus_error_message(&error
, -r
));
1575 r
= sd_bus_message_read(reply
, "o", &object
);
1577 return bus_log_parse_error(r
);
1579 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1584 log_info("Running %s as unit: %s", suffix
+ 1, trigger
);
1585 if (!strv_isempty(arg_cmdline
))
1586 log_info("Will run service as unit: %s", service
);
1592 static int run(int argc
, char* argv
[]) {
1593 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
1594 _cleanup_free_
char *description
= NULL
;
1595 int r
, retval
= EXIT_SUCCESS
;
1597 log_parse_environment();
1600 r
= parse_argv(argc
, argv
);
1604 if (!strv_isempty(arg_cmdline
) && arg_transport
== BUS_TRANSPORT_LOCAL
) {
1605 _cleanup_free_
char *command
= NULL
;
1607 /* Patch in an absolute path */
1609 r
= find_binary(arg_cmdline
[0], &command
);
1611 return log_error_errno(r
, "Failed to find executable %s: %m", arg_cmdline
[0]);
1613 free_and_replace(arg_cmdline
[0], command
);
1616 if (!arg_description
) {
1617 description
= strv_join(arg_cmdline
, " ");
1621 if (arg_unit
&& isempty(description
)) {
1622 r
= free_and_strdup(&description
, arg_unit
);
1627 arg_description
= description
;
1630 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the limited direct
1632 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
)
1633 r
= bus_connect_transport(arg_transport
, arg_host
, arg_user
, &bus
);
1635 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, arg_user
, &bus
);
1637 return log_error_errno(r
, "Failed to create bus connection: %m");
1640 r
= start_transient_scope(bus
);
1641 else if (arg_path_property
)
1642 r
= start_transient_trigger(bus
, ".path");
1643 else if (arg_socket_property
)
1644 r
= start_transient_trigger(bus
, ".socket");
1645 else if (with_timer
)
1646 r
= start_transient_trigger(bus
, ".timer");
1648 r
= start_transient_service(bus
, &retval
);
1655 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run
);