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 int help(void) {
62 _cleanup_free_
char *link
= NULL
;
65 r
= terminal_urlify_man("systemd-run", "1", &link
);
69 printf("%s [OPTIONS...] {COMMAND} [ARGS...]\n\n"
70 "Run the specified command in a transient scope or service.\n\n"
71 " -h --help Show this help\n"
72 " --version Show package version\n"
73 " --no-ask-password Do not prompt for password\n"
74 " --user Run as user unit\n"
75 " -H --host=[USER@]HOST Operate on remote host\n"
76 " -M --machine=CONTAINER Operate on local container\n"
77 " --scope Run this as scope rather than service\n"
78 " --unit=UNIT Run under the specified unit name\n"
79 " -p --property=NAME=VALUE Set service or scope unit property\n"
80 " --description=TEXT Description for unit\n"
81 " --slice=SLICE Run in the specified slice\n"
82 " --no-block Do not wait until operation finished\n"
83 " -r --remain-after-exit Leave service around until explicitly stopped\n"
84 " --wait Wait until service stopped again\n"
85 " --send-sighup Send SIGHUP when terminating\n"
86 " --service-type=TYPE Service type\n"
87 " --uid=USER Run as system user\n"
88 " --gid=GROUP Run as system group\n"
89 " --nice=NICE Nice level\n"
90 " -E --setenv=NAME=VALUE Set environment\n"
91 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
93 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
94 " -q --quiet Suppress information messages during runtime\n"
95 " -G --collect Unload unit after it ran, even when failed\n\n"
97 " --path-property=NAME=VALUE Set path unit property\n\n"
99 " --socket-property=NAME=VALUE Set socket unit property\n\n"
101 " --on-active=SECONDS Run after SECONDS delay\n"
102 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
103 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
104 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
105 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
106 " --on-calendar=SPEC Realtime timer\n"
107 " --timer-property=NAME=VALUE Set timer unit property\n"
108 "\nSee the %s for details.\n"
109 , program_invocation_short_name
116 static int add_timer_property(const char *name
, const char *val
) {
122 p
= strjoin(name
, "=", val
);
126 if (strv_consume(&arg_timer_property
, p
) < 0)
132 static int parse_argv(int argc
, char *argv
[]) {
151 ARG_ON_UNIT_INACTIVE
,
161 static const struct option options
[] = {
162 { "help", no_argument
, NULL
, 'h' },
163 { "version", no_argument
, NULL
, ARG_VERSION
},
164 { "user", no_argument
, NULL
, ARG_USER
},
165 { "system", no_argument
, NULL
, ARG_SYSTEM
},
166 { "scope", no_argument
, NULL
, ARG_SCOPE
},
167 { "unit", required_argument
, NULL
, ARG_UNIT
},
168 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
169 { "slice", required_argument
, NULL
, ARG_SLICE
},
170 { "remain-after-exit", no_argument
, NULL
, 'r' },
171 { "send-sighup", no_argument
, NULL
, ARG_SEND_SIGHUP
},
172 { "host", required_argument
, NULL
, 'H' },
173 { "machine", required_argument
, NULL
, 'M' },
174 { "service-type", required_argument
, NULL
, ARG_SERVICE_TYPE
},
175 { "wait", no_argument
, NULL
, ARG_WAIT
},
176 { "uid", required_argument
, NULL
, ARG_EXEC_USER
},
177 { "gid", required_argument
, NULL
, ARG_EXEC_GROUP
},
178 { "nice", required_argument
, NULL
, ARG_NICE
},
179 { "setenv", required_argument
, NULL
, 'E' },
180 { "property", required_argument
, NULL
, 'p' },
181 { "tty", no_argument
, NULL
, 't' }, /* deprecated alias */
182 { "pty", no_argument
, NULL
, 't' },
183 { "pipe", no_argument
, NULL
, 'P' },
184 { "quiet", no_argument
, NULL
, 'q' },
185 { "on-active", required_argument
, NULL
, ARG_ON_ACTIVE
},
186 { "on-boot", required_argument
, NULL
, ARG_ON_BOOT
},
187 { "on-startup", required_argument
, NULL
, ARG_ON_STARTUP
},
188 { "on-unit-active", required_argument
, NULL
, ARG_ON_UNIT_ACTIVE
},
189 { "on-unit-inactive", required_argument
, NULL
, ARG_ON_UNIT_INACTIVE
},
190 { "on-calendar", required_argument
, NULL
, ARG_ON_CALENDAR
},
191 { "timer-property", required_argument
, NULL
, ARG_TIMER_PROPERTY
},
192 { "path-property", required_argument
, NULL
, ARG_PATH_PROPERTY
},
193 { "socket-property", required_argument
, NULL
, ARG_SOCKET_PROPERTY
},
194 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
195 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
196 { "collect", no_argument
, NULL
, 'G' },
200 bool with_trigger
= false;
206 while ((c
= getopt_long(argc
, argv
, "+hrH:M:E:p:tPqG", options
, NULL
)) >= 0)
216 case ARG_NO_ASK_PASSWORD
:
217 arg_ask_password
= false;
236 case ARG_DESCRIPTION
:
237 arg_description
= optarg
;
244 case ARG_SEND_SIGHUP
:
245 arg_send_sighup
= true;
249 arg_remain_after_exit
= true;
253 arg_transport
= BUS_TRANSPORT_REMOTE
;
258 arg_transport
= BUS_TRANSPORT_MACHINE
;
262 case ARG_SERVICE_TYPE
:
263 arg_service_type
= optarg
;
267 arg_exec_user
= optarg
;
271 arg_exec_group
= optarg
;
275 r
= parse_nice(optarg
, &arg_nice
);
277 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
283 if (strv_extend(&arg_environment
, optarg
) < 0)
289 if (strv_extend(&arg_property
, optarg
) < 0)
294 case 't': /* --pty */
295 if (IN_SET(arg_stdio
, ARG_STDIO_DIRECT
, ARG_STDIO_AUTO
)) /* if --pipe is already used, upgrade to auto mode */
296 arg_stdio
= ARG_STDIO_AUTO
;
298 arg_stdio
= ARG_STDIO_PTY
;
301 case 'P': /* --pipe */
302 if (IN_SET(arg_stdio
, ARG_STDIO_PTY
, ARG_STDIO_AUTO
)) /* If --pty is already used, upgrade to auto mode */
303 arg_stdio
= ARG_STDIO_AUTO
;
305 arg_stdio
= ARG_STDIO_DIRECT
;
313 r
= add_timer_property("OnActiveSec", optarg
);
321 r
= add_timer_property("OnBootSec", optarg
);
329 r
= add_timer_property("OnStartupSec", optarg
);
336 case ARG_ON_UNIT_ACTIVE
:
337 r
= add_timer_property("OnUnitActiveSec", optarg
);
344 case ARG_ON_UNIT_INACTIVE
:
345 r
= add_timer_property("OnUnitInactiveSec", optarg
);
352 case ARG_ON_CALENDAR
:
353 r
= add_timer_property("OnCalendar", optarg
);
360 case ARG_TIMER_PROPERTY
:
362 if (strv_extend(&arg_timer_property
, optarg
) < 0)
365 with_timer
= with_timer
||
366 !!startswith(optarg
, "OnActiveSec=") ||
367 !!startswith(optarg
, "OnBootSec=") ||
368 !!startswith(optarg
, "OnStartupSec=") ||
369 !!startswith(optarg
, "OnUnitActiveSec=") ||
370 !!startswith(optarg
, "OnUnitInactiveSec=") ||
371 !!startswith(optarg
, "OnCalendar=");
374 case ARG_PATH_PROPERTY
:
376 if (strv_extend(&arg_path_property
, optarg
) < 0)
381 case ARG_SOCKET_PROPERTY
:
383 if (strv_extend(&arg_socket_property
, optarg
) < 0)
397 arg_aggressive_gc
= true;
404 assert_not_reached("Unhandled option");
407 with_trigger
= !!arg_path_property
|| !!arg_socket_property
|| with_timer
;
409 /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
410 if ((int) !!arg_path_property
+ (int) !!arg_socket_property
+ (int) with_timer
> 1) {
411 log_error("Only single trigger (path, socket, timer) unit can be created.");
415 if (arg_stdio
== ARG_STDIO_AUTO
) {
416 /* If we both --pty and --pipe are specified we'll automatically pick --pty if we are connected fully
417 * to a TTY and pick direct fd passing otherwise. This way, we automatically adapt to usage in a shell
418 * pipeline, but we are neatly interactive with tty-level isolation otherwise. */
419 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ?
424 if ((optind
>= argc
) && (!arg_unit
|| !with_trigger
)) {
425 log_error("Command line to execute required.");
429 if (arg_user
&& arg_transport
!= BUS_TRANSPORT_LOCAL
) {
430 log_error("Execution in user context is not supported on non-local systems.");
434 if (arg_scope
&& arg_transport
!= BUS_TRANSPORT_LOCAL
) {
435 log_error("Scope execution is not supported on non-local systems.");
439 if (arg_scope
&& (arg_remain_after_exit
|| arg_service_type
)) {
440 log_error("--remain-after-exit and --service-type= are not supported in --scope mode.");
444 if (arg_stdio
!= ARG_STDIO_NONE
&& (with_trigger
|| arg_scope
)) {
445 log_error("--pty/--pipe is not compatible in timer or --scope mode.");
449 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_transport
== BUS_TRANSPORT_REMOTE
) {
450 log_error("--pty/--pipe is only supported when connecting to the local system or containers.");
454 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_no_block
) {
455 log_error("--pty/--pipe is not compatible with --no-block.");
459 if (arg_scope
&& with_trigger
) {
460 log_error("Path, socket or timer options are not supported in --scope mode.");
464 if (arg_timer_property
&& !with_timer
) {
465 log_error("--timer-property= has no effect without any other timer options.");
471 log_error("--wait may not be combined with --no-block.");
476 log_error("--wait may not be combined with path, socket or timer operations.");
481 log_error("--wait may not be combined with --scope.");
489 static int transient_unit_set_properties(sd_bus_message
*m
, UnitType t
, char **properties
) {
492 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", arg_description
);
494 return bus_log_create_error(r
);
496 if (arg_aggressive_gc
) {
497 r
= sd_bus_message_append(m
, "(sv)", "CollectMode", "s", "inactive-or-failed");
499 return bus_log_create_error(r
);
502 r
= bus_append_unit_property_assignment_many(m
, t
, properties
);
509 static int transient_cgroup_set_properties(sd_bus_message
*m
) {
513 if (!isempty(arg_slice
)) {
514 _cleanup_free_
char *slice
= NULL
;
516 r
= unit_name_mangle_with_suffix(arg_slice
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".slice", &slice
);
518 return log_error_errno(r
, "Failed to mangle name '%s': %m", arg_slice
);
520 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", slice
);
522 return bus_log_create_error(r
);
528 static int transient_kill_set_properties(sd_bus_message
*m
) {
533 if (arg_send_sighup
) {
534 r
= sd_bus_message_append(m
, "(sv)", "SendSIGHUP", "b", arg_send_sighup
);
536 return bus_log_create_error(r
);
542 static int transient_service_set_properties(sd_bus_message
*m
, char **argv
, const char *pty_path
) {
543 bool send_term
= false;
548 r
= transient_unit_set_properties(m
, UNIT_SERVICE
, arg_property
);
552 r
= transient_kill_set_properties(m
);
556 r
= transient_cgroup_set_properties(m
);
560 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
561 r
= sd_bus_message_append(m
, "(sv)", "AddRef", "b", 1);
563 return bus_log_create_error(r
);
566 if (arg_remain_after_exit
) {
567 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit
);
569 return bus_log_create_error(r
);
572 if (arg_service_type
) {
573 r
= sd_bus_message_append(m
, "(sv)", "Type", "s", arg_service_type
);
575 return bus_log_create_error(r
);
579 r
= sd_bus_message_append(m
, "(sv)", "User", "s", arg_exec_user
);
581 return bus_log_create_error(r
);
584 if (arg_exec_group
) {
585 r
= sd_bus_message_append(m
, "(sv)", "Group", "s", arg_exec_group
);
587 return bus_log_create_error(r
);
591 r
= sd_bus_message_append(m
, "(sv)", "Nice", "i", arg_nice
);
593 return bus_log_create_error(r
);
597 r
= sd_bus_message_append(m
,
599 "StandardInput", "s", "tty",
600 "StandardOutput", "s", "tty",
601 "StandardError", "s", "tty",
602 "TTYPath", "s", pty_path
);
604 return bus_log_create_error(r
);
608 } else if (arg_stdio
== ARG_STDIO_DIRECT
) {
609 r
= sd_bus_message_append(m
,
611 "StandardInputFileDescriptor", "h", STDIN_FILENO
,
612 "StandardOutputFileDescriptor", "h", STDOUT_FILENO
,
613 "StandardErrorFileDescriptor", "h", STDERR_FILENO
);
615 return bus_log_create_error(r
);
617 send_term
= isatty(STDIN_FILENO
) || isatty(STDOUT_FILENO
) || isatty(STDERR_FILENO
);
627 n
= strjoina("TERM=", e
);
628 r
= sd_bus_message_append(m
,
630 "Environment", "as", 1, n
);
632 return bus_log_create_error(r
);
636 if (!strv_isempty(arg_environment
)) {
637 r
= sd_bus_message_open_container(m
, 'r', "sv");
639 return bus_log_create_error(r
);
641 r
= sd_bus_message_append(m
, "s", "Environment");
643 return bus_log_create_error(r
);
645 r
= sd_bus_message_open_container(m
, 'v', "as");
647 return bus_log_create_error(r
);
649 r
= sd_bus_message_append_strv(m
, arg_environment
);
651 return bus_log_create_error(r
);
653 r
= sd_bus_message_close_container(m
);
655 return bus_log_create_error(r
);
657 r
= sd_bus_message_close_container(m
);
659 return bus_log_create_error(r
);
664 r
= sd_bus_message_open_container(m
, 'r', "sv");
666 return bus_log_create_error(r
);
668 r
= sd_bus_message_append(m
, "s", "ExecStart");
670 return bus_log_create_error(r
);
672 r
= sd_bus_message_open_container(m
, 'v', "a(sasb)");
674 return bus_log_create_error(r
);
676 r
= sd_bus_message_open_container(m
, 'a', "(sasb)");
678 return bus_log_create_error(r
);
680 r
= sd_bus_message_open_container(m
, 'r', "sasb");
682 return bus_log_create_error(r
);
684 r
= sd_bus_message_append(m
, "s", argv
[0]);
686 return bus_log_create_error(r
);
688 r
= sd_bus_message_append_strv(m
, argv
);
690 return bus_log_create_error(r
);
692 r
= sd_bus_message_append(m
, "b", false);
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
);
704 r
= sd_bus_message_close_container(m
);
706 return bus_log_create_error(r
);
708 r
= sd_bus_message_close_container(m
);
710 return bus_log_create_error(r
);
716 static int transient_scope_set_properties(sd_bus_message
*m
) {
721 r
= transient_unit_set_properties(m
, UNIT_SCOPE
, arg_property
);
725 r
= transient_kill_set_properties(m
);
729 r
= transient_cgroup_set_properties(m
);
733 r
= sd_bus_message_append(m
, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached());
735 return bus_log_create_error(r
);
740 static int transient_timer_set_properties(sd_bus_message
*m
) {
745 r
= transient_unit_set_properties(m
, UNIT_TIMER
, arg_timer_property
);
749 /* Automatically clean up our transient timers */
750 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterElapse", "b", false);
752 return bus_log_create_error(r
);
757 static int make_unit_name(sd_bus
*bus
, UnitType t
, char **ret
) {
758 const char *unique
, *id
;
764 assert(t
< _UNIT_TYPE_MAX
);
766 r
= sd_bus_get_unique_name(bus
, &unique
);
770 /* We couldn't get the unique name, which is a pretty
771 * common case if we are connected to systemd
772 * directly. In that case, just pick a random uuid as
775 r
= sd_id128_randomize(&rnd
);
777 return log_error_errno(r
, "Failed to generate random run unit name: %m");
779 if (asprintf(ret
, "run-r" SD_ID128_FORMAT_STR
".%s", SD_ID128_FORMAT_VAL(rnd
), unit_type_to_string(t
)) < 0)
785 /* We managed to get the unique name, then let's use that to
786 * name our transient units. */
788 id
= startswith(unique
, ":1.");
790 log_error("Unique name %s has unexpected format.", unique
);
794 p
= strjoin("run-u", id
, ".", unit_type_to_string(t
));
802 typedef struct RunContext
{
808 /* The exit data of the unit */
810 uint64_t inactive_exit_usec
;
811 uint64_t inactive_enter_usec
;
813 uint64_t cpu_usage_nsec
;
814 uint64_t ip_ingress_bytes
;
815 uint64_t ip_egress_bytes
;
817 uint32_t exit_status
;
820 static void run_context_free(RunContext
*c
) {
823 c
->forward
= pty_forward_free(c
->forward
);
824 c
->match
= sd_bus_slot_unref(c
->match
);
825 c
->bus
= sd_bus_unref(c
->bus
);
826 c
->event
= sd_event_unref(c
->event
);
828 free(c
->active_state
);
832 static void run_context_check_done(RunContext
*c
) {
838 done
= STRPTR_IN_SET(c
->active_state
, "inactive", "failed");
842 if (c
->forward
&& done
) /* If the service is gone, it's time to drain the output */
843 done
= pty_forward_drain(c
->forward
);
846 sd_event_exit(c
->event
, EXIT_SUCCESS
);
849 static int run_context_update(RunContext
*c
, const char *path
) {
851 static const struct bus_properties_map map
[] = {
852 { "ActiveState", "s", NULL
, offsetof(RunContext
, active_state
) },
853 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_exit_usec
) },
854 { "InactiveEnterTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_enter_usec
) },
855 { "Result", "s", NULL
, offsetof(RunContext
, result
) },
856 { "ExecMainCode", "i", NULL
, offsetof(RunContext
, exit_code
) },
857 { "ExecMainStatus", "i", NULL
, offsetof(RunContext
, exit_status
) },
858 { "CPUUsageNSec", "t", NULL
, offsetof(RunContext
, cpu_usage_nsec
) },
859 { "IPIngressBytes", "t", NULL
, offsetof(RunContext
, ip_ingress_bytes
) },
860 { "IPEgressBytes", "t", NULL
, offsetof(RunContext
, ip_egress_bytes
) },
864 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
867 r
= bus_map_all_properties(c
->bus
,
868 "org.freedesktop.systemd1",
876 sd_event_exit(c
->event
, EXIT_FAILURE
);
877 return log_error_errno(r
, "Failed to query unit state: %s", bus_error_message(&error
, r
));
880 run_context_check_done(c
);
884 static int on_properties_changed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
885 RunContext
*c
= userdata
;
890 return run_context_update(c
, sd_bus_message_get_path(m
));
893 static int pty_forward_handler(PTYForward
*f
, int rcode
, void *userdata
) {
894 RunContext
*c
= userdata
;
899 sd_event_exit(c
->event
, EXIT_FAILURE
);
900 return log_error_errno(rcode
, "Error on PTY forwarding logic: %m");
903 run_context_check_done(c
);
907 static int start_transient_service(
912 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
913 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
914 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
915 _cleanup_free_
char *service
= NULL
, *pty_path
= NULL
;
916 _cleanup_close_
int master
= -1;
923 if (arg_stdio
== ARG_STDIO_PTY
) {
925 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
926 master
= posix_openpt(O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NONBLOCK
);
928 return log_error_errno(errno
, "Failed to acquire pseudo tty: %m");
930 r
= ptsname_malloc(master
, &pty_path
);
932 return log_error_errno(r
, "Failed to determine tty name: %m");
934 if (unlockpt(master
) < 0)
935 return log_error_errno(errno
, "Failed to unlock tty: %m");
937 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
938 _cleanup_(sd_bus_unrefp
) sd_bus
*system_bus
= NULL
;
939 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pty_reply
= NULL
;
942 r
= sd_bus_default_system(&system_bus
);
944 return log_error_errno(r
, "Failed to connect to system bus: %m");
946 r
= sd_bus_call_method(system_bus
,
947 "org.freedesktop.machine1",
948 "/org/freedesktop/machine1",
949 "org.freedesktop.machine1.Manager",
955 return log_error_errno(r
, "Failed to get machine PTY: %s", bus_error_message(&error
, -r
));
957 r
= sd_bus_message_read(pty_reply
, "hs", &master
, &s
);
959 return bus_log_parse_error(r
);
961 master
= fcntl(master
, F_DUPFD_CLOEXEC
, 3);
963 return log_error_errno(errno
, "Failed to duplicate master fd: %m");
965 pty_path
= strdup(s
);
969 assert_not_reached("Can't allocate tty via ssh");
973 r
= bus_wait_for_jobs_new(bus
, &w
);
975 return log_error_errno(r
, "Could not watch jobs: %m");
979 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".service", &service
);
981 return log_error_errno(r
, "Failed to mangle unit name: %m");
983 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
988 r
= sd_bus_message_new_method_call(
991 "org.freedesktop.systemd1",
992 "/org/freedesktop/systemd1",
993 "org.freedesktop.systemd1.Manager",
994 "StartTransientUnit");
996 return bus_log_create_error(r
);
998 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1000 return bus_log_create_error(r
);
1003 r
= sd_bus_message_append(m
, "ss", service
, "fail");
1005 return bus_log_create_error(r
);
1008 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1010 return bus_log_create_error(r
);
1012 r
= transient_service_set_properties(m
, argv
, pty_path
);
1016 r
= sd_bus_message_close_container(m
);
1018 return bus_log_create_error(r
);
1020 /* Auxiliary units */
1021 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1023 return bus_log_create_error(r
);
1025 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1027 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1029 return log_error_errno(r
, "Failed to start transient service unit: %s", bus_error_message(&error
, r
));
1034 r
= sd_bus_message_read(reply
, "o", &object
);
1036 return bus_log_parse_error(r
);
1038 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1044 log_info("Running as unit: %s", service
);
1046 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
1047 _cleanup_(run_context_free
) RunContext c
= {
1048 .cpu_usage_nsec
= NSEC_INFINITY
,
1049 .ip_ingress_bytes
= UINT64_MAX
,
1050 .ip_egress_bytes
= UINT64_MAX
,
1051 .inactive_exit_usec
= USEC_INFINITY
,
1052 .inactive_enter_usec
= USEC_INFINITY
,
1054 _cleanup_free_
char *path
= NULL
;
1056 c
.bus
= sd_bus_ref(bus
);
1058 r
= sd_event_default(&c
.event
);
1060 return log_error_errno(r
, "Failed to get event loop: %m");
1063 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
1064 (void) sd_event_add_signal(c
.event
, NULL
, SIGINT
, NULL
, NULL
);
1065 (void) sd_event_add_signal(c
.event
, NULL
, SIGTERM
, NULL
, NULL
);
1068 log_info("Press ^] three times within 1s to disconnect TTY.");
1070 r
= pty_forward_new(c
.event
, master
, PTY_FORWARD_IGNORE_INITIAL_VHANGUP
, &c
.forward
);
1072 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
1074 pty_forward_set_handler(c
.forward
, pty_forward_handler
, &c
);
1076 /* Make sure to process any TTY events before we process bus events */
1077 (void) pty_forward_set_priority(c
.forward
, SD_EVENT_PRIORITY_IMPORTANT
);
1080 path
= unit_dbus_path_from_name(service
);
1084 r
= sd_bus_match_signal_async(
1087 "org.freedesktop.systemd1",
1089 "org.freedesktop.DBus.Properties",
1090 "PropertiesChanged",
1091 on_properties_changed
, NULL
, &c
);
1093 return log_error_errno(r
, "Failed to request properties changed signal match: %m");
1095 r
= sd_bus_attach_event(bus
, c
.event
, SD_EVENT_PRIORITY_NORMAL
);
1097 return log_error_errno(r
, "Failed to attach bus to event loop: %m");
1099 r
= run_context_update(&c
, path
);
1103 r
= sd_event_loop(c
.event
);
1105 return log_error_errno(r
, "Failed to run event loop: %m");
1110 r
= pty_forward_get_last_char(c
.forward
, &last_char
);
1111 if (r
>= 0 && !arg_quiet
&& last_char
!= '\n')
1112 fputc('\n', stdout
);
1115 if (arg_wait
&& !arg_quiet
) {
1117 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, in its
1118 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1120 c
.forward
= pty_forward_free(c
.forward
);
1122 if (!isempty(c
.result
))
1123 log_info("Finished with result: %s", strna(c
.result
));
1125 if (c
.exit_code
== CLD_EXITED
)
1126 log_info("Main processes terminated with: code=%s/status=%i", sigchld_code_to_string(c
.exit_code
), c
.exit_status
);
1127 else if (c
.exit_code
> 0)
1128 log_info("Main processes terminated with: code=%s/status=%s", sigchld_code_to_string(c
.exit_code
), signal_to_string(c
.exit_status
));
1130 if (c
.inactive_enter_usec
> 0 && c
.inactive_enter_usec
!= USEC_INFINITY
&&
1131 c
.inactive_exit_usec
> 0 && c
.inactive_exit_usec
!= USEC_INFINITY
&&
1132 c
.inactive_enter_usec
> c
.inactive_exit_usec
) {
1133 char ts
[FORMAT_TIMESPAN_MAX
];
1134 log_info("Service runtime: %s", format_timespan(ts
, sizeof(ts
), c
.inactive_enter_usec
- c
.inactive_exit_usec
, USEC_PER_MSEC
));
1137 if (c
.cpu_usage_nsec
!= NSEC_INFINITY
) {
1138 char ts
[FORMAT_TIMESPAN_MAX
];
1139 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
));
1142 if (c
.ip_ingress_bytes
!= UINT64_MAX
) {
1143 char bytes
[FORMAT_BYTES_MAX
];
1144 log_info("IP traffic received: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_ingress_bytes
));
1146 if (c
.ip_egress_bytes
!= UINT64_MAX
) {
1147 char bytes
[FORMAT_BYTES_MAX
];
1148 log_info("IP traffic sent: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_egress_bytes
));
1152 /* Try to propagate the service's return value */
1153 if (c
.result
&& STR_IN_SET(c
.result
, "success", "exit-code") && c
.exit_code
== CLD_EXITED
)
1154 *retval
= c
.exit_status
;
1156 *retval
= EXIT_FAILURE
;
1162 static int start_transient_scope(
1166 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1167 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1168 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1169 _cleanup_strv_free_
char **env
= NULL
, **user_env
= NULL
;
1170 _cleanup_free_
char *scope
= NULL
;
1171 const char *object
= NULL
;
1177 r
= bus_wait_for_jobs_new(bus
, &w
);
1182 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".scope", &scope
);
1184 return log_error_errno(r
, "Failed to mangle scope name: %m");
1186 r
= make_unit_name(bus
, UNIT_SCOPE
, &scope
);
1191 r
= sd_bus_message_new_method_call(
1194 "org.freedesktop.systemd1",
1195 "/org/freedesktop/systemd1",
1196 "org.freedesktop.systemd1.Manager",
1197 "StartTransientUnit");
1199 return bus_log_create_error(r
);
1201 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1203 return bus_log_create_error(r
);
1206 r
= sd_bus_message_append(m
, "ss", scope
, "fail");
1208 return bus_log_create_error(r
);
1211 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1213 return bus_log_create_error(r
);
1215 r
= transient_scope_set_properties(m
);
1219 r
= sd_bus_message_close_container(m
);
1221 return bus_log_create_error(r
);
1223 /* Auxiliary units */
1224 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1226 return bus_log_create_error(r
);
1228 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1230 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1232 return log_error_errno(r
, "Failed to start transient scope unit: %s", bus_error_message(&error
, -r
));
1235 if (setpriority(PRIO_PROCESS
, 0, arg_nice
) < 0)
1236 return log_error_errno(errno
, "Failed to set nice level: %m");
1239 if (arg_exec_group
) {
1242 r
= get_group_creds(&arg_exec_group
, &gid
, 0);
1244 return log_error_errno(r
, "Failed to resolve group %s: %m", arg_exec_group
);
1246 if (setresgid(gid
, gid
, gid
) < 0)
1247 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1250 if (arg_exec_user
) {
1251 const char *home
, *shell
;
1255 r
= get_user_creds(&arg_exec_user
, &uid
, &gid
, &home
, &shell
, USER_CREDS_CLEAN
|USER_CREDS_PREFER_NSS
);
1257 return log_error_errno(r
, "Failed to resolve user %s: %m", arg_exec_user
);
1260 r
= strv_extendf(&user_env
, "HOME=%s", home
);
1266 r
= strv_extendf(&user_env
, "SHELL=%s", shell
);
1271 r
= strv_extendf(&user_env
, "USER=%s", arg_exec_user
);
1275 r
= strv_extendf(&user_env
, "LOGNAME=%s", arg_exec_user
);
1279 if (!arg_exec_group
) {
1280 if (setresgid(gid
, gid
, gid
) < 0)
1281 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1284 if (setresuid(uid
, uid
, uid
) < 0)
1285 return log_error_errno(errno
, "Failed to change UID to " UID_FMT
": %m", uid
);
1288 env
= strv_env_merge(3, environ
, user_env
, arg_environment
);
1292 r
= sd_bus_message_read(reply
, "o", &object
);
1294 return bus_log_parse_error(r
);
1296 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1301 log_info("Running scope as unit: %s", scope
);
1303 execvpe(argv
[0], argv
, env
);
1305 return log_error_errno(errno
, "Failed to execute: %m");
1308 static int start_transient_trigger(
1311 const char *suffix
) {
1313 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1314 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1315 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1316 _cleanup_free_
char *trigger
= NULL
, *service
= NULL
;
1317 const char *object
= NULL
;
1323 r
= bus_wait_for_jobs_new(bus
, &w
);
1328 switch (unit_name_to_type(arg_unit
)) {
1331 service
= strdup(arg_unit
);
1335 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1337 return log_error_errno(r
, "Failed to change unit suffix: %m");
1341 trigger
= strdup(arg_unit
);
1345 r
= unit_name_change_suffix(trigger
, ".service", &service
);
1347 return log_error_errno(r
, "Failed to change unit suffix: %m");
1351 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, ".service", &service
);
1353 return log_error_errno(r
, "Failed to mangle unit name: %m");
1355 r
= unit_name_mangle_with_suffix(arg_unit
, arg_quiet
? 0 : UNIT_NAME_MANGLE_WARN
, suffix
, &trigger
);
1357 return log_error_errno(r
, "Failed to mangle unit name: %m");
1362 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1366 r
= unit_name_change_suffix(service
, suffix
, &trigger
);
1368 return log_error_errno(r
, "Failed to change unit suffix: %m");
1371 r
= sd_bus_message_new_method_call(
1374 "org.freedesktop.systemd1",
1375 "/org/freedesktop/systemd1",
1376 "org.freedesktop.systemd1.Manager",
1377 "StartTransientUnit");
1379 return bus_log_create_error(r
);
1381 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1383 return bus_log_create_error(r
);
1386 r
= sd_bus_message_append(m
, "ss", trigger
, "fail");
1388 return bus_log_create_error(r
);
1391 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1393 return bus_log_create_error(r
);
1395 if (streq(suffix
, ".path"))
1396 r
= transient_unit_set_properties(m
, UNIT_PATH
, arg_path_property
);
1397 else if (streq(suffix
, ".socket"))
1398 r
= transient_unit_set_properties(m
, UNIT_SOCKET
, arg_socket_property
);
1399 else if (streq(suffix
, ".timer"))
1400 r
= transient_timer_set_properties(m
);
1402 assert_not_reached("Invalid suffix");
1406 r
= sd_bus_message_close_container(m
);
1408 return bus_log_create_error(r
);
1410 r
= sd_bus_message_open_container(m
, 'a', "(sa(sv))");
1412 return bus_log_create_error(r
);
1414 if (!strv_isempty(argv
)) {
1415 r
= sd_bus_message_open_container(m
, 'r', "sa(sv)");
1417 return bus_log_create_error(r
);
1419 r
= sd_bus_message_append(m
, "s", service
);
1421 return bus_log_create_error(r
);
1423 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1425 return bus_log_create_error(r
);
1427 r
= transient_service_set_properties(m
, argv
, NULL
);
1431 r
= sd_bus_message_close_container(m
);
1433 return bus_log_create_error(r
);
1435 r
= sd_bus_message_close_container(m
);
1437 return bus_log_create_error(r
);
1440 r
= sd_bus_message_close_container(m
);
1442 return bus_log_create_error(r
);
1444 polkit_agent_open_if_enabled(arg_transport
, arg_ask_password
);
1446 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1448 return log_error_errno(r
, "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
;