1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 Copyright 2013 Lennart Poettering
12 #include "alloc-util.h"
13 #include "bus-error.h"
14 #include "bus-unit-util.h"
16 #include "calendarspec.h"
19 #include "format-util.h"
20 #include "parse-util.h"
21 #include "path-util.h"
22 #include "process-util.h"
24 #include "signal-util.h"
25 #include "spawn-polkit-agent.h"
27 #include "terminal-util.h"
29 #include "unit-name.h"
30 #include "user-util.h"
32 static bool arg_ask_password
= true;
33 static bool arg_scope
= false;
34 static bool arg_remain_after_exit
= false;
35 static bool arg_no_block
= false;
36 static bool arg_wait
= false;
37 static const char *arg_unit
= NULL
;
38 static const char *arg_description
= NULL
;
39 static const char *arg_slice
= NULL
;
40 static bool arg_send_sighup
= false;
41 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
42 static const char *arg_host
= NULL
;
43 static bool arg_user
= false;
44 static const char *arg_service_type
= NULL
;
45 static const char *arg_exec_user
= NULL
;
46 static const char *arg_exec_group
= NULL
;
47 static int arg_nice
= 0;
48 static bool arg_nice_set
= false;
49 static char **arg_environment
= NULL
;
50 static char **arg_property
= NULL
;
52 ARG_STDIO_NONE
, /* The default, as it is for normal services, stdin connected to /dev/null, and stdout+stderr to the journal */
53 ARG_STDIO_PTY
, /* Interactive behaviour, requested by --pty: we allocate a pty and connect it to the TTY we are invoked from */
54 ARG_STDIO_DIRECT
, /* Directly pass our stdin/stdout/stderr to the activated service, useful for usage in shell pipelines, requested by --pipe */
55 ARG_STDIO_AUTO
, /* If --pipe and --pty are used together we use --pty when invoked on a TTY, and --pipe otherwise */
56 } arg_stdio
= ARG_STDIO_NONE
;
57 static char **arg_path_property
= NULL
;
58 static char **arg_socket_property
= NULL
;
59 static char **arg_timer_property
= NULL
;
60 static bool with_timer
= false;
61 static bool arg_quiet
= false;
62 static bool arg_aggressive_gc
= false;
64 static void help(void) {
65 printf("%s [OPTIONS...] {COMMAND} [ARGS...]\n\n"
66 "Run the specified command in a transient scope or service.\n\n"
67 " -h --help Show this help\n"
68 " --version Show package version\n"
69 " --no-ask-password Do not prompt for password\n"
70 " --user Run as user unit\n"
71 " -H --host=[USER@]HOST Operate on remote host\n"
72 " -M --machine=CONTAINER Operate on local container\n"
73 " --scope Run this as scope rather than service\n"
74 " --unit=UNIT Run under the specified unit name\n"
75 " -p --property=NAME=VALUE Set service or scope unit property\n"
76 " --description=TEXT Description for unit\n"
77 " --slice=SLICE Run in the specified slice\n"
78 " --no-block Do not wait until operation finished\n"
79 " -r --remain-after-exit Leave service around until explicitly stopped\n"
80 " --wait Wait until service stopped again\n"
81 " --send-sighup Send SIGHUP when terminating\n"
82 " --service-type=TYPE Service type\n"
83 " --uid=USER Run as system user\n"
84 " --gid=GROUP Run as system group\n"
85 " --nice=NICE Nice level\n"
86 " -E --setenv=NAME=VALUE Set environment\n"
87 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
89 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
90 " -q --quiet Suppress information messages during runtime\n"
91 " -G --collect Unload unit after it ran, even when failed\n\n"
93 " --path-property=NAME=VALUE Set path unit property\n\n"
95 " --socket-property=NAME=VALUE Set socket unit property\n\n"
97 " --on-active=SECONDS Run after SECONDS delay\n"
98 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
99 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
100 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
101 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
102 " --on-calendar=SPEC Realtime timer\n"
103 " --timer-property=NAME=VALUE Set timer unit property\n"
104 , program_invocation_short_name
);
107 static int add_timer_property(const char *name
, const char *val
) {
113 p
= strjoin(name
, "=", val
);
117 if (strv_consume(&arg_timer_property
, p
) < 0)
123 static int parse_argv(int argc
, char *argv
[]) {
142 ARG_ON_UNIT_INACTIVE
,
152 static const struct option options
[] = {
153 { "help", no_argument
, NULL
, 'h' },
154 { "version", no_argument
, NULL
, ARG_VERSION
},
155 { "user", no_argument
, NULL
, ARG_USER
},
156 { "system", no_argument
, NULL
, ARG_SYSTEM
},
157 { "scope", no_argument
, NULL
, ARG_SCOPE
},
158 { "unit", required_argument
, NULL
, ARG_UNIT
},
159 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
160 { "slice", required_argument
, NULL
, ARG_SLICE
},
161 { "remain-after-exit", no_argument
, NULL
, 'r' },
162 { "send-sighup", no_argument
, NULL
, ARG_SEND_SIGHUP
},
163 { "host", required_argument
, NULL
, 'H' },
164 { "machine", required_argument
, NULL
, 'M' },
165 { "service-type", required_argument
, NULL
, ARG_SERVICE_TYPE
},
166 { "wait", no_argument
, NULL
, ARG_WAIT
},
167 { "uid", required_argument
, NULL
, ARG_EXEC_USER
},
168 { "gid", required_argument
, NULL
, ARG_EXEC_GROUP
},
169 { "nice", required_argument
, NULL
, ARG_NICE
},
170 { "setenv", required_argument
, NULL
, 'E' },
171 { "property", required_argument
, NULL
, 'p' },
172 { "tty", no_argument
, NULL
, 't' }, /* deprecated alias */
173 { "pty", no_argument
, NULL
, 't' },
174 { "pipe", no_argument
, NULL
, 'P' },
175 { "quiet", no_argument
, NULL
, 'q' },
176 { "on-active", required_argument
, NULL
, ARG_ON_ACTIVE
},
177 { "on-boot", required_argument
, NULL
, ARG_ON_BOOT
},
178 { "on-startup", required_argument
, NULL
, ARG_ON_STARTUP
},
179 { "on-unit-active", required_argument
, NULL
, ARG_ON_UNIT_ACTIVE
},
180 { "on-unit-inactive", required_argument
, NULL
, ARG_ON_UNIT_INACTIVE
},
181 { "on-calendar", required_argument
, NULL
, ARG_ON_CALENDAR
},
182 { "timer-property", required_argument
, NULL
, ARG_TIMER_PROPERTY
},
183 { "path-property", required_argument
, NULL
, ARG_PATH_PROPERTY
},
184 { "socket-property", required_argument
, NULL
, ARG_SOCKET_PROPERTY
},
185 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
186 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
187 { "collect", no_argument
, NULL
, 'G' },
191 bool with_trigger
= false;
197 while ((c
= getopt_long(argc
, argv
, "+hrH:M:E:p:tPqG", options
, NULL
)) >= 0)
208 case ARG_NO_ASK_PASSWORD
:
209 arg_ask_password
= false;
228 case ARG_DESCRIPTION
:
229 arg_description
= optarg
;
236 case ARG_SEND_SIGHUP
:
237 arg_send_sighup
= true;
241 arg_remain_after_exit
= true;
245 arg_transport
= BUS_TRANSPORT_REMOTE
;
250 arg_transport
= BUS_TRANSPORT_MACHINE
;
254 case ARG_SERVICE_TYPE
:
255 arg_service_type
= optarg
;
259 arg_exec_user
= optarg
;
263 arg_exec_group
= optarg
;
267 r
= parse_nice(optarg
, &arg_nice
);
269 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
275 if (strv_extend(&arg_environment
, optarg
) < 0)
281 if (strv_extend(&arg_property
, optarg
) < 0)
286 case 't': /* --pty */
287 if (IN_SET(arg_stdio
, ARG_STDIO_DIRECT
, ARG_STDIO_AUTO
)) /* if --pipe is already used, upgrade to auto mode */
288 arg_stdio
= ARG_STDIO_AUTO
;
290 arg_stdio
= ARG_STDIO_PTY
;
293 case 'P': /* --pipe */
294 if (IN_SET(arg_stdio
, ARG_STDIO_PTY
, ARG_STDIO_AUTO
)) /* If --pty is already used, upgrade to auto mode */
295 arg_stdio
= ARG_STDIO_AUTO
;
297 arg_stdio
= ARG_STDIO_DIRECT
;
305 r
= add_timer_property("OnActiveSec", optarg
);
313 r
= add_timer_property("OnBootSec", optarg
);
321 r
= add_timer_property("OnStartupSec", optarg
);
328 case ARG_ON_UNIT_ACTIVE
:
329 r
= add_timer_property("OnUnitActiveSec", optarg
);
336 case ARG_ON_UNIT_INACTIVE
:
337 r
= add_timer_property("OnUnitInactiveSec", optarg
);
344 case ARG_ON_CALENDAR
:
345 r
= add_timer_property("OnCalendar", optarg
);
352 case ARG_TIMER_PROPERTY
:
354 if (strv_extend(&arg_timer_property
, optarg
) < 0)
357 with_timer
= with_timer
||
358 !!startswith(optarg
, "OnActiveSec=") ||
359 !!startswith(optarg
, "OnBootSec=") ||
360 !!startswith(optarg
, "OnStartupSec=") ||
361 !!startswith(optarg
, "OnUnitActiveSec=") ||
362 !!startswith(optarg
, "OnUnitInactiveSec=") ||
363 !!startswith(optarg
, "OnCalendar=");
366 case ARG_PATH_PROPERTY
:
368 if (strv_extend(&arg_path_property
, optarg
) < 0)
373 case ARG_SOCKET_PROPERTY
:
375 if (strv_extend(&arg_socket_property
, optarg
) < 0)
389 arg_aggressive_gc
= true;
396 assert_not_reached("Unhandled option");
399 with_trigger
= !!arg_path_property
|| !!arg_socket_property
|| with_timer
;
401 /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
402 if ((int) !!arg_path_property
+ (int) !!arg_socket_property
+ (int) with_timer
> 1) {
403 log_error("Only single trigger (path, socket, timer) unit can be created.");
407 if (arg_stdio
== ARG_STDIO_AUTO
) {
408 /* If we both --pty and --pipe are specified we'll automatically pick --pty if we are connected fully
409 * to a TTY and pick direct fd passing otherwise. This way, we automatically adapt to usage in a shell
410 * pipeline, but we are neatly interactive with tty-level isolation otherwise. */
411 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ?
416 if ((optind
>= argc
) && (!arg_unit
|| !with_trigger
)) {
417 log_error("Command line to execute required.");
421 if (arg_user
&& arg_transport
!= BUS_TRANSPORT_LOCAL
) {
422 log_error("Execution in user context is not supported on non-local systems.");
426 if (arg_scope
&& arg_transport
!= BUS_TRANSPORT_LOCAL
) {
427 log_error("Scope execution is not supported on non-local systems.");
431 if (arg_scope
&& (arg_remain_after_exit
|| arg_service_type
)) {
432 log_error("--remain-after-exit and --service-type= are not supported in --scope mode.");
436 if (arg_stdio
!= ARG_STDIO_NONE
&& (with_trigger
|| arg_scope
)) {
437 log_error("--pty/--pipe is not compatible in timer or --scope mode.");
441 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_transport
== BUS_TRANSPORT_REMOTE
) {
442 log_error("--pty/--pipe is only supported when connecting to the local system or containers.");
446 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_no_block
) {
447 log_error("--pty/--pipe is not compatible with --no-block.");
451 if (arg_scope
&& with_trigger
) {
452 log_error("Path, socket or timer options are not supported in --scope mode.");
456 if (arg_timer_property
&& !with_timer
) {
457 log_error("--timer-property= has no effect without any other timer options.");
463 log_error("--wait may not be combined with --no-block.");
468 log_error("--wait may not be combined with path, socket or timer operations.");
473 log_error("--wait may not be combined with --scope.");
481 static int transient_unit_set_properties(sd_bus_message
*m
, UnitType t
, char **properties
) {
484 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", arg_description
);
486 return bus_log_create_error(r
);
488 if (arg_aggressive_gc
) {
489 r
= sd_bus_message_append(m
, "(sv)", "CollectMode", "s", "inactive-or-failed");
491 return bus_log_create_error(r
);
494 r
= bus_append_unit_property_assignment_many(m
, t
, properties
);
501 static int transient_cgroup_set_properties(sd_bus_message
*m
) {
505 if (!isempty(arg_slice
)) {
506 _cleanup_free_
char *slice
= NULL
;
508 r
= unit_name_mangle_with_suffix(arg_slice
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".slice", &slice
);
510 return log_error_errno(r
, "Failed to mangle name '%s': %m", arg_slice
);
512 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", slice
);
514 return bus_log_create_error(r
);
520 static int transient_kill_set_properties(sd_bus_message
*m
) {
525 if (arg_send_sighup
) {
526 r
= sd_bus_message_append(m
, "(sv)", "SendSIGHUP", "b", arg_send_sighup
);
528 return bus_log_create_error(r
);
534 static int transient_service_set_properties(sd_bus_message
*m
, char **argv
, const char *pty_path
) {
535 bool send_term
= false;
540 r
= transient_unit_set_properties(m
, UNIT_SERVICE
, arg_property
);
544 r
= transient_kill_set_properties(m
);
548 r
= transient_cgroup_set_properties(m
);
552 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
553 r
= sd_bus_message_append(m
, "(sv)", "AddRef", "b", 1);
555 return bus_log_create_error(r
);
558 if (arg_remain_after_exit
) {
559 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit
);
561 return bus_log_create_error(r
);
564 if (arg_service_type
) {
565 r
= sd_bus_message_append(m
, "(sv)", "Type", "s", arg_service_type
);
567 return bus_log_create_error(r
);
571 r
= sd_bus_message_append(m
, "(sv)", "User", "s", arg_exec_user
);
573 return bus_log_create_error(r
);
576 if (arg_exec_group
) {
577 r
= sd_bus_message_append(m
, "(sv)", "Group", "s", arg_exec_group
);
579 return bus_log_create_error(r
);
583 r
= sd_bus_message_append(m
, "(sv)", "Nice", "i", arg_nice
);
585 return bus_log_create_error(r
);
589 r
= sd_bus_message_append(m
,
591 "StandardInput", "s", "tty",
592 "StandardOutput", "s", "tty",
593 "StandardError", "s", "tty",
594 "TTYPath", "s", pty_path
);
596 return bus_log_create_error(r
);
600 } else if (arg_stdio
== ARG_STDIO_DIRECT
) {
601 r
= sd_bus_message_append(m
,
603 "StandardInputFileDescriptor", "h", STDIN_FILENO
,
604 "StandardOutputFileDescriptor", "h", STDOUT_FILENO
,
605 "StandardErrorFileDescriptor", "h", STDERR_FILENO
);
607 return bus_log_create_error(r
);
609 send_term
= isatty(STDIN_FILENO
) || isatty(STDOUT_FILENO
) || isatty(STDERR_FILENO
);
619 n
= strjoina("TERM=", e
);
620 r
= sd_bus_message_append(m
,
622 "Environment", "as", 1, n
);
624 return bus_log_create_error(r
);
628 if (!strv_isempty(arg_environment
)) {
629 r
= sd_bus_message_open_container(m
, 'r', "sv");
631 return bus_log_create_error(r
);
633 r
= sd_bus_message_append(m
, "s", "Environment");
635 return bus_log_create_error(r
);
637 r
= sd_bus_message_open_container(m
, 'v', "as");
639 return bus_log_create_error(r
);
641 r
= sd_bus_message_append_strv(m
, arg_environment
);
643 return bus_log_create_error(r
);
645 r
= sd_bus_message_close_container(m
);
647 return bus_log_create_error(r
);
649 r
= sd_bus_message_close_container(m
);
651 return bus_log_create_error(r
);
656 r
= sd_bus_message_open_container(m
, 'r', "sv");
658 return bus_log_create_error(r
);
660 r
= sd_bus_message_append(m
, "s", "ExecStart");
662 return bus_log_create_error(r
);
664 r
= sd_bus_message_open_container(m
, 'v', "a(sasb)");
666 return bus_log_create_error(r
);
668 r
= sd_bus_message_open_container(m
, 'a', "(sasb)");
670 return bus_log_create_error(r
);
672 r
= sd_bus_message_open_container(m
, 'r', "sasb");
674 return bus_log_create_error(r
);
676 r
= sd_bus_message_append(m
, "s", argv
[0]);
678 return bus_log_create_error(r
);
680 r
= sd_bus_message_append_strv(m
, argv
);
682 return bus_log_create_error(r
);
684 r
= sd_bus_message_append(m
, "b", false);
686 return bus_log_create_error(r
);
688 r
= sd_bus_message_close_container(m
);
690 return bus_log_create_error(r
);
692 r
= sd_bus_message_close_container(m
);
694 return bus_log_create_error(r
);
696 r
= sd_bus_message_close_container(m
);
698 return bus_log_create_error(r
);
700 r
= sd_bus_message_close_container(m
);
702 return bus_log_create_error(r
);
708 static int transient_scope_set_properties(sd_bus_message
*m
) {
713 r
= transient_unit_set_properties(m
, UNIT_SCOPE
, arg_property
);
717 r
= transient_kill_set_properties(m
);
721 r
= transient_cgroup_set_properties(m
);
725 r
= sd_bus_message_append(m
, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached());
727 return bus_log_create_error(r
);
732 static int transient_timer_set_properties(sd_bus_message
*m
) {
737 r
= transient_unit_set_properties(m
, UNIT_TIMER
, arg_timer_property
);
741 /* Automatically clean up our transient timers */
742 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterElapse", "b", false);
744 return bus_log_create_error(r
);
749 static int make_unit_name(sd_bus
*bus
, UnitType t
, char **ret
) {
750 const char *unique
, *id
;
756 assert(t
< _UNIT_TYPE_MAX
);
758 r
= sd_bus_get_unique_name(bus
, &unique
);
762 /* We couldn't get the unique name, which is a pretty
763 * common case if we are connected to systemd
764 * directly. In that case, just pick a random uuid as
767 r
= sd_id128_randomize(&rnd
);
769 return log_error_errno(r
, "Failed to generate random run unit name: %m");
771 if (asprintf(ret
, "run-r" SD_ID128_FORMAT_STR
".%s", SD_ID128_FORMAT_VAL(rnd
), unit_type_to_string(t
)) < 0)
777 /* We managed to get the unique name, then let's use that to
778 * name our transient units. */
780 id
= startswith(unique
, ":1.");
782 log_error("Unique name %s has unexpected format.", unique
);
786 p
= strjoin("run-u", id
, ".", unit_type_to_string(t
));
794 typedef struct RunContext
{
800 /* The exit data of the unit */
802 uint64_t inactive_exit_usec
;
803 uint64_t inactive_enter_usec
;
805 uint64_t cpu_usage_nsec
;
806 uint64_t ip_ingress_bytes
;
807 uint64_t ip_egress_bytes
;
809 uint32_t exit_status
;
812 static void run_context_free(RunContext
*c
) {
815 c
->forward
= pty_forward_free(c
->forward
);
816 c
->match
= sd_bus_slot_unref(c
->match
);
817 c
->bus
= sd_bus_unref(c
->bus
);
818 c
->event
= sd_event_unref(c
->event
);
820 free(c
->active_state
);
824 static void run_context_check_done(RunContext
*c
) {
830 done
= STRPTR_IN_SET(c
->active_state
, "inactive", "failed");
834 if (c
->forward
&& done
) /* If the service is gone, it's time to drain the output */
835 done
= pty_forward_drain(c
->forward
);
838 sd_event_exit(c
->event
, EXIT_SUCCESS
);
841 static int run_context_update(RunContext
*c
, const char *path
) {
843 static const struct bus_properties_map map
[] = {
844 { "ActiveState", "s", NULL
, offsetof(RunContext
, active_state
) },
845 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_exit_usec
) },
846 { "InactiveEnterTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_enter_usec
) },
847 { "Result", "s", NULL
, offsetof(RunContext
, result
) },
848 { "ExecMainCode", "i", NULL
, offsetof(RunContext
, exit_code
) },
849 { "ExecMainStatus", "i", NULL
, offsetof(RunContext
, exit_status
) },
850 { "CPUUsageNSec", "t", NULL
, offsetof(RunContext
, cpu_usage_nsec
) },
851 { "IPIngressBytes", "t", NULL
, offsetof(RunContext
, ip_ingress_bytes
) },
852 { "IPEgressBytes", "t", NULL
, offsetof(RunContext
, ip_egress_bytes
) },
856 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
859 r
= bus_map_all_properties(c
->bus
,
860 "org.freedesktop.systemd1",
868 sd_event_exit(c
->event
, EXIT_FAILURE
);
869 return log_error_errno(r
, "Failed to query unit state: %s", bus_error_message(&error
, r
));
872 run_context_check_done(c
);
876 static int on_properties_changed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
877 RunContext
*c
= userdata
;
882 return run_context_update(c
, sd_bus_message_get_path(m
));
885 static int pty_forward_handler(PTYForward
*f
, int rcode
, void *userdata
) {
886 RunContext
*c
= userdata
;
891 sd_event_exit(c
->event
, EXIT_FAILURE
);
892 return log_error_errno(rcode
, "Error on PTY forwarding logic: %m");
895 run_context_check_done(c
);
899 static int start_transient_service(
904 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
905 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
906 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
907 _cleanup_free_
char *service
= NULL
, *pty_path
= NULL
;
908 _cleanup_close_
int master
= -1;
915 if (arg_stdio
== ARG_STDIO_PTY
) {
917 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
918 master
= posix_openpt(O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
920 return log_error_errno(errno
, "Failed to acquire pseudo tty: %m");
922 r
= ptsname_malloc(master
, &pty_path
);
924 return log_error_errno(r
, "Failed to determine tty name: %m");
926 if (unlockpt(master
) < 0)
927 return log_error_errno(errno
, "Failed to unlock tty: %m");
929 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
930 _cleanup_(sd_bus_unrefp
) sd_bus
*system_bus
= NULL
;
931 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pty_reply
= NULL
;
934 r
= sd_bus_default_system(&system_bus
);
936 return log_error_errno(r
, "Failed to connect to system bus: %m");
938 r
= sd_bus_call_method(system_bus
,
939 "org.freedesktop.machine1",
940 "/org/freedesktop/machine1",
941 "org.freedesktop.machine1.Manager",
947 log_error("Failed to get machine PTY: %s", bus_error_message(&error
, -r
));
951 r
= sd_bus_message_read(pty_reply
, "hs", &master
, &s
);
953 return bus_log_parse_error(r
);
955 master
= fcntl(master
, F_DUPFD_CLOEXEC
, 3);
957 return log_error_errno(errno
, "Failed to duplicate master fd: %m");
959 pty_path
= strdup(s
);
963 assert_not_reached("Can't allocate tty via ssh");
967 r
= bus_wait_for_jobs_new(bus
, &w
);
969 return log_error_errno(r
, "Could not watch jobs: %m");
973 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".service", &service
);
975 return log_error_errno(r
, "Failed to mangle unit name: %m");
977 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
982 r
= sd_bus_message_new_method_call(
985 "org.freedesktop.systemd1",
986 "/org/freedesktop/systemd1",
987 "org.freedesktop.systemd1.Manager",
988 "StartTransientUnit");
990 return bus_log_create_error(r
);
992 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
994 return bus_log_create_error(r
);
997 r
= sd_bus_message_append(m
, "ss", service
, "fail");
999 return bus_log_create_error(r
);
1002 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1004 return bus_log_create_error(r
);
1006 r
= transient_service_set_properties(m
, argv
, pty_path
);
1010 r
= sd_bus_message_close_container(m
);
1012 return bus_log_create_error(r
);
1014 /* Auxiliary units */
1015 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1017 return bus_log_create_error(r
);
1019 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1021 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1023 return log_error_errno(r
, "Failed to start transient service unit: %s", bus_error_message(&error
, r
));
1028 r
= sd_bus_message_read(reply
, "o", &object
);
1030 return bus_log_parse_error(r
);
1032 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1038 log_info("Running as unit: %s", service
);
1040 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
1041 _cleanup_(run_context_free
) RunContext c
= {
1042 .cpu_usage_nsec
= NSEC_INFINITY
,
1043 .ip_ingress_bytes
= UINT64_MAX
,
1044 .ip_egress_bytes
= UINT64_MAX
,
1045 .inactive_exit_usec
= USEC_INFINITY
,
1046 .inactive_enter_usec
= USEC_INFINITY
,
1048 _cleanup_free_
char *path
= NULL
;
1050 c
.bus
= sd_bus_ref(bus
);
1052 r
= sd_event_default(&c
.event
);
1054 return log_error_errno(r
, "Failed to get event loop: %m");
1057 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
1058 (void) sd_event_add_signal(c
.event
, NULL
, SIGINT
, NULL
, NULL
);
1059 (void) sd_event_add_signal(c
.event
, NULL
, SIGTERM
, NULL
, NULL
);
1062 log_info("Press ^] three times within 1s to disconnect TTY.");
1064 r
= pty_forward_new(c
.event
, master
, PTY_FORWARD_IGNORE_INITIAL_VHANGUP
, &c
.forward
);
1066 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
1068 pty_forward_set_handler(c
.forward
, pty_forward_handler
, &c
);
1070 /* Make sure to process any TTY events before we process bus events */
1071 (void) pty_forward_set_priority(c
.forward
, SD_EVENT_PRIORITY_IMPORTANT
);
1074 path
= unit_dbus_path_from_name(service
);
1078 r
= sd_bus_match_signal_async(
1081 "org.freedesktop.systemd1",
1083 "org.freedesktop.DBus.Properties",
1084 "PropertiesChanged",
1085 on_properties_changed
, NULL
, &c
);
1087 return log_error_errno(r
, "Failed to request properties changed signal match: %m");
1089 r
= sd_bus_attach_event(bus
, c
.event
, SD_EVENT_PRIORITY_NORMAL
);
1091 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1093 r
= run_context_update(&c
, path
);
1097 r
= sd_event_loop(c
.event
);
1099 return log_error_errno(r
, "Failed to run event loop: %m");
1104 r
= pty_forward_get_last_char(c
.forward
, &last_char
);
1105 if (r
>= 0 && !arg_quiet
&& last_char
!= '\n')
1106 fputc('\n', stdout
);
1109 if (arg_wait
&& !arg_quiet
) {
1111 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, in its
1112 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1114 c
.forward
= pty_forward_free(c
.forward
);
1116 if (!isempty(c
.result
))
1117 log_info("Finished with result: %s", strna(c
.result
));
1119 if (c
.exit_code
== CLD_EXITED
)
1120 log_info("Main processes terminated with: code=%s/status=%i", sigchld_code_to_string(c
.exit_code
), c
.exit_status
);
1121 else if (c
.exit_code
> 0)
1122 log_info("Main processes terminated with: code=%s/status=%s", sigchld_code_to_string(c
.exit_code
), signal_to_string(c
.exit_status
));
1124 if (c
.inactive_enter_usec
> 0 && c
.inactive_enter_usec
!= USEC_INFINITY
&&
1125 c
.inactive_exit_usec
> 0 && c
.inactive_exit_usec
!= USEC_INFINITY
&&
1126 c
.inactive_enter_usec
> c
.inactive_exit_usec
) {
1127 char ts
[FORMAT_TIMESPAN_MAX
];
1128 log_info("Service runtime: %s", format_timespan(ts
, sizeof(ts
), c
.inactive_enter_usec
- c
.inactive_exit_usec
, USEC_PER_MSEC
));
1131 if (c
.cpu_usage_nsec
!= NSEC_INFINITY
) {
1132 char ts
[FORMAT_TIMESPAN_MAX
];
1133 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
));
1136 if (c
.ip_ingress_bytes
!= UINT64_MAX
) {
1137 char bytes
[FORMAT_BYTES_MAX
];
1138 log_info("IP traffic received: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_ingress_bytes
));
1140 if (c
.ip_egress_bytes
!= UINT64_MAX
) {
1141 char bytes
[FORMAT_BYTES_MAX
];
1142 log_info("IP traffic sent: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_egress_bytes
));
1146 /* Try to propagate the service's return value */
1147 if (c
.result
&& STR_IN_SET(c
.result
, "success", "exit-code") && c
.exit_code
== CLD_EXITED
)
1148 *retval
= c
.exit_status
;
1150 *retval
= EXIT_FAILURE
;
1156 static int start_transient_scope(
1160 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1161 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1162 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1163 _cleanup_strv_free_
char **env
= NULL
, **user_env
= NULL
;
1164 _cleanup_free_
char *scope
= NULL
;
1165 const char *object
= NULL
;
1171 r
= bus_wait_for_jobs_new(bus
, &w
);
1176 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".scope", &scope
);
1178 return log_error_errno(r
, "Failed to mangle scope name: %m");
1180 r
= make_unit_name(bus
, UNIT_SCOPE
, &scope
);
1185 r
= sd_bus_message_new_method_call(
1188 "org.freedesktop.systemd1",
1189 "/org/freedesktop/systemd1",
1190 "org.freedesktop.systemd1.Manager",
1191 "StartTransientUnit");
1193 return bus_log_create_error(r
);
1195 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1197 return bus_log_create_error(r
);
1200 r
= sd_bus_message_append(m
, "ss", scope
, "fail");
1202 return bus_log_create_error(r
);
1205 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1207 return bus_log_create_error(r
);
1209 r
= transient_scope_set_properties(m
);
1213 r
= sd_bus_message_close_container(m
);
1215 return bus_log_create_error(r
);
1217 /* Auxiliary units */
1218 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1220 return bus_log_create_error(r
);
1222 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1224 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1226 log_error("Failed to start transient scope unit: %s", bus_error_message(&error
, -r
));
1231 if (setpriority(PRIO_PROCESS
, 0, arg_nice
) < 0)
1232 return log_error_errno(errno
, "Failed to set nice level: %m");
1235 if (arg_exec_group
) {
1238 r
= get_group_creds(&arg_exec_group
, &gid
);
1240 return log_error_errno(r
, "Failed to resolve group %s: %m", arg_exec_group
);
1242 if (setresgid(gid
, gid
, gid
) < 0)
1243 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1246 if (arg_exec_user
) {
1247 const char *home
, *shell
;
1251 r
= get_user_creds_clean(&arg_exec_user
, &uid
, &gid
, &home
, &shell
);
1253 return log_error_errno(r
, "Failed to resolve user %s: %m", arg_exec_user
);
1256 r
= strv_extendf(&user_env
, "HOME=%s", home
);
1262 r
= strv_extendf(&user_env
, "SHELL=%s", shell
);
1267 r
= strv_extendf(&user_env
, "USER=%s", arg_exec_user
);
1271 r
= strv_extendf(&user_env
, "LOGNAME=%s", arg_exec_user
);
1275 if (!arg_exec_group
) {
1276 if (setresgid(gid
, gid
, gid
) < 0)
1277 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1280 if (setresuid(uid
, uid
, uid
) < 0)
1281 return log_error_errno(errno
, "Failed to change UID to " UID_FMT
": %m", uid
);
1284 env
= strv_env_merge(3, environ
, user_env
, arg_environment
);
1288 r
= sd_bus_message_read(reply
, "o", &object
);
1290 return bus_log_parse_error(r
);
1292 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1297 log_info("Running scope as unit: %s", scope
);
1299 execvpe(argv
[0], argv
, env
);
1301 return log_error_errno(errno
, "Failed to execute: %m");
1304 static int start_transient_trigger(
1307 const char *suffix
) {
1309 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1310 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1311 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1312 _cleanup_free_
char *trigger
= NULL
, *service
= NULL
;
1313 const char *object
= NULL
;
1319 r
= bus_wait_for_jobs_new(bus
, &w
);
1324 switch (unit_name_to_type(arg_unit
)) {
1327 service
= strdup(arg_unit
);
1331 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1333 return log_error_errno(r
, "Failed to change unit suffix: %m");
1337 trigger
= strdup(arg_unit
);
1341 r
= unit_name_change_suffix(trigger
, ".service", &service
);
1343 return log_error_errno(r
, "Failed to change unit suffix: %m");
1347 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".service", &service
);
1349 return log_error_errno(r
, "Failed to mangle unit name: %m");
1351 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, suffix
, &trigger
);
1353 return log_error_errno(r
, "Failed to mangle unit name: %m");
1358 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1362 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1364 return log_error_errno(r
, "Failed to change unit suffix: %m");
1367 r
= sd_bus_message_new_method_call(
1370 "org.freedesktop.systemd1",
1371 "/org/freedesktop/systemd1",
1372 "org.freedesktop.systemd1.Manager",
1373 "StartTransientUnit");
1375 return bus_log_create_error(r
);
1377 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1379 return bus_log_create_error(r
);
1382 r
= sd_bus_message_append(m
, "ss", trigger
, "fail");
1384 return bus_log_create_error(r
);
1387 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1389 return bus_log_create_error(r
);
1391 if (streq(suffix
, ".path"))
1392 r
= transient_unit_set_properties(m
, UNIT_PATH
, arg_path_property
);
1393 else if (streq(suffix
, ".socket"))
1394 r
= transient_unit_set_properties(m
, UNIT_SOCKET
, arg_socket_property
);
1395 else if (streq(suffix
, ".timer"))
1396 r
= transient_timer_set_properties(m
);
1398 assert_not_reached("Invalid suffix");
1402 r
= sd_bus_message_close_container(m
);
1404 return bus_log_create_error(r
);
1406 r
= sd_bus_message_open_container(m
, 'a', "(sa(sv))");
1408 return bus_log_create_error(r
);
1410 if (!strv_isempty(argv
)) {
1411 r
= sd_bus_message_open_container(m
, 'r', "sa(sv)");
1413 return bus_log_create_error(r
);
1415 r
= sd_bus_message_append(m
, "s", service
);
1417 return bus_log_create_error(r
);
1419 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1421 return bus_log_create_error(r
);
1423 r
= transient_service_set_properties(m
, argv
, NULL
);
1427 r
= sd_bus_message_close_container(m
);
1429 return bus_log_create_error(r
);
1431 r
= sd_bus_message_close_container(m
);
1433 return bus_log_create_error(r
);
1436 r
= sd_bus_message_close_container(m
);
1438 return bus_log_create_error(r
);
1440 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1442 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1444 log_error("Failed to start transient %s unit: %s", suffix
+ 1, bus_error_message(&error
, -r
));
1448 r
= sd_bus_message_read(reply
, "o", &object
);
1450 return bus_log_parse_error(r
);
1452 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1457 log_info("Running %s as unit: %s", suffix
+ 1, trigger
);
1459 log_info("Will run service as unit: %s", service
);
1465 int main(int argc
, char* argv
[]) {
1466 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
1467 _cleanup_free_
char *description
= NULL
, *command
= NULL
;
1468 int r
, retval
= EXIT_SUCCESS
;
1470 log_parse_environment();
1473 r
= parse_argv(argc
, argv
);
1477 if (argc
> optind
&& arg_transport
== BUS_TRANSPORT_LOCAL
) {
1478 /* Patch in an absolute path */
1480 r
= find_binary(argv
[optind
], &command
);
1482 log_error_errno(r
, "Failed to find executable %s: %m", argv
[optind
]);
1486 argv
[optind
] = command
;
1489 if (!arg_description
) {
1490 description
= strv_join(argv
+ optind
, " ");
1496 if (arg_unit
&& isempty(description
)) {
1497 r
= free_and_strdup(&description
, arg_unit
);
1502 arg_description
= description
;
1505 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the limited direct
1507 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
)
1508 r
= bus_connect_transport(arg_transport
, arg_host
, arg_user
, &bus
);
1510 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, arg_user
, &bus
);
1512 log_error_errno(r
, "Failed to create bus connection: %m");
1517 r
= start_transient_scope(bus
, argv
+ optind
);
1518 else if (arg_path_property
)
1519 r
= start_transient_trigger(bus
, argv
+ optind
, ".path");
1520 else if (arg_socket_property
)
1521 r
= start_transient_trigger(bus
, argv
+ optind
, ".socket");
1522 else if (with_timer
)
1523 r
= start_transient_trigger(bus
, argv
+ optind
, ".timer");
1525 r
= start_transient_service(bus
, argv
+ optind
, &retval
);
1528 strv_free(arg_environment
);
1529 strv_free(arg_property
);
1530 strv_free(arg_path_property
);
1531 strv_free(arg_socket_property
);
1532 strv_free(arg_timer_property
);
1534 return r
< 0 ? EXIT_FAILURE
: retval
;