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 "parse-util.h"
18 #include "path-util.h"
19 #include "process-util.h"
21 #include "signal-util.h"
22 #include "spawn-polkit-agent.h"
24 #include "terminal-util.h"
26 #include "unit-name.h"
27 #include "user-util.h"
29 static bool arg_ask_password
= true;
30 static bool arg_scope
= false;
31 static bool arg_remain_after_exit
= false;
32 static bool arg_no_block
= false;
33 static bool arg_wait
= false;
34 static const char *arg_unit
= NULL
;
35 static const char *arg_description
= NULL
;
36 static const char *arg_slice
= NULL
;
37 static bool arg_send_sighup
= false;
38 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
39 static const char *arg_host
= NULL
;
40 static bool arg_user
= false;
41 static const char *arg_service_type
= NULL
;
42 static const char *arg_exec_user
= NULL
;
43 static const char *arg_exec_group
= NULL
;
44 static int arg_nice
= 0;
45 static bool arg_nice_set
= false;
46 static char **arg_environment
= NULL
;
47 static char **arg_property
= NULL
;
49 ARG_STDIO_NONE
, /* The default, as it is for normal services, stdin connected to /dev/null, and stdout+stderr to the journal */
50 ARG_STDIO_PTY
, /* Interactive behaviour, requested by --pty: we allocate a pty and connect it to the TTY we are invoked from */
51 ARG_STDIO_DIRECT
, /* Directly pass our stdin/stdout/stderr to the activated service, useful for usage in shell pipelines, requested by --pipe */
52 ARG_STDIO_AUTO
, /* If --pipe and --pty are used together we use --pty when invoked on a TTY, and --pipe otherwise */
53 } arg_stdio
= ARG_STDIO_NONE
;
54 static char **arg_path_property
= NULL
;
55 static char **arg_socket_property
= NULL
;
56 static char **arg_timer_property
= NULL
;
57 static bool with_timer
= false;
58 static bool arg_quiet
= false;
59 static bool arg_aggressive_gc
= false;
61 static void help(void) {
62 printf("%s [OPTIONS...] {COMMAND} [ARGS...]\n\n"
63 "Run the specified command in a transient scope or service.\n\n"
64 " -h --help Show this help\n"
65 " --version Show package version\n"
66 " --no-ask-password Do not prompt for password\n"
67 " --user Run as user unit\n"
68 " -H --host=[USER@]HOST Operate on remote host\n"
69 " -M --machine=CONTAINER Operate on local container\n"
70 " --scope Run this as scope rather than service\n"
71 " --unit=UNIT Run under the specified unit name\n"
72 " -p --property=NAME=VALUE Set service or scope unit property\n"
73 " --description=TEXT Description for unit\n"
74 " --slice=SLICE Run in the specified slice\n"
75 " --no-block Do not wait until operation finished\n"
76 " -r --remain-after-exit Leave service around until explicitly stopped\n"
77 " --wait Wait until service stopped again\n"
78 " --send-sighup Send SIGHUP when terminating\n"
79 " --service-type=TYPE Service type\n"
80 " --uid=USER Run as system user\n"
81 " --gid=GROUP Run as system group\n"
82 " --nice=NICE Nice level\n"
83 " -E --setenv=NAME=VALUE Set environment\n"
84 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
86 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
87 " -q --quiet Suppress information messages during runtime\n"
88 " -G --collect Unload unit after it ran, even when failed\n\n"
90 " --path-property=NAME=VALUE Set path unit property\n\n"
92 " --socket-property=NAME=VALUE Set socket unit property\n\n"
94 " --on-active=SECONDS Run after SECONDS delay\n"
95 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
96 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
97 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
98 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
99 " --on-calendar=SPEC Realtime timer\n"
100 " --timer-property=NAME=VALUE Set timer unit property\n"
101 , program_invocation_short_name
);
104 static int add_timer_property(const char *name
, const char *val
) {
110 p
= strjoin(name
, "=", val
);
114 if (strv_consume(&arg_timer_property
, p
) < 0)
120 static int parse_argv(int argc
, char *argv
[]) {
139 ARG_ON_UNIT_INACTIVE
,
149 static const struct option options
[] = {
150 { "help", no_argument
, NULL
, 'h' },
151 { "version", no_argument
, NULL
, ARG_VERSION
},
152 { "user", no_argument
, NULL
, ARG_USER
},
153 { "system", no_argument
, NULL
, ARG_SYSTEM
},
154 { "scope", no_argument
, NULL
, ARG_SCOPE
},
155 { "unit", required_argument
, NULL
, ARG_UNIT
},
156 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
157 { "slice", required_argument
, NULL
, ARG_SLICE
},
158 { "remain-after-exit", no_argument
, NULL
, 'r' },
159 { "send-sighup", no_argument
, NULL
, ARG_SEND_SIGHUP
},
160 { "host", required_argument
, NULL
, 'H' },
161 { "machine", required_argument
, NULL
, 'M' },
162 { "service-type", required_argument
, NULL
, ARG_SERVICE_TYPE
},
163 { "wait", no_argument
, NULL
, ARG_WAIT
},
164 { "uid", required_argument
, NULL
, ARG_EXEC_USER
},
165 { "gid", required_argument
, NULL
, ARG_EXEC_GROUP
},
166 { "nice", required_argument
, NULL
, ARG_NICE
},
167 { "setenv", required_argument
, NULL
, 'E' },
168 { "property", required_argument
, NULL
, 'p' },
169 { "tty", no_argument
, NULL
, 't' }, /* deprecated alias */
170 { "pty", no_argument
, NULL
, 't' },
171 { "pipe", no_argument
, NULL
, 'P' },
172 { "quiet", no_argument
, NULL
, 'q' },
173 { "on-active", required_argument
, NULL
, ARG_ON_ACTIVE
},
174 { "on-boot", required_argument
, NULL
, ARG_ON_BOOT
},
175 { "on-startup", required_argument
, NULL
, ARG_ON_STARTUP
},
176 { "on-unit-active", required_argument
, NULL
, ARG_ON_UNIT_ACTIVE
},
177 { "on-unit-inactive", required_argument
, NULL
, ARG_ON_UNIT_INACTIVE
},
178 { "on-calendar", required_argument
, NULL
, ARG_ON_CALENDAR
},
179 { "timer-property", required_argument
, NULL
, ARG_TIMER_PROPERTY
},
180 { "path-property", required_argument
, NULL
, ARG_PATH_PROPERTY
},
181 { "socket-property", required_argument
, NULL
, ARG_SOCKET_PROPERTY
},
182 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
183 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
184 { "collect", no_argument
, NULL
, 'G' },
188 bool with_trigger
= false;
194 while ((c
= getopt_long(argc
, argv
, "+hrH:M:E:p:tPqG", options
, NULL
)) >= 0)
205 case ARG_NO_ASK_PASSWORD
:
206 arg_ask_password
= false;
225 case ARG_DESCRIPTION
:
226 arg_description
= optarg
;
233 case ARG_SEND_SIGHUP
:
234 arg_send_sighup
= true;
238 arg_remain_after_exit
= true;
242 arg_transport
= BUS_TRANSPORT_REMOTE
;
247 arg_transport
= BUS_TRANSPORT_MACHINE
;
251 case ARG_SERVICE_TYPE
:
252 arg_service_type
= optarg
;
256 arg_exec_user
= optarg
;
260 arg_exec_group
= optarg
;
264 r
= parse_nice(optarg
, &arg_nice
);
266 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
272 if (strv_extend(&arg_environment
, optarg
) < 0)
278 if (strv_extend(&arg_property
, optarg
) < 0)
283 case 't': /* --pty */
284 if (IN_SET(arg_stdio
, ARG_STDIO_DIRECT
, ARG_STDIO_AUTO
)) /* if --pipe is already used, upgrade to auto mode */
285 arg_stdio
= ARG_STDIO_AUTO
;
287 arg_stdio
= ARG_STDIO_PTY
;
290 case 'P': /* --pipe */
291 if (IN_SET(arg_stdio
, ARG_STDIO_PTY
, ARG_STDIO_AUTO
)) /* If --pty is already used, upgrade to auto mode */
292 arg_stdio
= ARG_STDIO_AUTO
;
294 arg_stdio
= ARG_STDIO_DIRECT
;
302 r
= add_timer_property("OnActiveSec", optarg
);
310 r
= add_timer_property("OnBootSec", optarg
);
318 r
= add_timer_property("OnStartupSec", optarg
);
325 case ARG_ON_UNIT_ACTIVE
:
326 r
= add_timer_property("OnUnitActiveSec", optarg
);
333 case ARG_ON_UNIT_INACTIVE
:
334 r
= add_timer_property("OnUnitInactiveSec", optarg
);
341 case ARG_ON_CALENDAR
:
342 r
= add_timer_property("OnCalendar", optarg
);
349 case ARG_TIMER_PROPERTY
:
351 if (strv_extend(&arg_timer_property
, optarg
) < 0)
354 with_timer
= with_timer
||
355 !!startswith(optarg
, "OnActiveSec=") ||
356 !!startswith(optarg
, "OnBootSec=") ||
357 !!startswith(optarg
, "OnStartupSec=") ||
358 !!startswith(optarg
, "OnUnitActiveSec=") ||
359 !!startswith(optarg
, "OnUnitInactiveSec=") ||
360 !!startswith(optarg
, "OnCalendar=");
363 case ARG_PATH_PROPERTY
:
365 if (strv_extend(&arg_path_property
, optarg
) < 0)
370 case ARG_SOCKET_PROPERTY
:
372 if (strv_extend(&arg_socket_property
, optarg
) < 0)
386 arg_aggressive_gc
= true;
393 assert_not_reached("Unhandled option");
396 with_trigger
= !!arg_path_property
|| !!arg_socket_property
|| with_timer
;
398 /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
399 if ((int) !!arg_path_property
+ (int) !!arg_socket_property
+ (int) with_timer
> 1) {
400 log_error("Only single trigger (path, socket, timer) unit can be created.");
404 if (arg_stdio
== ARG_STDIO_AUTO
) {
405 /* If we both --pty and --pipe are specified we'll automatically pick --pty if we are connected fully
406 * to a TTY and pick direct fd passing otherwise. This way, we automatically adapt to usage in a shell
407 * pipeline, but we are neatly interactive with tty-level isolation otherwise. */
408 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ?
413 if ((optind
>= argc
) && (!arg_unit
|| !with_trigger
)) {
414 log_error("Command line to execute required.");
418 if (arg_user
&& arg_transport
!= BUS_TRANSPORT_LOCAL
) {
419 log_error("Execution in user context is not supported on non-local systems.");
423 if (arg_scope
&& arg_transport
!= BUS_TRANSPORT_LOCAL
) {
424 log_error("Scope execution is not supported on non-local systems.");
428 if (arg_scope
&& (arg_remain_after_exit
|| arg_service_type
)) {
429 log_error("--remain-after-exit and --service-type= are not supported in --scope mode.");
433 if (arg_stdio
!= ARG_STDIO_NONE
&& (with_trigger
|| arg_scope
)) {
434 log_error("--pty/--pipe is not compatible in timer or --scope mode.");
438 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_transport
== BUS_TRANSPORT_REMOTE
) {
439 log_error("--pty/--pipe is only supported when connecting to the local system or containers.");
443 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_no_block
) {
444 log_error("--pty/--pipe is not compatible with --no-block.");
448 if (arg_scope
&& with_trigger
) {
449 log_error("Path, socket or timer options are not supported in --scope mode.");
453 if (arg_timer_property
&& !with_timer
) {
454 log_error("--timer-property= has no effect without any other timer options.");
460 log_error("--wait may not be combined with --no-block.");
465 log_error("--wait may not be combined with path, socket or timer operations.");
470 log_error("--wait may not be combined with --scope.");
478 static int transient_unit_set_properties(sd_bus_message
*m
, UnitType t
, char **properties
) {
481 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", arg_description
);
483 return bus_log_create_error(r
);
485 if (arg_aggressive_gc
) {
486 r
= sd_bus_message_append(m
, "(sv)", "CollectMode", "s", "inactive-or-failed");
488 return bus_log_create_error(r
);
491 r
= bus_append_unit_property_assignment_many(m
, t
, properties
);
498 static int transient_cgroup_set_properties(sd_bus_message
*m
) {
502 if (!isempty(arg_slice
)) {
503 _cleanup_free_
char *slice
= NULL
;
505 r
= unit_name_mangle_with_suffix(arg_slice
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".slice", &slice
);
507 return log_error_errno(r
, "Failed to mangle name '%s': %m", arg_slice
);
509 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", slice
);
511 return bus_log_create_error(r
);
517 static int transient_kill_set_properties(sd_bus_message
*m
) {
522 if (arg_send_sighup
) {
523 r
= sd_bus_message_append(m
, "(sv)", "SendSIGHUP", "b", arg_send_sighup
);
525 return bus_log_create_error(r
);
531 static int transient_service_set_properties(sd_bus_message
*m
, char **argv
, const char *pty_path
) {
532 bool send_term
= false;
537 r
= transient_unit_set_properties(m
, UNIT_SERVICE
, arg_property
);
541 r
= transient_kill_set_properties(m
);
545 r
= transient_cgroup_set_properties(m
);
549 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
550 r
= sd_bus_message_append(m
, "(sv)", "AddRef", "b", 1);
552 return bus_log_create_error(r
);
555 if (arg_remain_after_exit
) {
556 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit
);
558 return bus_log_create_error(r
);
561 if (arg_service_type
) {
562 r
= sd_bus_message_append(m
, "(sv)", "Type", "s", arg_service_type
);
564 return bus_log_create_error(r
);
568 r
= sd_bus_message_append(m
, "(sv)", "User", "s", arg_exec_user
);
570 return bus_log_create_error(r
);
573 if (arg_exec_group
) {
574 r
= sd_bus_message_append(m
, "(sv)", "Group", "s", arg_exec_group
);
576 return bus_log_create_error(r
);
580 r
= sd_bus_message_append(m
, "(sv)", "Nice", "i", arg_nice
);
582 return bus_log_create_error(r
);
586 r
= sd_bus_message_append(m
,
588 "StandardInput", "s", "tty",
589 "StandardOutput", "s", "tty",
590 "StandardError", "s", "tty",
591 "TTYPath", "s", pty_path
);
593 return bus_log_create_error(r
);
597 } else if (arg_stdio
== ARG_STDIO_DIRECT
) {
598 r
= sd_bus_message_append(m
,
600 "StandardInputFileDescriptor", "h", STDIN_FILENO
,
601 "StandardOutputFileDescriptor", "h", STDOUT_FILENO
,
602 "StandardErrorFileDescriptor", "h", STDERR_FILENO
);
604 return bus_log_create_error(r
);
606 send_term
= isatty(STDIN_FILENO
) || isatty(STDOUT_FILENO
) || isatty(STDERR_FILENO
);
616 n
= strjoina("TERM=", e
);
617 r
= sd_bus_message_append(m
,
619 "Environment", "as", 1, n
);
621 return bus_log_create_error(r
);
625 if (!strv_isempty(arg_environment
)) {
626 r
= sd_bus_message_open_container(m
, 'r', "sv");
628 return bus_log_create_error(r
);
630 r
= sd_bus_message_append(m
, "s", "Environment");
632 return bus_log_create_error(r
);
634 r
= sd_bus_message_open_container(m
, 'v', "as");
636 return bus_log_create_error(r
);
638 r
= sd_bus_message_append_strv(m
, arg_environment
);
640 return bus_log_create_error(r
);
642 r
= sd_bus_message_close_container(m
);
644 return bus_log_create_error(r
);
646 r
= sd_bus_message_close_container(m
);
648 return bus_log_create_error(r
);
653 r
= sd_bus_message_open_container(m
, 'r', "sv");
655 return bus_log_create_error(r
);
657 r
= sd_bus_message_append(m
, "s", "ExecStart");
659 return bus_log_create_error(r
);
661 r
= sd_bus_message_open_container(m
, 'v', "a(sasb)");
663 return bus_log_create_error(r
);
665 r
= sd_bus_message_open_container(m
, 'a', "(sasb)");
667 return bus_log_create_error(r
);
669 r
= sd_bus_message_open_container(m
, 'r', "sasb");
671 return bus_log_create_error(r
);
673 r
= sd_bus_message_append(m
, "s", argv
[0]);
675 return bus_log_create_error(r
);
677 r
= sd_bus_message_append_strv(m
, argv
);
679 return bus_log_create_error(r
);
681 r
= sd_bus_message_append(m
, "b", false);
683 return bus_log_create_error(r
);
685 r
= sd_bus_message_close_container(m
);
687 return bus_log_create_error(r
);
689 r
= sd_bus_message_close_container(m
);
691 return bus_log_create_error(r
);
693 r
= sd_bus_message_close_container(m
);
695 return bus_log_create_error(r
);
697 r
= sd_bus_message_close_container(m
);
699 return bus_log_create_error(r
);
705 static int transient_scope_set_properties(sd_bus_message
*m
) {
710 r
= transient_unit_set_properties(m
, UNIT_SCOPE
, arg_property
);
714 r
= transient_kill_set_properties(m
);
718 r
= transient_cgroup_set_properties(m
);
722 r
= sd_bus_message_append(m
, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached());
724 return bus_log_create_error(r
);
729 static int transient_timer_set_properties(sd_bus_message
*m
) {
734 r
= transient_unit_set_properties(m
, UNIT_TIMER
, arg_timer_property
);
738 /* Automatically clean up our transient timers */
739 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterElapse", "b", false);
741 return bus_log_create_error(r
);
746 static int make_unit_name(sd_bus
*bus
, UnitType t
, char **ret
) {
747 const char *unique
, *id
;
753 assert(t
< _UNIT_TYPE_MAX
);
755 r
= sd_bus_get_unique_name(bus
, &unique
);
759 /* We couldn't get the unique name, which is a pretty
760 * common case if we are connected to systemd
761 * directly. In that case, just pick a random uuid as
764 r
= sd_id128_randomize(&rnd
);
766 return log_error_errno(r
, "Failed to generate random run unit name: %m");
768 if (asprintf(ret
, "run-r" SD_ID128_FORMAT_STR
".%s", SD_ID128_FORMAT_VAL(rnd
), unit_type_to_string(t
)) < 0)
774 /* We managed to get the unique name, then let's use that to
775 * name our transient units. */
777 id
= startswith(unique
, ":1.");
779 log_error("Unique name %s has unexpected format.", unique
);
783 p
= strjoin("run-u", id
, ".", unit_type_to_string(t
));
791 typedef struct RunContext
{
797 /* The exit data of the unit */
799 uint64_t inactive_exit_usec
;
800 uint64_t inactive_enter_usec
;
802 uint64_t cpu_usage_nsec
;
803 uint64_t ip_ingress_bytes
;
804 uint64_t ip_egress_bytes
;
806 uint32_t exit_status
;
809 static void run_context_free(RunContext
*c
) {
812 c
->forward
= pty_forward_free(c
->forward
);
813 c
->match
= sd_bus_slot_unref(c
->match
);
814 c
->bus
= sd_bus_unref(c
->bus
);
815 c
->event
= sd_event_unref(c
->event
);
817 free(c
->active_state
);
821 static void run_context_check_done(RunContext
*c
) {
827 done
= STRPTR_IN_SET(c
->active_state
, "inactive", "failed");
831 if (c
->forward
&& done
) /* If the service is gone, it's time to drain the output */
832 done
= pty_forward_drain(c
->forward
);
835 sd_event_exit(c
->event
, EXIT_SUCCESS
);
838 static int run_context_update(RunContext
*c
, const char *path
) {
840 static const struct bus_properties_map map
[] = {
841 { "ActiveState", "s", NULL
, offsetof(RunContext
, active_state
) },
842 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_exit_usec
) },
843 { "InactiveEnterTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_enter_usec
) },
844 { "Result", "s", NULL
, offsetof(RunContext
, result
) },
845 { "ExecMainCode", "i", NULL
, offsetof(RunContext
, exit_code
) },
846 { "ExecMainStatus", "i", NULL
, offsetof(RunContext
, exit_status
) },
847 { "CPUUsageNSec", "t", NULL
, offsetof(RunContext
, cpu_usage_nsec
) },
848 { "IPIngressBytes", "t", NULL
, offsetof(RunContext
, ip_ingress_bytes
) },
849 { "IPEgressBytes", "t", NULL
, offsetof(RunContext
, ip_egress_bytes
) },
853 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
856 r
= bus_map_all_properties(c
->bus
,
857 "org.freedesktop.systemd1",
865 sd_event_exit(c
->event
, EXIT_FAILURE
);
866 return log_error_errno(r
, "Failed to query unit state: %s", bus_error_message(&error
, r
));
869 run_context_check_done(c
);
873 static int on_properties_changed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
874 RunContext
*c
= userdata
;
879 return run_context_update(c
, sd_bus_message_get_path(m
));
882 static int pty_forward_handler(PTYForward
*f
, int rcode
, void *userdata
) {
883 RunContext
*c
= userdata
;
888 sd_event_exit(c
->event
, EXIT_FAILURE
);
889 return log_error_errno(rcode
, "Error on PTY forwarding logic: %m");
892 run_context_check_done(c
);
896 static int start_transient_service(
901 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
902 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
903 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
904 _cleanup_free_
char *service
= NULL
, *pty_path
= NULL
;
905 _cleanup_close_
int master
= -1;
912 if (arg_stdio
== ARG_STDIO_PTY
) {
914 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
915 master
= posix_openpt(O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
917 return log_error_errno(errno
, "Failed to acquire pseudo tty: %m");
919 r
= ptsname_malloc(master
, &pty_path
);
921 return log_error_errno(r
, "Failed to determine tty name: %m");
923 if (unlockpt(master
) < 0)
924 return log_error_errno(errno
, "Failed to unlock tty: %m");
926 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
927 _cleanup_(sd_bus_unrefp
) sd_bus
*system_bus
= NULL
;
928 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pty_reply
= NULL
;
931 r
= sd_bus_default_system(&system_bus
);
933 return log_error_errno(r
, "Failed to connect to system bus: %m");
935 r
= sd_bus_call_method(system_bus
,
936 "org.freedesktop.machine1",
937 "/org/freedesktop/machine1",
938 "org.freedesktop.machine1.Manager",
944 log_error("Failed to get machine PTY: %s", bus_error_message(&error
, -r
));
948 r
= sd_bus_message_read(pty_reply
, "hs", &master
, &s
);
950 return bus_log_parse_error(r
);
952 master
= fcntl(master
, F_DUPFD_CLOEXEC
, 3);
954 return log_error_errno(errno
, "Failed to duplicate master fd: %m");
956 pty_path
= strdup(s
);
960 assert_not_reached("Can't allocate tty via ssh");
964 r
= bus_wait_for_jobs_new(bus
, &w
);
966 return log_error_errno(r
, "Could not watch jobs: %m");
970 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".service", &service
);
972 return log_error_errno(r
, "Failed to mangle unit name: %m");
974 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
979 r
= sd_bus_message_new_method_call(
982 "org.freedesktop.systemd1",
983 "/org/freedesktop/systemd1",
984 "org.freedesktop.systemd1.Manager",
985 "StartTransientUnit");
987 return bus_log_create_error(r
);
989 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
991 return bus_log_create_error(r
);
994 r
= sd_bus_message_append(m
, "ss", service
, "fail");
996 return bus_log_create_error(r
);
999 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1001 return bus_log_create_error(r
);
1003 r
= transient_service_set_properties(m
, argv
, pty_path
);
1007 r
= sd_bus_message_close_container(m
);
1009 return bus_log_create_error(r
);
1011 /* Auxiliary units */
1012 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1014 return bus_log_create_error(r
);
1016 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1018 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1020 return log_error_errno(r
, "Failed to start transient service unit: %s", bus_error_message(&error
, r
));
1025 r
= sd_bus_message_read(reply
, "o", &object
);
1027 return bus_log_parse_error(r
);
1029 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1035 log_info("Running as unit: %s", service
);
1037 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
1038 _cleanup_(run_context_free
) RunContext c
= {
1039 .cpu_usage_nsec
= NSEC_INFINITY
,
1040 .ip_ingress_bytes
= UINT64_MAX
,
1041 .ip_egress_bytes
= UINT64_MAX
,
1042 .inactive_exit_usec
= USEC_INFINITY
,
1043 .inactive_enter_usec
= USEC_INFINITY
,
1045 _cleanup_free_
char *path
= NULL
;
1047 c
.bus
= sd_bus_ref(bus
);
1049 r
= sd_event_default(&c
.event
);
1051 return log_error_errno(r
, "Failed to get event loop: %m");
1054 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
1055 (void) sd_event_add_signal(c
.event
, NULL
, SIGINT
, NULL
, NULL
);
1056 (void) sd_event_add_signal(c
.event
, NULL
, SIGTERM
, NULL
, NULL
);
1059 log_info("Press ^] three times within 1s to disconnect TTY.");
1061 r
= pty_forward_new(c
.event
, master
, PTY_FORWARD_IGNORE_INITIAL_VHANGUP
, &c
.forward
);
1063 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
1065 pty_forward_set_handler(c
.forward
, pty_forward_handler
, &c
);
1067 /* Make sure to process any TTY events before we process bus events */
1068 (void) pty_forward_set_priority(c
.forward
, SD_EVENT_PRIORITY_IMPORTANT
);
1071 path
= unit_dbus_path_from_name(service
);
1075 r
= sd_bus_match_signal_async(
1078 "org.freedesktop.systemd1",
1080 "org.freedesktop.DBus.Properties",
1081 "PropertiesChanged",
1082 on_properties_changed
, NULL
, &c
);
1084 return log_error_errno(r
, "Failed to request properties changed signal match: %m");
1086 r
= sd_bus_attach_event(bus
, c
.event
, SD_EVENT_PRIORITY_NORMAL
);
1088 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1090 r
= run_context_update(&c
, path
);
1094 r
= sd_event_loop(c
.event
);
1096 return log_error_errno(r
, "Failed to run event loop: %m");
1101 r
= pty_forward_get_last_char(c
.forward
, &last_char
);
1102 if (r
>= 0 && !arg_quiet
&& last_char
!= '\n')
1103 fputc('\n', stdout
);
1106 if (arg_wait
&& !arg_quiet
) {
1108 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, in its
1109 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1111 c
.forward
= pty_forward_free(c
.forward
);
1113 if (!isempty(c
.result
))
1114 log_info("Finished with result: %s", strna(c
.result
));
1116 if (c
.exit_code
== CLD_EXITED
)
1117 log_info("Main processes terminated with: code=%s/status=%i", sigchld_code_to_string(c
.exit_code
), c
.exit_status
);
1118 else if (c
.exit_code
> 0)
1119 log_info("Main processes terminated with: code=%s/status=%s", sigchld_code_to_string(c
.exit_code
), signal_to_string(c
.exit_status
));
1121 if (c
.inactive_enter_usec
> 0 && c
.inactive_enter_usec
!= USEC_INFINITY
&&
1122 c
.inactive_exit_usec
> 0 && c
.inactive_exit_usec
!= USEC_INFINITY
&&
1123 c
.inactive_enter_usec
> c
.inactive_exit_usec
) {
1124 char ts
[FORMAT_TIMESPAN_MAX
];
1125 log_info("Service runtime: %s", format_timespan(ts
, sizeof(ts
), c
.inactive_enter_usec
- c
.inactive_exit_usec
, USEC_PER_MSEC
));
1128 if (c
.cpu_usage_nsec
!= NSEC_INFINITY
) {
1129 char ts
[FORMAT_TIMESPAN_MAX
];
1130 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
));
1133 if (c
.ip_ingress_bytes
!= UINT64_MAX
) {
1134 char bytes
[FORMAT_BYTES_MAX
];
1135 log_info("IP traffic received: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_ingress_bytes
));
1137 if (c
.ip_egress_bytes
!= UINT64_MAX
) {
1138 char bytes
[FORMAT_BYTES_MAX
];
1139 log_info("IP traffic sent: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_egress_bytes
));
1143 /* Try to propagate the service's return value */
1144 if (c
.result
&& STR_IN_SET(c
.result
, "success", "exit-code") && c
.exit_code
== CLD_EXITED
)
1145 *retval
= c
.exit_status
;
1147 *retval
= EXIT_FAILURE
;
1153 static int start_transient_scope(
1157 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1158 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1159 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1160 _cleanup_strv_free_
char **env
= NULL
, **user_env
= NULL
;
1161 _cleanup_free_
char *scope
= NULL
;
1162 const char *object
= NULL
;
1168 r
= bus_wait_for_jobs_new(bus
, &w
);
1173 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".scope", &scope
);
1175 return log_error_errno(r
, "Failed to mangle scope name: %m");
1177 r
= make_unit_name(bus
, UNIT_SCOPE
, &scope
);
1182 r
= sd_bus_message_new_method_call(
1185 "org.freedesktop.systemd1",
1186 "/org/freedesktop/systemd1",
1187 "org.freedesktop.systemd1.Manager",
1188 "StartTransientUnit");
1190 return bus_log_create_error(r
);
1192 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1194 return bus_log_create_error(r
);
1197 r
= sd_bus_message_append(m
, "ss", scope
, "fail");
1199 return bus_log_create_error(r
);
1202 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1204 return bus_log_create_error(r
);
1206 r
= transient_scope_set_properties(m
);
1210 r
= sd_bus_message_close_container(m
);
1212 return bus_log_create_error(r
);
1214 /* Auxiliary units */
1215 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1217 return bus_log_create_error(r
);
1219 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1221 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1223 log_error("Failed to start transient scope unit: %s", bus_error_message(&error
, -r
));
1228 if (setpriority(PRIO_PROCESS
, 0, arg_nice
) < 0)
1229 return log_error_errno(errno
, "Failed to set nice level: %m");
1232 if (arg_exec_group
) {
1235 r
= get_group_creds(&arg_exec_group
, &gid
);
1237 return log_error_errno(r
, "Failed to resolve group %s: %m", arg_exec_group
);
1239 if (setresgid(gid
, gid
, gid
) < 0)
1240 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1243 if (arg_exec_user
) {
1244 const char *home
, *shell
;
1248 r
= get_user_creds_clean(&arg_exec_user
, &uid
, &gid
, &home
, &shell
);
1250 return log_error_errno(r
, "Failed to resolve user %s: %m", arg_exec_user
);
1253 r
= strv_extendf(&user_env
, "HOME=%s", home
);
1259 r
= strv_extendf(&user_env
, "SHELL=%s", shell
);
1264 r
= strv_extendf(&user_env
, "USER=%s", arg_exec_user
);
1268 r
= strv_extendf(&user_env
, "LOGNAME=%s", arg_exec_user
);
1272 if (!arg_exec_group
) {
1273 if (setresgid(gid
, gid
, gid
) < 0)
1274 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1277 if (setresuid(uid
, uid
, uid
) < 0)
1278 return log_error_errno(errno
, "Failed to change UID to " UID_FMT
": %m", uid
);
1281 env
= strv_env_merge(3, environ
, user_env
, arg_environment
);
1285 r
= sd_bus_message_read(reply
, "o", &object
);
1287 return bus_log_parse_error(r
);
1289 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1294 log_info("Running scope as unit: %s", scope
);
1296 execvpe(argv
[0], argv
, env
);
1298 return log_error_errno(errno
, "Failed to execute: %m");
1301 static int start_transient_trigger(
1304 const char *suffix
) {
1306 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1307 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1308 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1309 _cleanup_free_
char *trigger
= NULL
, *service
= NULL
;
1310 const char *object
= NULL
;
1316 r
= bus_wait_for_jobs_new(bus
, &w
);
1321 switch (unit_name_to_type(arg_unit
)) {
1324 service
= strdup(arg_unit
);
1328 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1330 return log_error_errno(r
, "Failed to change unit suffix: %m");
1334 trigger
= strdup(arg_unit
);
1338 r
= unit_name_change_suffix(trigger
, ".service", &service
);
1340 return log_error_errno(r
, "Failed to change unit suffix: %m");
1344 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".service", &service
);
1346 return log_error_errno(r
, "Failed to mangle unit name: %m");
1348 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, suffix
, &trigger
);
1350 return log_error_errno(r
, "Failed to mangle unit name: %m");
1355 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1359 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1361 return log_error_errno(r
, "Failed to change unit suffix: %m");
1364 r
= sd_bus_message_new_method_call(
1367 "org.freedesktop.systemd1",
1368 "/org/freedesktop/systemd1",
1369 "org.freedesktop.systemd1.Manager",
1370 "StartTransientUnit");
1372 return bus_log_create_error(r
);
1374 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1376 return bus_log_create_error(r
);
1379 r
= sd_bus_message_append(m
, "ss", trigger
, "fail");
1381 return bus_log_create_error(r
);
1384 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1386 return bus_log_create_error(r
);
1388 if (streq(suffix
, ".path"))
1389 r
= transient_unit_set_properties(m
, UNIT_PATH
, arg_path_property
);
1390 else if (streq(suffix
, ".socket"))
1391 r
= transient_unit_set_properties(m
, UNIT_SOCKET
, arg_socket_property
);
1392 else if (streq(suffix
, ".timer"))
1393 r
= transient_timer_set_properties(m
);
1395 assert_not_reached("Invalid suffix");
1399 r
= sd_bus_message_close_container(m
);
1401 return bus_log_create_error(r
);
1403 r
= sd_bus_message_open_container(m
, 'a', "(sa(sv))");
1405 return bus_log_create_error(r
);
1407 if (!strv_isempty(argv
)) {
1408 r
= sd_bus_message_open_container(m
, 'r', "sa(sv)");
1410 return bus_log_create_error(r
);
1412 r
= sd_bus_message_append(m
, "s", service
);
1414 return bus_log_create_error(r
);
1416 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1418 return bus_log_create_error(r
);
1420 r
= transient_service_set_properties(m
, argv
, NULL
);
1424 r
= sd_bus_message_close_container(m
);
1426 return bus_log_create_error(r
);
1428 r
= sd_bus_message_close_container(m
);
1430 return bus_log_create_error(r
);
1433 r
= sd_bus_message_close_container(m
);
1435 return bus_log_create_error(r
);
1437 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1439 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1441 log_error("Failed to start transient %s unit: %s", suffix
+ 1, bus_error_message(&error
, -r
));
1445 r
= sd_bus_message_read(reply
, "o", &object
);
1447 return bus_log_parse_error(r
);
1449 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1454 log_info("Running %s as unit: %s", suffix
+ 1, trigger
);
1456 log_info("Will run service as unit: %s", service
);
1462 int main(int argc
, char* argv
[]) {
1463 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
1464 _cleanup_free_
char *description
= NULL
, *command
= NULL
;
1465 int r
, retval
= EXIT_SUCCESS
;
1467 log_parse_environment();
1470 r
= parse_argv(argc
, argv
);
1474 if (argc
> optind
&& arg_transport
== BUS_TRANSPORT_LOCAL
) {
1475 /* Patch in an absolute path */
1477 r
= find_binary(argv
[optind
], &command
);
1479 log_error_errno(r
, "Failed to find executable %s: %m", argv
[optind
]);
1483 argv
[optind
] = command
;
1486 if (!arg_description
) {
1487 description
= strv_join(argv
+ optind
, " ");
1493 if (arg_unit
&& isempty(description
)) {
1494 r
= free_and_strdup(&description
, arg_unit
);
1499 arg_description
= description
;
1502 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the limited direct
1504 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
)
1505 r
= bus_connect_transport(arg_transport
, arg_host
, arg_user
, &bus
);
1507 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, arg_user
, &bus
);
1509 log_error_errno(r
, "Failed to create bus connection: %m");
1514 r
= start_transient_scope(bus
, argv
+ optind
);
1515 else if (arg_path_property
)
1516 r
= start_transient_trigger(bus
, argv
+ optind
, ".path");
1517 else if (arg_socket_property
)
1518 r
= start_transient_trigger(bus
, argv
+ optind
, ".socket");
1519 else if (with_timer
)
1520 r
= start_transient_trigger(bus
, argv
+ optind
, ".timer");
1522 r
= start_transient_service(bus
, argv
+ optind
, &retval
);
1525 strv_free(arg_environment
);
1526 strv_free(arg_property
);
1527 strv_free(arg_path_property
);
1528 strv_free(arg_socket_property
);
1529 strv_free(arg_timer_property
);
1531 return r
< 0 ? EXIT_FAILURE
: retval
;