1 /* SPDX-License-Identifier: LGPL-2.1+ */
3 This file is part of systemd.
5 Copyright 2013 Lennart Poettering
14 #include "alloc-util.h"
15 #include "bus-error.h"
16 #include "bus-unit-util.h"
18 #include "calendarspec.h"
21 #include "format-util.h"
22 #include "parse-util.h"
23 #include "path-util.h"
24 #include "process-util.h"
26 #include "signal-util.h"
27 #include "spawn-polkit-agent.h"
29 #include "terminal-util.h"
31 #include "unit-name.h"
32 #include "user-util.h"
34 static bool arg_ask_password
= true;
35 static bool arg_scope
= false;
36 static bool arg_remain_after_exit
= false;
37 static bool arg_no_block
= false;
38 static bool arg_wait
= false;
39 static const char *arg_unit
= NULL
;
40 static const char *arg_description
= NULL
;
41 static const char *arg_slice
= NULL
;
42 static bool arg_send_sighup
= false;
43 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
44 static const char *arg_host
= NULL
;
45 static bool arg_user
= false;
46 static const char *arg_service_type
= NULL
;
47 static const char *arg_exec_user
= NULL
;
48 static const char *arg_exec_group
= NULL
;
49 static int arg_nice
= 0;
50 static bool arg_nice_set
= false;
51 static char **arg_environment
= NULL
;
52 static char **arg_property
= NULL
;
54 ARG_STDIO_NONE
, /* The default, as it is for normal services, stdin connected to /dev/null, and stdout+stderr to the journal */
55 ARG_STDIO_PTY
, /* Interactive behaviour, requested by --pty: we allocate a pty and connect it to the TTY we are invoked from */
56 ARG_STDIO_DIRECT
, /* Directly pass our stdin/stdout/stderr to the activated service, useful for usage in shell pipelines, requested by --pipe */
57 ARG_STDIO_AUTO
, /* If --pipe and --pty are used together we use --pty when invoked on a TTY, and --pipe otherwise */
58 } arg_stdio
= ARG_STDIO_NONE
;
59 static char **arg_path_property
= NULL
;
60 static char **arg_socket_property
= NULL
;
61 static char **arg_timer_property
= NULL
;
62 static bool with_timer
= false;
63 static bool arg_quiet
= false;
64 static bool arg_aggressive_gc
= false;
66 static void help(void) {
67 printf("%s [OPTIONS...] {COMMAND} [ARGS...]\n\n"
68 "Run the specified command in a transient scope or service.\n\n"
69 " -h --help Show this help\n"
70 " --version Show package version\n"
71 " --no-ask-password Do not prompt for password\n"
72 " --user Run as user unit\n"
73 " -H --host=[USER@]HOST Operate on remote host\n"
74 " -M --machine=CONTAINER Operate on local container\n"
75 " --scope Run this as scope rather than service\n"
76 " --unit=UNIT Run under the specified unit name\n"
77 " -p --property=NAME=VALUE Set service or scope unit property\n"
78 " --description=TEXT Description for unit\n"
79 " --slice=SLICE Run in the specified slice\n"
80 " --no-block Do not wait until operation finished\n"
81 " -r --remain-after-exit Leave service around until explicitly stopped\n"
82 " --wait Wait until service stopped again\n"
83 " --send-sighup Send SIGHUP when terminating\n"
84 " --service-type=TYPE Service type\n"
85 " --uid=USER Run as system user\n"
86 " --gid=GROUP Run as system group\n"
87 " --nice=NICE Nice level\n"
88 " -E --setenv=NAME=VALUE Set environment\n"
89 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
91 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
92 " -q --quiet Suppress information messages during runtime\n"
93 " -G --collect Unload unit after it ran, even when failed\n\n"
95 " --path-property=NAME=VALUE Set path unit property\n\n"
97 " --socket-property=NAME=VALUE Set socket unit property\n\n"
99 " --on-active=SECONDS Run after SECONDS delay\n"
100 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
101 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
102 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
103 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
104 " --on-calendar=SPEC Realtime timer\n"
105 " --timer-property=NAME=VALUE Set timer unit property\n"
106 , program_invocation_short_name
);
109 static int add_timer_property(const char *name
, const char *val
) {
115 p
= strjoin(name
, "=", val
);
119 if (strv_consume(&arg_timer_property
, p
) < 0)
125 static int parse_argv(int argc
, char *argv
[]) {
144 ARG_ON_UNIT_INACTIVE
,
154 static const struct option options
[] = {
155 { "help", no_argument
, NULL
, 'h' },
156 { "version", no_argument
, NULL
, ARG_VERSION
},
157 { "user", no_argument
, NULL
, ARG_USER
},
158 { "system", no_argument
, NULL
, ARG_SYSTEM
},
159 { "scope", no_argument
, NULL
, ARG_SCOPE
},
160 { "unit", required_argument
, NULL
, ARG_UNIT
},
161 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
162 { "slice", required_argument
, NULL
, ARG_SLICE
},
163 { "remain-after-exit", no_argument
, NULL
, 'r' },
164 { "send-sighup", no_argument
, NULL
, ARG_SEND_SIGHUP
},
165 { "host", required_argument
, NULL
, 'H' },
166 { "machine", required_argument
, NULL
, 'M' },
167 { "service-type", required_argument
, NULL
, ARG_SERVICE_TYPE
},
168 { "wait", no_argument
, NULL
, ARG_WAIT
},
169 { "uid", required_argument
, NULL
, ARG_EXEC_USER
},
170 { "gid", required_argument
, NULL
, ARG_EXEC_GROUP
},
171 { "nice", required_argument
, NULL
, ARG_NICE
},
172 { "setenv", required_argument
, NULL
, 'E' },
173 { "property", required_argument
, NULL
, 'p' },
174 { "tty", no_argument
, NULL
, 't' }, /* deprecated alias */
175 { "pty", no_argument
, NULL
, 't' },
176 { "pipe", no_argument
, NULL
, 'P' },
177 { "quiet", no_argument
, NULL
, 'q' },
178 { "on-active", required_argument
, NULL
, ARG_ON_ACTIVE
},
179 { "on-boot", required_argument
, NULL
, ARG_ON_BOOT
},
180 { "on-startup", required_argument
, NULL
, ARG_ON_STARTUP
},
181 { "on-unit-active", required_argument
, NULL
, ARG_ON_UNIT_ACTIVE
},
182 { "on-unit-inactive", required_argument
, NULL
, ARG_ON_UNIT_INACTIVE
},
183 { "on-calendar", required_argument
, NULL
, ARG_ON_CALENDAR
},
184 { "timer-property", required_argument
, NULL
, ARG_TIMER_PROPERTY
},
185 { "path-property", required_argument
, NULL
, ARG_PATH_PROPERTY
},
186 { "socket-property", required_argument
, NULL
, ARG_SOCKET_PROPERTY
},
187 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
188 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
189 { "collect", no_argument
, NULL
, 'G' },
193 bool with_trigger
= false;
199 while ((c
= getopt_long(argc
, argv
, "+hrH:M:E:p:tPqG", options
, NULL
)) >= 0)
210 case ARG_NO_ASK_PASSWORD
:
211 arg_ask_password
= false;
230 case ARG_DESCRIPTION
:
231 arg_description
= optarg
;
238 case ARG_SEND_SIGHUP
:
239 arg_send_sighup
= true;
243 arg_remain_after_exit
= true;
247 arg_transport
= BUS_TRANSPORT_REMOTE
;
252 arg_transport
= BUS_TRANSPORT_MACHINE
;
256 case ARG_SERVICE_TYPE
:
257 arg_service_type
= optarg
;
261 arg_exec_user
= optarg
;
265 arg_exec_group
= optarg
;
269 r
= parse_nice(optarg
, &arg_nice
);
271 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
277 if (strv_extend(&arg_environment
, optarg
) < 0)
283 if (strv_extend(&arg_property
, optarg
) < 0)
288 case 't': /* --pty */
289 if (IN_SET(arg_stdio
, ARG_STDIO_DIRECT
, ARG_STDIO_AUTO
)) /* if --pipe is already used, upgrade to auto mode */
290 arg_stdio
= ARG_STDIO_AUTO
;
292 arg_stdio
= ARG_STDIO_PTY
;
295 case 'P': /* --pipe */
296 if (IN_SET(arg_stdio
, ARG_STDIO_PTY
, ARG_STDIO_AUTO
)) /* If --pty is already used, upgrade to auto mode */
297 arg_stdio
= ARG_STDIO_AUTO
;
299 arg_stdio
= ARG_STDIO_DIRECT
;
307 r
= add_timer_property("OnActiveSec", optarg
);
315 r
= add_timer_property("OnBootSec", optarg
);
323 r
= add_timer_property("OnStartupSec", optarg
);
330 case ARG_ON_UNIT_ACTIVE
:
331 r
= add_timer_property("OnUnitActiveSec", optarg
);
338 case ARG_ON_UNIT_INACTIVE
:
339 r
= add_timer_property("OnUnitInactiveSec", optarg
);
346 case ARG_ON_CALENDAR
:
347 r
= add_timer_property("OnCalendar", optarg
);
354 case ARG_TIMER_PROPERTY
:
356 if (strv_extend(&arg_timer_property
, optarg
) < 0)
359 with_timer
= with_timer
||
360 !!startswith(optarg
, "OnActiveSec=") ||
361 !!startswith(optarg
, "OnBootSec=") ||
362 !!startswith(optarg
, "OnStartupSec=") ||
363 !!startswith(optarg
, "OnUnitActiveSec=") ||
364 !!startswith(optarg
, "OnUnitInactiveSec=") ||
365 !!startswith(optarg
, "OnCalendar=");
368 case ARG_PATH_PROPERTY
:
370 if (strv_extend(&arg_path_property
, optarg
) < 0)
375 case ARG_SOCKET_PROPERTY
:
377 if (strv_extend(&arg_socket_property
, optarg
) < 0)
391 arg_aggressive_gc
= true;
398 assert_not_reached("Unhandled option");
401 with_trigger
= !!arg_path_property
|| !!arg_socket_property
|| with_timer
;
403 /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
404 if ((int) !!arg_path_property
+ (int) !!arg_socket_property
+ (int) with_timer
> 1) {
405 log_error("Only single trigger (path, socket, timer) unit can be created.");
409 if (arg_stdio
== ARG_STDIO_AUTO
) {
410 /* If we both --pty and --pipe are specified we'll automatically pick --pty if we are connected fully
411 * to a TTY and pick direct fd passing otherwise. This way, we automatically adapt to usage in a shell
412 * pipeline, but we are neatly interactive with tty-level isolation otherwise. */
413 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ?
418 if ((optind
>= argc
) && (!arg_unit
|| !with_trigger
)) {
419 log_error("Command line to execute required.");
423 if (arg_user
&& arg_transport
!= BUS_TRANSPORT_LOCAL
) {
424 log_error("Execution in user context is not supported on non-local systems.");
428 if (arg_scope
&& arg_transport
!= BUS_TRANSPORT_LOCAL
) {
429 log_error("Scope execution is not supported on non-local systems.");
433 if (arg_scope
&& (arg_remain_after_exit
|| arg_service_type
)) {
434 log_error("--remain-after-exit and --service-type= are not supported in --scope mode.");
438 if (arg_stdio
!= ARG_STDIO_NONE
&& (with_trigger
|| arg_scope
)) {
439 log_error("--pty/--pipe is not compatible in timer or --scope mode.");
443 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_transport
== BUS_TRANSPORT_REMOTE
) {
444 log_error("--pty/--pipe is only supported when connecting to the local system or containers.");
448 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_no_block
) {
449 log_error("--pty/--pipe is not compatible with --no-block.");
453 if (arg_scope
&& with_trigger
) {
454 log_error("Path, socket or timer options are not supported in --scope mode.");
458 if (arg_timer_property
&& !with_timer
) {
459 log_error("--timer-property= has no effect without any other timer options.");
465 log_error("--wait may not be combined with --no-block.");
470 log_error("--wait may not be combined with path, socket or timer operations.");
475 log_error("--wait may not be combined with --scope.");
483 static int transient_unit_set_properties(sd_bus_message
*m
, UnitType t
, char **properties
) {
486 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", arg_description
);
488 return bus_log_create_error(r
);
490 if (arg_aggressive_gc
) {
491 r
= sd_bus_message_append(m
, "(sv)", "CollectMode", "s", "inactive-or-failed");
493 return bus_log_create_error(r
);
496 r
= bus_append_unit_property_assignment_many(m
, t
, properties
);
503 static int transient_cgroup_set_properties(sd_bus_message
*m
) {
507 if (!isempty(arg_slice
)) {
508 _cleanup_free_
char *slice
= NULL
;
510 r
= unit_name_mangle_with_suffix(arg_slice
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".slice", &slice
);
512 return log_error_errno(r
, "Failed to mangle name '%s': %m", arg_slice
);
514 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", slice
);
516 return bus_log_create_error(r
);
522 static int transient_kill_set_properties(sd_bus_message
*m
) {
527 if (arg_send_sighup
) {
528 r
= sd_bus_message_append(m
, "(sv)", "SendSIGHUP", "b", arg_send_sighup
);
530 return bus_log_create_error(r
);
536 static int transient_service_set_properties(sd_bus_message
*m
, char **argv
, const char *pty_path
) {
537 bool send_term
= false;
542 r
= transient_unit_set_properties(m
, UNIT_SERVICE
, arg_property
);
546 r
= transient_kill_set_properties(m
);
550 r
= transient_cgroup_set_properties(m
);
554 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
555 r
= sd_bus_message_append(m
, "(sv)", "AddRef", "b", 1);
557 return bus_log_create_error(r
);
560 if (arg_remain_after_exit
) {
561 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit
);
563 return bus_log_create_error(r
);
566 if (arg_service_type
) {
567 r
= sd_bus_message_append(m
, "(sv)", "Type", "s", arg_service_type
);
569 return bus_log_create_error(r
);
573 r
= sd_bus_message_append(m
, "(sv)", "User", "s", arg_exec_user
);
575 return bus_log_create_error(r
);
578 if (arg_exec_group
) {
579 r
= sd_bus_message_append(m
, "(sv)", "Group", "s", arg_exec_group
);
581 return bus_log_create_error(r
);
585 r
= sd_bus_message_append(m
, "(sv)", "Nice", "i", arg_nice
);
587 return bus_log_create_error(r
);
591 r
= sd_bus_message_append(m
,
593 "StandardInput", "s", "tty",
594 "StandardOutput", "s", "tty",
595 "StandardError", "s", "tty",
596 "TTYPath", "s", pty_path
);
598 return bus_log_create_error(r
);
602 } else if (arg_stdio
== ARG_STDIO_DIRECT
) {
603 r
= sd_bus_message_append(m
,
605 "StandardInputFileDescriptor", "h", STDIN_FILENO
,
606 "StandardOutputFileDescriptor", "h", STDOUT_FILENO
,
607 "StandardErrorFileDescriptor", "h", STDERR_FILENO
);
609 return bus_log_create_error(r
);
611 send_term
= isatty(STDIN_FILENO
) || isatty(STDOUT_FILENO
) || isatty(STDERR_FILENO
);
621 n
= strjoina("TERM=", e
);
622 r
= sd_bus_message_append(m
,
624 "Environment", "as", 1, n
);
626 return bus_log_create_error(r
);
630 if (!strv_isempty(arg_environment
)) {
631 r
= sd_bus_message_open_container(m
, 'r', "sv");
633 return bus_log_create_error(r
);
635 r
= sd_bus_message_append(m
, "s", "Environment");
637 return bus_log_create_error(r
);
639 r
= sd_bus_message_open_container(m
, 'v', "as");
641 return bus_log_create_error(r
);
643 r
= sd_bus_message_append_strv(m
, arg_environment
);
645 return bus_log_create_error(r
);
647 r
= sd_bus_message_close_container(m
);
649 return bus_log_create_error(r
);
651 r
= sd_bus_message_close_container(m
);
653 return bus_log_create_error(r
);
658 r
= sd_bus_message_open_container(m
, 'r', "sv");
660 return bus_log_create_error(r
);
662 r
= sd_bus_message_append(m
, "s", "ExecStart");
664 return bus_log_create_error(r
);
666 r
= sd_bus_message_open_container(m
, 'v', "a(sasb)");
668 return bus_log_create_error(r
);
670 r
= sd_bus_message_open_container(m
, 'a', "(sasb)");
672 return bus_log_create_error(r
);
674 r
= sd_bus_message_open_container(m
, 'r', "sasb");
676 return bus_log_create_error(r
);
678 r
= sd_bus_message_append(m
, "s", argv
[0]);
680 return bus_log_create_error(r
);
682 r
= sd_bus_message_append_strv(m
, argv
);
684 return bus_log_create_error(r
);
686 r
= sd_bus_message_append(m
, "b", false);
688 return bus_log_create_error(r
);
690 r
= sd_bus_message_close_container(m
);
692 return bus_log_create_error(r
);
694 r
= sd_bus_message_close_container(m
);
696 return bus_log_create_error(r
);
698 r
= sd_bus_message_close_container(m
);
700 return bus_log_create_error(r
);
702 r
= sd_bus_message_close_container(m
);
704 return bus_log_create_error(r
);
710 static int transient_scope_set_properties(sd_bus_message
*m
) {
715 r
= transient_unit_set_properties(m
, UNIT_SCOPE
, arg_property
);
719 r
= transient_kill_set_properties(m
);
723 r
= transient_cgroup_set_properties(m
);
727 r
= sd_bus_message_append(m
, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached());
729 return bus_log_create_error(r
);
734 static int transient_timer_set_properties(sd_bus_message
*m
) {
739 r
= transient_unit_set_properties(m
, UNIT_TIMER
, arg_timer_property
);
743 /* Automatically clean up our transient timers */
744 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterElapse", "b", false);
746 return bus_log_create_error(r
);
751 static int make_unit_name(sd_bus
*bus
, UnitType t
, char **ret
) {
752 const char *unique
, *id
;
758 assert(t
< _UNIT_TYPE_MAX
);
760 r
= sd_bus_get_unique_name(bus
, &unique
);
764 /* We couldn't get the unique name, which is a pretty
765 * common case if we are connected to systemd
766 * directly. In that case, just pick a random uuid as
769 r
= sd_id128_randomize(&rnd
);
771 return log_error_errno(r
, "Failed to generate random run unit name: %m");
773 if (asprintf(ret
, "run-r" SD_ID128_FORMAT_STR
".%s", SD_ID128_FORMAT_VAL(rnd
), unit_type_to_string(t
)) < 0)
779 /* We managed to get the unique name, then let's use that to
780 * name our transient units. */
782 id
= startswith(unique
, ":1.");
784 log_error("Unique name %s has unexpected format.", unique
);
788 p
= strjoin("run-u", id
, ".", unit_type_to_string(t
));
796 typedef struct RunContext
{
802 /* The exit data of the unit */
804 uint64_t inactive_exit_usec
;
805 uint64_t inactive_enter_usec
;
807 uint64_t cpu_usage_nsec
;
808 uint64_t ip_ingress_bytes
;
809 uint64_t ip_egress_bytes
;
811 uint32_t exit_status
;
814 static void run_context_free(RunContext
*c
) {
817 c
->forward
= pty_forward_free(c
->forward
);
818 c
->match
= sd_bus_slot_unref(c
->match
);
819 c
->bus
= sd_bus_unref(c
->bus
);
820 c
->event
= sd_event_unref(c
->event
);
822 free(c
->active_state
);
826 static void run_context_check_done(RunContext
*c
) {
832 done
= STRPTR_IN_SET(c
->active_state
, "inactive", "failed");
836 if (c
->forward
&& done
) /* If the service is gone, it's time to drain the output */
837 done
= pty_forward_drain(c
->forward
);
840 sd_event_exit(c
->event
, EXIT_SUCCESS
);
843 static int run_context_update(RunContext
*c
, const char *path
) {
845 static const struct bus_properties_map map
[] = {
846 { "ActiveState", "s", NULL
, offsetof(RunContext
, active_state
) },
847 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_exit_usec
) },
848 { "InactiveEnterTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_enter_usec
) },
849 { "Result", "s", NULL
, offsetof(RunContext
, result
) },
850 { "ExecMainCode", "i", NULL
, offsetof(RunContext
, exit_code
) },
851 { "ExecMainStatus", "i", NULL
, offsetof(RunContext
, exit_status
) },
852 { "CPUUsageNSec", "t", NULL
, offsetof(RunContext
, cpu_usage_nsec
) },
853 { "IPIngressBytes", "t", NULL
, offsetof(RunContext
, ip_ingress_bytes
) },
854 { "IPEgressBytes", "t", NULL
, offsetof(RunContext
, ip_egress_bytes
) },
858 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
861 r
= bus_map_all_properties(c
->bus
,
862 "org.freedesktop.systemd1",
870 sd_event_exit(c
->event
, EXIT_FAILURE
);
871 return log_error_errno(r
, "Failed to query unit state: %s", bus_error_message(&error
, r
));
874 run_context_check_done(c
);
878 static int on_properties_changed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
879 RunContext
*c
= userdata
;
884 return run_context_update(c
, sd_bus_message_get_path(m
));
887 static int pty_forward_handler(PTYForward
*f
, int rcode
, void *userdata
) {
888 RunContext
*c
= userdata
;
893 sd_event_exit(c
->event
, EXIT_FAILURE
);
894 return log_error_errno(rcode
, "Error on PTY forwarding logic: %m");
897 run_context_check_done(c
);
901 static int start_transient_service(
906 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
907 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
908 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
909 _cleanup_free_
char *service
= NULL
, *pty_path
= NULL
;
910 _cleanup_close_
int master
= -1;
917 if (arg_stdio
== ARG_STDIO_PTY
) {
919 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
920 master
= posix_openpt(O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NDELAY
);
922 return log_error_errno(errno
, "Failed to acquire pseudo tty: %m");
924 r
= ptsname_malloc(master
, &pty_path
);
926 return log_error_errno(r
, "Failed to determine tty name: %m");
928 if (unlockpt(master
) < 0)
929 return log_error_errno(errno
, "Failed to unlock tty: %m");
931 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
932 _cleanup_(sd_bus_unrefp
) sd_bus
*system_bus
= NULL
;
933 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pty_reply
= NULL
;
936 r
= sd_bus_default_system(&system_bus
);
938 return log_error_errno(r
, "Failed to connect to system bus: %m");
940 r
= sd_bus_call_method(system_bus
,
941 "org.freedesktop.machine1",
942 "/org/freedesktop/machine1",
943 "org.freedesktop.machine1.Manager",
949 log_error("Failed to get machine PTY: %s", bus_error_message(&error
, -r
));
953 r
= sd_bus_message_read(pty_reply
, "hs", &master
, &s
);
955 return bus_log_parse_error(r
);
957 master
= fcntl(master
, F_DUPFD_CLOEXEC
, 3);
959 return log_error_errno(errno
, "Failed to duplicate master fd: %m");
961 pty_path
= strdup(s
);
965 assert_not_reached("Can't allocate tty via ssh");
969 r
= bus_wait_for_jobs_new(bus
, &w
);
971 return log_error_errno(r
, "Could not watch jobs: %m");
975 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".service", &service
);
977 return log_error_errno(r
, "Failed to mangle unit name: %m");
979 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
984 r
= sd_bus_message_new_method_call(
987 "org.freedesktop.systemd1",
988 "/org/freedesktop/systemd1",
989 "org.freedesktop.systemd1.Manager",
990 "StartTransientUnit");
992 return bus_log_create_error(r
);
994 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
996 return bus_log_create_error(r
);
999 r
= sd_bus_message_append(m
, "ss", service
, "fail");
1001 return bus_log_create_error(r
);
1004 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1006 return bus_log_create_error(r
);
1008 r
= transient_service_set_properties(m
, argv
, pty_path
);
1012 r
= sd_bus_message_close_container(m
);
1014 return bus_log_create_error(r
);
1016 /* Auxiliary units */
1017 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1019 return bus_log_create_error(r
);
1021 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1023 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1025 return log_error_errno(r
, "Failed to start transient service unit: %s", bus_error_message(&error
, r
));
1030 r
= sd_bus_message_read(reply
, "o", &object
);
1032 return bus_log_parse_error(r
);
1034 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1040 log_info("Running as unit: %s", service
);
1042 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
1043 _cleanup_(run_context_free
) RunContext c
= {
1044 .cpu_usage_nsec
= NSEC_INFINITY
,
1045 .ip_ingress_bytes
= UINT64_MAX
,
1046 .ip_egress_bytes
= UINT64_MAX
,
1047 .inactive_exit_usec
= USEC_INFINITY
,
1048 .inactive_enter_usec
= USEC_INFINITY
,
1050 _cleanup_free_
char *path
= NULL
;
1052 c
.bus
= sd_bus_ref(bus
);
1054 r
= sd_event_default(&c
.event
);
1056 return log_error_errno(r
, "Failed to get event loop: %m");
1059 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
1060 (void) sd_event_add_signal(c
.event
, NULL
, SIGINT
, NULL
, NULL
);
1061 (void) sd_event_add_signal(c
.event
, NULL
, SIGTERM
, NULL
, NULL
);
1064 log_info("Press ^] three times within 1s to disconnect TTY.");
1066 r
= pty_forward_new(c
.event
, master
, PTY_FORWARD_IGNORE_INITIAL_VHANGUP
, &c
.forward
);
1068 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
1070 pty_forward_set_handler(c
.forward
, pty_forward_handler
, &c
);
1072 /* Make sure to process any TTY events before we process bus events */
1073 (void) pty_forward_set_priority(c
.forward
, SD_EVENT_PRIORITY_IMPORTANT
);
1076 path
= unit_dbus_path_from_name(service
);
1080 r
= sd_bus_match_signal_async(
1083 "org.freedesktop.systemd1",
1085 "org.freedesktop.DBus.Properties",
1086 "PropertiesChanged",
1087 on_properties_changed
, NULL
, &c
);
1089 return log_error_errno(r
, "Failed to request properties changed signal match: %m");
1091 r
= sd_bus_attach_event(bus
, c
.event
, SD_EVENT_PRIORITY_NORMAL
);
1093 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1095 r
= run_context_update(&c
, path
);
1099 r
= sd_event_loop(c
.event
);
1101 return log_error_errno(r
, "Failed to run event loop: %m");
1106 r
= pty_forward_get_last_char(c
.forward
, &last_char
);
1107 if (r
>= 0 && !arg_quiet
&& last_char
!= '\n')
1108 fputc('\n', stdout
);
1111 if (arg_wait
&& !arg_quiet
) {
1113 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, in its
1114 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1116 c
.forward
= pty_forward_free(c
.forward
);
1118 if (!isempty(c
.result
))
1119 log_info("Finished with result: %s", strna(c
.result
));
1121 if (c
.exit_code
== CLD_EXITED
)
1122 log_info("Main processes terminated with: code=%s/status=%i", sigchld_code_to_string(c
.exit_code
), c
.exit_status
);
1123 else if (c
.exit_code
> 0)
1124 log_info("Main processes terminated with: code=%s/status=%s", sigchld_code_to_string(c
.exit_code
), signal_to_string(c
.exit_status
));
1126 if (c
.inactive_enter_usec
> 0 && c
.inactive_enter_usec
!= USEC_INFINITY
&&
1127 c
.inactive_exit_usec
> 0 && c
.inactive_exit_usec
!= USEC_INFINITY
&&
1128 c
.inactive_enter_usec
> c
.inactive_exit_usec
) {
1129 char ts
[FORMAT_TIMESPAN_MAX
];
1130 log_info("Service runtime: %s", format_timespan(ts
, sizeof(ts
), c
.inactive_enter_usec
- c
.inactive_exit_usec
, USEC_PER_MSEC
));
1133 if (c
.cpu_usage_nsec
!= NSEC_INFINITY
) {
1134 char ts
[FORMAT_TIMESPAN_MAX
];
1135 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
));
1138 if (c
.ip_ingress_bytes
!= UINT64_MAX
) {
1139 char bytes
[FORMAT_BYTES_MAX
];
1140 log_info("IP traffic received: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_ingress_bytes
));
1142 if (c
.ip_egress_bytes
!= UINT64_MAX
) {
1143 char bytes
[FORMAT_BYTES_MAX
];
1144 log_info("IP traffic sent: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_egress_bytes
));
1148 /* Try to propagate the service's return value */
1149 if (c
.result
&& STR_IN_SET(c
.result
, "success", "exit-code") && c
.exit_code
== CLD_EXITED
)
1150 *retval
= c
.exit_status
;
1152 *retval
= EXIT_FAILURE
;
1158 static int start_transient_scope(
1162 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1163 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1164 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1165 _cleanup_strv_free_
char **env
= NULL
, **user_env
= NULL
;
1166 _cleanup_free_
char *scope
= NULL
;
1167 const char *object
= NULL
;
1173 r
= bus_wait_for_jobs_new(bus
, &w
);
1178 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".scope", &scope
);
1180 return log_error_errno(r
, "Failed to mangle scope name: %m");
1182 r
= make_unit_name(bus
, UNIT_SCOPE
, &scope
);
1187 r
= sd_bus_message_new_method_call(
1190 "org.freedesktop.systemd1",
1191 "/org/freedesktop/systemd1",
1192 "org.freedesktop.systemd1.Manager",
1193 "StartTransientUnit");
1195 return bus_log_create_error(r
);
1197 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1199 return bus_log_create_error(r
);
1202 r
= sd_bus_message_append(m
, "ss", scope
, "fail");
1204 return bus_log_create_error(r
);
1207 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1209 return bus_log_create_error(r
);
1211 r
= transient_scope_set_properties(m
);
1215 r
= sd_bus_message_close_container(m
);
1217 return bus_log_create_error(r
);
1219 /* Auxiliary units */
1220 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1222 return bus_log_create_error(r
);
1224 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1226 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1228 log_error("Failed to start transient scope unit: %s", bus_error_message(&error
, -r
));
1233 if (setpriority(PRIO_PROCESS
, 0, arg_nice
) < 0)
1234 return log_error_errno(errno
, "Failed to set nice level: %m");
1237 if (arg_exec_group
) {
1240 r
= get_group_creds(&arg_exec_group
, &gid
);
1242 return log_error_errno(r
, "Failed to resolve group %s: %m", arg_exec_group
);
1244 if (setresgid(gid
, gid
, gid
) < 0)
1245 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1248 if (arg_exec_user
) {
1249 const char *home
, *shell
;
1253 r
= get_user_creds_clean(&arg_exec_user
, &uid
, &gid
, &home
, &shell
);
1255 return log_error_errno(r
, "Failed to resolve user %s: %m", arg_exec_user
);
1258 r
= strv_extendf(&user_env
, "HOME=%s", home
);
1264 r
= strv_extendf(&user_env
, "SHELL=%s", shell
);
1269 r
= strv_extendf(&user_env
, "USER=%s", arg_exec_user
);
1273 r
= strv_extendf(&user_env
, "LOGNAME=%s", arg_exec_user
);
1277 if (!arg_exec_group
) {
1278 if (setresgid(gid
, gid
, gid
) < 0)
1279 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1282 if (setresuid(uid
, uid
, uid
) < 0)
1283 return log_error_errno(errno
, "Failed to change UID to " UID_FMT
": %m", uid
);
1286 env
= strv_env_merge(3, environ
, user_env
, arg_environment
);
1290 r
= sd_bus_message_read(reply
, "o", &object
);
1292 return bus_log_parse_error(r
);
1294 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1299 log_info("Running scope as unit: %s", scope
);
1301 execvpe(argv
[0], argv
, env
);
1303 return log_error_errno(errno
, "Failed to execute: %m");
1306 static int start_transient_trigger(
1309 const char *suffix
) {
1311 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1312 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1313 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1314 _cleanup_free_
char *trigger
= NULL
, *service
= NULL
;
1315 const char *object
= NULL
;
1321 r
= bus_wait_for_jobs_new(bus
, &w
);
1326 switch (unit_name_to_type(arg_unit
)) {
1329 service
= strdup(arg_unit
);
1333 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1335 return log_error_errno(r
, "Failed to change unit suffix: %m");
1339 trigger
= strdup(arg_unit
);
1343 r
= unit_name_change_suffix(trigger
, ".service", &service
);
1345 return log_error_errno(r
, "Failed to change unit suffix: %m");
1349 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".service", &service
);
1351 return log_error_errno(r
, "Failed to mangle unit name: %m");
1353 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, suffix
, &trigger
);
1355 return log_error_errno(r
, "Failed to mangle unit name: %m");
1360 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1364 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1366 return log_error_errno(r
, "Failed to change unit suffix: %m");
1369 r
= sd_bus_message_new_method_call(
1372 "org.freedesktop.systemd1",
1373 "/org/freedesktop/systemd1",
1374 "org.freedesktop.systemd1.Manager",
1375 "StartTransientUnit");
1377 return bus_log_create_error(r
);
1379 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1381 return bus_log_create_error(r
);
1384 r
= sd_bus_message_append(m
, "ss", trigger
, "fail");
1386 return bus_log_create_error(r
);
1389 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1391 return bus_log_create_error(r
);
1393 if (streq(suffix
, ".path"))
1394 r
= transient_unit_set_properties(m
, UNIT_PATH
, arg_path_property
);
1395 else if (streq(suffix
, ".socket"))
1396 r
= transient_unit_set_properties(m
, UNIT_SOCKET
, arg_socket_property
);
1397 else if (streq(suffix
, ".timer"))
1398 r
= transient_timer_set_properties(m
);
1400 assert_not_reached("Invalid suffix");
1404 r
= sd_bus_message_close_container(m
);
1406 return bus_log_create_error(r
);
1408 r
= sd_bus_message_open_container(m
, 'a', "(sa(sv))");
1410 return bus_log_create_error(r
);
1412 if (!strv_isempty(argv
)) {
1413 r
= sd_bus_message_open_container(m
, 'r', "sa(sv)");
1415 return bus_log_create_error(r
);
1417 r
= sd_bus_message_append(m
, "s", service
);
1419 return bus_log_create_error(r
);
1421 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1423 return bus_log_create_error(r
);
1425 r
= transient_service_set_properties(m
, argv
, NULL
);
1429 r
= sd_bus_message_close_container(m
);
1431 return bus_log_create_error(r
);
1433 r
= sd_bus_message_close_container(m
);
1435 return bus_log_create_error(r
);
1438 r
= sd_bus_message_close_container(m
);
1440 return bus_log_create_error(r
);
1442 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1444 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1446 log_error("Failed to start transient %s unit: %s", suffix
+ 1, bus_error_message(&error
, -r
));
1450 r
= sd_bus_message_read(reply
, "o", &object
);
1452 return bus_log_parse_error(r
);
1454 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1459 log_info("Running %s as unit: %s", suffix
+ 1, trigger
);
1461 log_info("Will run service as unit: %s", service
);
1467 int main(int argc
, char* argv
[]) {
1468 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
1469 _cleanup_free_
char *description
= NULL
, *command
= NULL
;
1470 int r
, retval
= EXIT_SUCCESS
;
1472 log_parse_environment();
1475 r
= parse_argv(argc
, argv
);
1479 if (argc
> optind
&& arg_transport
== BUS_TRANSPORT_LOCAL
) {
1480 /* Patch in an absolute path */
1482 r
= find_binary(argv
[optind
], &command
);
1484 log_error_errno(r
, "Failed to find executable %s: %m", argv
[optind
]);
1488 argv
[optind
] = command
;
1491 if (!arg_description
) {
1492 description
= strv_join(argv
+ optind
, " ");
1498 if (arg_unit
&& isempty(description
)) {
1499 r
= free_and_strdup(&description
, arg_unit
);
1504 arg_description
= description
;
1507 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the limited direct
1509 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
)
1510 r
= bus_connect_transport(arg_transport
, arg_host
, arg_user
, &bus
);
1512 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, arg_user
, &bus
);
1514 log_error_errno(r
, "Failed to create bus connection: %m");
1519 r
= start_transient_scope(bus
, argv
+ optind
);
1520 else if (arg_path_property
)
1521 r
= start_transient_trigger(bus
, argv
+ optind
, ".path");
1522 else if (arg_socket_property
)
1523 r
= start_transient_trigger(bus
, argv
+ optind
, ".socket");
1524 else if (with_timer
)
1525 r
= start_transient_trigger(bus
, argv
+ optind
, ".timer");
1527 r
= start_transient_service(bus
, argv
+ optind
, &retval
);
1530 strv_free(arg_environment
);
1531 strv_free(arg_property
);
1532 strv_free(arg_path_property
);
1533 strv_free(arg_socket_property
);
1534 strv_free(arg_timer_property
);
1536 return r
< 0 ? EXIT_FAILURE
: retval
;