2 This file is part of systemd.
4 Copyright 2013 Lennart Poettering
6 systemd is free software; you can redistribute it and/or modify it
7 under the terms of the GNU Lesser General Public License as published by
8 the Free Software Foundation; either version 2.1 of the License, or
9 (at your option) any later version.
11 systemd is distributed in the hope that it will be useful, but
12 WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 Lesser General Public License for more details.
16 You should have received a copy of the GNU Lesser General Public License
17 along with systemd; If not, see <http://www.gnu.org/licenses/>.
26 #include "alloc-util.h"
27 #include "bus-error.h"
28 #include "bus-unit-util.h"
30 #include "calendarspec.h"
33 #include "format-util.h"
34 #include "parse-util.h"
35 #include "path-util.h"
36 #include "process-util.h"
38 #include "signal-util.h"
39 #include "spawn-polkit-agent.h"
41 #include "terminal-util.h"
42 #include "unit-name.h"
43 #include "user-util.h"
45 static bool arg_ask_password
= true;
46 static bool arg_scope
= false;
47 static bool arg_remain_after_exit
= false;
48 static bool arg_no_block
= false;
49 static bool arg_wait
= false;
50 static const char *arg_unit
= NULL
;
51 static const char *arg_description
= NULL
;
52 static const char *arg_slice
= NULL
;
53 static bool arg_send_sighup
= false;
54 static BusTransport arg_transport
= BUS_TRANSPORT_LOCAL
;
55 static const char *arg_host
= NULL
;
56 static bool arg_user
= false;
57 static const char *arg_service_type
= NULL
;
58 static const char *arg_exec_user
= NULL
;
59 static const char *arg_exec_group
= NULL
;
60 static int arg_nice
= 0;
61 static bool arg_nice_set
= false;
62 static char **arg_environment
= NULL
;
63 static char **arg_property
= NULL
;
65 ARG_STDIO_NONE
, /* The default, as it is for normal services, stdin connected to /dev/null, and stdout+stderr to the journal */
66 ARG_STDIO_PTY
, /* Interactive behaviour, requested by --pty: we allocate a pty and connect it to the TTY we are invoked from */
67 ARG_STDIO_DIRECT
, /* Directly pass our stdin/stdout/stderr to the activated service, useful for usage in shell pipelines, requested by --pipe */
68 ARG_STDIO_AUTO
, /* If --pipe and --pty are used together we use --pty when invoked on a TTY, and --pipe otherwise */
69 } arg_stdio
= ARG_STDIO_NONE
;
70 static usec_t arg_on_active
= 0;
71 static usec_t arg_on_boot
= 0;
72 static usec_t arg_on_startup
= 0;
73 static usec_t arg_on_unit_active
= 0;
74 static usec_t arg_on_unit_inactive
= 0;
75 static const char *arg_on_calendar
= NULL
;
76 static char **arg_timer_property
= NULL
;
77 static bool arg_quiet
= false;
79 static void polkit_agent_open_if_enabled(void) {
81 /* Open the polkit agent as a child process if necessary */
82 if (!arg_ask_password
)
85 if (arg_transport
!= BUS_TRANSPORT_LOCAL
)
91 static void help(void) {
92 printf("%s [OPTIONS...] {COMMAND} [ARGS...]\n\n"
93 "Run the specified command in a transient scope or service.\n\n"
94 " -h --help Show this help\n"
95 " --version Show package version\n"
96 " --no-ask-password Do not prompt for password\n"
97 " --user Run as user unit\n"
98 " -H --host=[USER@]HOST Operate on remote host\n"
99 " -M --machine=CONTAINER Operate on local container\n"
100 " --scope Run this as scope rather than service\n"
101 " --unit=UNIT Run under the specified unit name\n"
102 " -p --property=NAME=VALUE Set service or scope unit property\n"
103 " --description=TEXT Description for unit\n"
104 " --slice=SLICE Run in the specified slice\n"
105 " --no-block Do not wait until operation finished\n"
106 " -r --remain-after-exit Leave service around until explicitly stopped\n"
107 " --wait Wait until service stopped again\n"
108 " --send-sighup Send SIGHUP when terminating\n"
109 " --service-type=TYPE Service type\n"
110 " --uid=USER Run as system user\n"
111 " --gid=GROUP Run as system group\n"
112 " --nice=NICE Nice level\n"
113 " -E --setenv=NAME=VALUE Set environment\n"
114 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
116 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
117 " -q --quiet Suppress information messages during runtime\n\n"
119 " --on-active=SECONDS Run after SECONDS delay\n"
120 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
121 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
122 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
123 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
124 " --on-calendar=SPEC Realtime timer\n"
125 " --timer-property=NAME=VALUE Set timer unit property\n"
126 , program_invocation_short_name
);
129 static bool with_timer(void) {
130 return arg_on_active
|| arg_on_boot
|| arg_on_startup
|| arg_on_unit_active
|| arg_on_unit_inactive
|| arg_on_calendar
;
133 static int parse_argv(int argc
, char *argv
[]) {
152 ARG_ON_UNIT_INACTIVE
,
160 static const struct option options
[] = {
161 { "help", no_argument
, NULL
, 'h' },
162 { "version", no_argument
, NULL
, ARG_VERSION
},
163 { "user", no_argument
, NULL
, ARG_USER
},
164 { "system", no_argument
, NULL
, ARG_SYSTEM
},
165 { "scope", no_argument
, NULL
, ARG_SCOPE
},
166 { "unit", required_argument
, NULL
, ARG_UNIT
},
167 { "description", required_argument
, NULL
, ARG_DESCRIPTION
},
168 { "slice", required_argument
, NULL
, ARG_SLICE
},
169 { "remain-after-exit", no_argument
, NULL
, 'r' },
170 { "send-sighup", no_argument
, NULL
, ARG_SEND_SIGHUP
},
171 { "host", required_argument
, NULL
, 'H' },
172 { "machine", required_argument
, NULL
, 'M' },
173 { "service-type", required_argument
, NULL
, ARG_SERVICE_TYPE
},
174 { "wait", no_argument
, NULL
, ARG_WAIT
},
175 { "uid", required_argument
, NULL
, ARG_EXEC_USER
},
176 { "gid", required_argument
, NULL
, ARG_EXEC_GROUP
},
177 { "nice", required_argument
, NULL
, ARG_NICE
},
178 { "setenv", required_argument
, NULL
, 'E' },
179 { "property", required_argument
, NULL
, 'p' },
180 { "tty", no_argument
, NULL
, 't' }, /* deprecated alias */
181 { "pty", no_argument
, NULL
, 't' },
182 { "pipe", no_argument
, NULL
, 'P' },
183 { "quiet", no_argument
, NULL
, 'q' },
184 { "on-active", required_argument
, NULL
, ARG_ON_ACTIVE
},
185 { "on-boot", required_argument
, NULL
, ARG_ON_BOOT
},
186 { "on-startup", required_argument
, NULL
, ARG_ON_STARTUP
},
187 { "on-unit-active", required_argument
, NULL
, ARG_ON_UNIT_ACTIVE
},
188 { "on-unit-inactive", required_argument
, NULL
, ARG_ON_UNIT_INACTIVE
},
189 { "on-calendar", required_argument
, NULL
, ARG_ON_CALENDAR
},
190 { "timer-property", required_argument
, NULL
, ARG_TIMER_PROPERTY
},
191 { "no-block", no_argument
, NULL
, ARG_NO_BLOCK
},
192 { "no-ask-password", no_argument
, NULL
, ARG_NO_ASK_PASSWORD
},
201 while ((c
= getopt_long(argc
, argv
, "+hrH:M:E:p:tPq", options
, NULL
)) >= 0)
212 case ARG_NO_ASK_PASSWORD
:
213 arg_ask_password
= false;
232 case ARG_DESCRIPTION
:
233 arg_description
= optarg
;
240 case ARG_SEND_SIGHUP
:
241 arg_send_sighup
= true;
245 arg_remain_after_exit
= true;
249 arg_transport
= BUS_TRANSPORT_REMOTE
;
254 arg_transport
= BUS_TRANSPORT_MACHINE
;
258 case ARG_SERVICE_TYPE
:
259 arg_service_type
= optarg
;
263 arg_exec_user
= optarg
;
267 arg_exec_group
= optarg
;
271 r
= parse_nice(optarg
, &arg_nice
);
273 return log_error_errno(r
, "Failed to parse nice value: %s", optarg
);
279 if (strv_extend(&arg_environment
, optarg
) < 0)
285 if (strv_extend(&arg_property
, optarg
) < 0)
290 case 't': /* --pty */
291 if (IN_SET(arg_stdio
, ARG_STDIO_DIRECT
, ARG_STDIO_AUTO
)) /* if --pipe is already used, upgrade to auto mode */
292 arg_stdio
= ARG_STDIO_AUTO
;
294 arg_stdio
= ARG_STDIO_PTY
;
297 case 'P': /* --pipe */
298 if (IN_SET(arg_stdio
, ARG_STDIO_PTY
, ARG_STDIO_AUTO
)) /* If --pty is already used, upgrade to auto mode */
299 arg_stdio
= ARG_STDIO_AUTO
;
301 arg_stdio
= ARG_STDIO_DIRECT
;
310 r
= parse_sec(optarg
, &arg_on_active
);
312 log_error("Failed to parse timer value: %s", optarg
);
320 r
= parse_sec(optarg
, &arg_on_boot
);
322 log_error("Failed to parse timer value: %s", optarg
);
330 r
= parse_sec(optarg
, &arg_on_startup
);
332 log_error("Failed to parse timer value: %s", optarg
);
338 case ARG_ON_UNIT_ACTIVE
:
340 r
= parse_sec(optarg
, &arg_on_unit_active
);
342 log_error("Failed to parse timer value: %s", optarg
);
348 case ARG_ON_UNIT_INACTIVE
:
350 r
= parse_sec(optarg
, &arg_on_unit_inactive
);
352 log_error("Failed to parse timer value: %s", optarg
);
358 case ARG_ON_CALENDAR
: {
359 CalendarSpec
*spec
= NULL
;
361 r
= calendar_spec_from_string(optarg
, &spec
);
363 log_error("Invalid calendar spec: %s", optarg
);
367 calendar_spec_free(spec
);
368 arg_on_calendar
= optarg
;
372 case ARG_TIMER_PROPERTY
:
374 if (strv_extend(&arg_timer_property
, optarg
) < 0)
391 assert_not_reached("Unhandled option");
395 if (arg_stdio
== ARG_STDIO_AUTO
) {
396 /* If we both --pty and --pipe are specified we'll automatically pick --pty if we are connected fully
397 * to a TTY and pick direct fd passing otherwise. This way, we automatically adapt to usage in a shell
398 * pipeline, but we are neatly interactive with tty-level isolation otherwise. */
399 arg_stdio
= isatty(STDIN_FILENO
) && isatty(STDOUT_FILENO
) && isatty(STDERR_FILENO
) ?
404 if ((optind
>= argc
) && (!arg_unit
|| !with_timer())) {
405 log_error("Command line to execute required.");
409 if (arg_user
&& arg_transport
!= BUS_TRANSPORT_LOCAL
) {
410 log_error("Execution in user context is not supported on non-local systems.");
414 if (arg_scope
&& arg_transport
!= BUS_TRANSPORT_LOCAL
) {
415 log_error("Scope execution is not supported on non-local systems.");
419 if (arg_scope
&& (arg_remain_after_exit
|| arg_service_type
)) {
420 log_error("--remain-after-exit and --service-type= are not supported in --scope mode.");
424 if (arg_stdio
!= ARG_STDIO_NONE
&& (with_timer() || arg_scope
)) {
425 log_error("--pty/--pipe is not compatible in timer or --scope mode.");
429 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_transport
== BUS_TRANSPORT_REMOTE
) {
430 log_error("--pty/--pipe is only supported when connecting to the local system or containers.");
434 if (arg_stdio
!= ARG_STDIO_NONE
&& arg_no_block
) {
435 log_error("--pty/--pipe is not compatible with --no-block.");
439 if (arg_scope
&& with_timer()) {
440 log_error("Timer options are not supported in --scope mode.");
444 if (arg_timer_property
&& !with_timer()) {
445 log_error("--timer-property= has no effect without any other timer options.");
451 log_error("--wait may not be combined with --no-block.");
456 log_error("--wait may not be combined with timer operations.");
461 log_error("--wait may not be combined with --scope.");
469 static int transient_unit_set_properties(sd_bus_message
*m
, char **properties
) {
472 r
= sd_bus_message_append(m
, "(sv)", "Description", "s", arg_description
);
476 r
= bus_append_unit_property_assignment_many(m
, properties
);
483 static int transient_cgroup_set_properties(sd_bus_message
*m
) {
487 if (!isempty(arg_slice
)) {
488 _cleanup_free_
char *slice
;
490 r
= unit_name_mangle_with_suffix(arg_slice
, UNIT_NAME_NOGLOB
, ".slice", &slice
);
494 r
= sd_bus_message_append(m
, "(sv)", "Slice", "s", slice
);
502 static int transient_kill_set_properties(sd_bus_message
*m
) {
506 return sd_bus_message_append(m
, "(sv)", "SendSIGHUP", "b", arg_send_sighup
);
511 static int transient_service_set_properties(sd_bus_message
*m
, char **argv
, const char *pty_path
) {
512 bool send_term
= false;
517 r
= transient_unit_set_properties(m
, arg_property
);
521 r
= transient_kill_set_properties(m
);
525 r
= transient_cgroup_set_properties(m
);
529 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
530 r
= sd_bus_message_append(m
, "(sv)", "AddRef", "b", 1);
535 if (arg_remain_after_exit
) {
536 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit
);
541 if (arg_service_type
) {
542 r
= sd_bus_message_append(m
, "(sv)", "Type", "s", arg_service_type
);
548 r
= sd_bus_message_append(m
, "(sv)", "User", "s", arg_exec_user
);
553 if (arg_exec_group
) {
554 r
= sd_bus_message_append(m
, "(sv)", "Group", "s", arg_exec_group
);
560 r
= sd_bus_message_append(m
, "(sv)", "Nice", "i", arg_nice
);
566 r
= sd_bus_message_append(m
,
568 "StandardInput", "s", "tty",
569 "StandardOutput", "s", "tty",
570 "StandardError", "s", "tty",
571 "TTYPath", "s", pty_path
);
577 } else if (arg_stdio
== ARG_STDIO_DIRECT
) {
578 r
= sd_bus_message_append(m
,
580 "StandardInputFileDescriptor", "h", STDIN_FILENO
,
581 "StandardOutputFileDescriptor", "h", STDOUT_FILENO
,
582 "StandardErrorFileDescriptor", "h", STDERR_FILENO
);
586 send_term
= isatty(STDIN_FILENO
) || isatty(STDOUT_FILENO
) || isatty(STDERR_FILENO
);
596 n
= strjoina("TERM=", e
);
597 r
= sd_bus_message_append(m
,
599 "Environment", "as", 1, n
);
605 if (!strv_isempty(arg_environment
)) {
606 r
= sd_bus_message_open_container(m
, 'r', "sv");
610 r
= sd_bus_message_append(m
, "s", "Environment");
614 r
= sd_bus_message_open_container(m
, 'v', "as");
618 r
= sd_bus_message_append_strv(m
, arg_environment
);
622 r
= sd_bus_message_close_container(m
);
626 r
= sd_bus_message_close_container(m
);
633 r
= sd_bus_message_open_container(m
, 'r', "sv");
637 r
= sd_bus_message_append(m
, "s", "ExecStart");
641 r
= sd_bus_message_open_container(m
, 'v', "a(sasb)");
645 r
= sd_bus_message_open_container(m
, 'a', "(sasb)");
649 r
= sd_bus_message_open_container(m
, 'r', "sasb");
653 r
= sd_bus_message_append(m
, "s", argv
[0]);
657 r
= sd_bus_message_append_strv(m
, argv
);
661 r
= sd_bus_message_append(m
, "b", false);
665 r
= sd_bus_message_close_container(m
);
669 r
= sd_bus_message_close_container(m
);
673 r
= sd_bus_message_close_container(m
);
677 r
= sd_bus_message_close_container(m
);
685 static int transient_scope_set_properties(sd_bus_message
*m
) {
690 r
= transient_unit_set_properties(m
, arg_property
);
694 r
= transient_kill_set_properties(m
);
698 r
= transient_cgroup_set_properties(m
);
702 r
= sd_bus_message_append(m
, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached());
709 static int transient_timer_set_properties(sd_bus_message
*m
) {
714 r
= transient_unit_set_properties(m
, arg_timer_property
);
718 /* Automatically clean up our transient timers */
719 r
= sd_bus_message_append(m
, "(sv)", "RemainAfterElapse", "b", false);
724 r
= sd_bus_message_append(m
, "(sv)", "OnActiveSec", "t", arg_on_active
);
730 r
= sd_bus_message_append(m
, "(sv)", "OnBootSec", "t", arg_on_boot
);
735 if (arg_on_startup
) {
736 r
= sd_bus_message_append(m
, "(sv)", "OnStartupSec", "t", arg_on_startup
);
741 if (arg_on_unit_active
) {
742 r
= sd_bus_message_append(m
, "(sv)", "OnUnitActiveSec", "t", arg_on_unit_active
);
747 if (arg_on_unit_inactive
) {
748 r
= sd_bus_message_append(m
, "(sv)", "OnUnitInactiveSec", "t", arg_on_unit_inactive
);
753 if (arg_on_calendar
) {
754 r
= sd_bus_message_append(m
, "(sv)", "OnCalendar", "s", arg_on_calendar
);
762 static int make_unit_name(sd_bus
*bus
, UnitType t
, char **ret
) {
763 const char *unique
, *id
;
769 assert(t
< _UNIT_TYPE_MAX
);
771 r
= sd_bus_get_unique_name(bus
, &unique
);
775 /* We couldn't get the unique name, which is a pretty
776 * common case if we are connected to systemd
777 * directly. In that case, just pick a random uuid as
780 r
= sd_id128_randomize(&rnd
);
782 return log_error_errno(r
, "Failed to generate random run unit name: %m");
784 if (asprintf(ret
, "run-r" SD_ID128_FORMAT_STR
".%s", SD_ID128_FORMAT_VAL(rnd
), unit_type_to_string(t
)) < 0)
790 /* We managed to get the unique name, then let's use that to
791 * name our transient units. */
793 id
= startswith(unique
, ":1.");
795 log_error("Unique name %s has unexpected format.", unique
);
799 p
= strjoin("run-u", id
, ".", unit_type_to_string(t
));
807 typedef struct RunContext
{
813 /* The exit data of the unit */
815 uint64_t inactive_exit_usec
;
816 uint64_t inactive_enter_usec
;
818 uint64_t cpu_usage_nsec
;
819 uint64_t ip_ingress_bytes
;
820 uint64_t ip_egress_bytes
;
822 uint32_t exit_status
;
825 static void run_context_free(RunContext
*c
) {
828 c
->forward
= pty_forward_free(c
->forward
);
829 c
->match
= sd_bus_slot_unref(c
->match
);
830 c
->bus
= sd_bus_unref(c
->bus
);
831 c
->event
= sd_event_unref(c
->event
);
833 free(c
->active_state
);
837 static void run_context_check_done(RunContext
*c
) {
843 done
= STRPTR_IN_SET(c
->active_state
, "inactive", "failed");
847 if (c
->forward
&& done
) /* If the service is gone, it's time to drain the output */
848 done
= pty_forward_drain(c
->forward
);
851 sd_event_exit(c
->event
, EXIT_SUCCESS
);
854 static int run_context_update(RunContext
*c
, const char *path
) {
856 static const struct bus_properties_map map
[] = {
857 { "ActiveState", "s", NULL
, offsetof(RunContext
, active_state
) },
858 { "InactiveExitTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_exit_usec
) },
859 { "InactiveEnterTimestampMonotonic", "t", NULL
, offsetof(RunContext
, inactive_enter_usec
) },
860 { "Result", "s", NULL
, offsetof(RunContext
, result
) },
861 { "ExecMainCode", "i", NULL
, offsetof(RunContext
, exit_code
) },
862 { "ExecMainStatus", "i", NULL
, offsetof(RunContext
, exit_status
) },
863 { "CPUUsageNSec", "t", NULL
, offsetof(RunContext
, cpu_usage_nsec
) },
864 { "IPIngressBytes", "t", NULL
, offsetof(RunContext
, ip_ingress_bytes
) },
865 { "IPEgressBytes", "t", NULL
, offsetof(RunContext
, ip_egress_bytes
) },
869 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
872 r
= bus_map_all_properties(c
->bus
,
873 "org.freedesktop.systemd1",
879 sd_event_exit(c
->event
, EXIT_FAILURE
);
880 return log_error_errno(r
, "Failed to query unit state: %s", bus_error_message(&error
, r
));
883 run_context_check_done(c
);
887 static int on_properties_changed(sd_bus_message
*m
, void *userdata
, sd_bus_error
*error
) {
888 RunContext
*c
= userdata
;
893 return run_context_update(c
, sd_bus_message_get_path(m
));
896 static int pty_forward_handler(PTYForward
*f
, int rcode
, void *userdata
) {
897 RunContext
*c
= userdata
;
902 sd_event_exit(c
->event
, EXIT_FAILURE
);
903 return log_error_errno(rcode
, "Error on PTY forwarding logic: %m");
906 run_context_check_done(c
);
910 static int start_transient_service(
915 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
916 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
917 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
918 _cleanup_free_
char *service
= NULL
, *pty_path
= NULL
;
919 _cleanup_close_
int master
= -1;
926 if (arg_stdio
== ARG_STDIO_PTY
) {
928 if (arg_transport
== BUS_TRANSPORT_LOCAL
) {
929 master
= posix_openpt(O_RDWR
|O_NOCTTY
|O_CLOEXEC
|O_NDELAY
);
931 return log_error_errno(errno
, "Failed to acquire pseudo tty: %m");
933 r
= ptsname_malloc(master
, &pty_path
);
935 return log_error_errno(r
, "Failed to determine tty name: %m");
937 if (unlockpt(master
) < 0)
938 return log_error_errno(errno
, "Failed to unlock tty: %m");
940 } else if (arg_transport
== BUS_TRANSPORT_MACHINE
) {
941 _cleanup_(sd_bus_unrefp
) sd_bus
*system_bus
= NULL
;
942 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*pty_reply
= NULL
;
945 r
= sd_bus_default_system(&system_bus
);
947 return log_error_errno(r
, "Failed to connect to system bus: %m");
949 r
= sd_bus_call_method(system_bus
,
950 "org.freedesktop.machine1",
951 "/org/freedesktop/machine1",
952 "org.freedesktop.machine1.Manager",
958 log_error("Failed to get machine PTY: %s", bus_error_message(&error
, -r
));
962 r
= sd_bus_message_read(pty_reply
, "hs", &master
, &s
);
964 return bus_log_parse_error(r
);
966 master
= fcntl(master
, F_DUPFD_CLOEXEC
, 3);
968 return log_error_errno(errno
, "Failed to duplicate master fd: %m");
970 pty_path
= strdup(s
);
974 assert_not_reached("Can't allocate tty via ssh");
978 r
= bus_wait_for_jobs_new(bus
, &w
);
980 return log_error_errno(r
, "Could not watch jobs: %m");
984 r
= unit_name_mangle_with_suffix(arg_unit
, UNIT_NAME_NOGLOB
, ".service", &service
);
986 return log_error_errno(r
, "Failed to mangle unit name: %m");
988 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
993 r
= sd_bus_message_new_method_call(
996 "org.freedesktop.systemd1",
997 "/org/freedesktop/systemd1",
998 "org.freedesktop.systemd1.Manager",
999 "StartTransientUnit");
1001 return bus_log_create_error(r
);
1003 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1005 return bus_log_create_error(r
);
1008 r
= sd_bus_message_append(m
, "ss", service
, "fail");
1010 return bus_log_create_error(r
);
1013 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1015 return bus_log_create_error(r
);
1017 r
= transient_service_set_properties(m
, argv
, pty_path
);
1019 return bus_log_create_error(r
);
1021 r
= sd_bus_message_close_container(m
);
1023 return bus_log_create_error(r
);
1025 /* Auxiliary units */
1026 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1028 return bus_log_create_error(r
);
1030 polkit_agent_open_if_enabled();
1032 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1034 return log_error_errno(r
, "Failed to start transient service unit: %s", bus_error_message(&error
, r
));
1039 r
= sd_bus_message_read(reply
, "o", &object
);
1041 return bus_log_parse_error(r
);
1043 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1049 log_info("Running as unit: %s", service
);
1051 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
) {
1052 _cleanup_(run_context_free
) RunContext c
= {
1053 .cpu_usage_nsec
= NSEC_INFINITY
,
1054 .ip_ingress_bytes
= UINT64_MAX
,
1055 .ip_egress_bytes
= UINT64_MAX
,
1056 .inactive_exit_usec
= USEC_INFINITY
,
1057 .inactive_enter_usec
= USEC_INFINITY
,
1059 _cleanup_free_
char *path
= NULL
;
1062 c
.bus
= sd_bus_ref(bus
);
1064 r
= sd_event_default(&c
.event
);
1066 return log_error_errno(r
, "Failed to get event loop: %m");
1069 assert_se(sigprocmask_many(SIG_BLOCK
, NULL
, SIGWINCH
, SIGTERM
, SIGINT
, -1) >= 0);
1070 (void) sd_event_add_signal(c
.event
, NULL
, SIGINT
, NULL
, NULL
);
1071 (void) sd_event_add_signal(c
.event
, NULL
, SIGTERM
, NULL
, NULL
);
1074 log_info("Press ^] three times within 1s to disconnect TTY.");
1076 r
= pty_forward_new(c
.event
, master
, PTY_FORWARD_IGNORE_INITIAL_VHANGUP
, &c
.forward
);
1078 return log_error_errno(r
, "Failed to create PTY forwarder: %m");
1080 pty_forward_set_handler(c
.forward
, pty_forward_handler
, &c
);
1083 path
= unit_dbus_path_from_name(service
);
1087 mt
= strjoina("type='signal',"
1088 "sender='org.freedesktop.systemd1',"
1089 "path='", path
, "',"
1090 "interface='org.freedesktop.DBus.Properties',"
1091 "member='PropertiesChanged'");
1092 r
= sd_bus_add_match(bus
, &c
.match
, mt
, on_properties_changed
, &c
);
1094 return log_error_errno(r
, "Failed to add properties changed signal.");
1096 r
= sd_bus_attach_event(bus
, c
.event
, 0);
1098 return log_error_errno(r
, "Failed to attach bus to event loop.");
1100 r
= run_context_update(&c
, path
);
1104 r
= sd_event_loop(c
.event
);
1106 return log_error_errno(r
, "Failed to run event loop: %m");
1111 r
= pty_forward_get_last_char(c
.forward
, &last_char
);
1112 if (r
>= 0 && !arg_quiet
&& last_char
!= '\n')
1113 fputc('\n', stdout
);
1116 if (arg_wait
&& !arg_quiet
) {
1118 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, in its
1119 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1121 c
.forward
= pty_forward_free(c
.forward
);
1123 if (!isempty(c
.result
))
1124 log_info("Finished with result: %s", strna(c
.result
));
1126 if (c
.exit_code
== CLD_EXITED
)
1127 log_info("Main processes terminated with: code=%s/status=%i", sigchld_code_to_string(c
.exit_code
), c
.exit_status
);
1128 else if (c
.exit_code
> 0)
1129 log_info("Main processes terminated with: code=%s/status=%s", sigchld_code_to_string(c
.exit_code
), signal_to_string(c
.exit_status
));
1131 if (c
.inactive_enter_usec
> 0 && c
.inactive_enter_usec
!= USEC_INFINITY
&&
1132 c
.inactive_exit_usec
> 0 && c
.inactive_exit_usec
!= USEC_INFINITY
&&
1133 c
.inactive_enter_usec
> c
.inactive_exit_usec
) {
1134 char ts
[FORMAT_TIMESPAN_MAX
];
1135 log_info("Service runtime: %s", format_timespan(ts
, sizeof(ts
), c
.inactive_enter_usec
- c
.inactive_exit_usec
, USEC_PER_MSEC
));
1138 if (c
.cpu_usage_nsec
!= NSEC_INFINITY
) {
1139 char ts
[FORMAT_TIMESPAN_MAX
];
1140 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
));
1143 if (c
.ip_ingress_bytes
!= UINT64_MAX
) {
1144 char bytes
[FORMAT_BYTES_MAX
];
1145 log_info("IP traffic received: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_ingress_bytes
));
1147 if (c
.ip_egress_bytes
!= UINT64_MAX
) {
1148 char bytes
[FORMAT_BYTES_MAX
];
1149 log_info("IP traffic sent: %s", format_bytes(bytes
, sizeof(bytes
), c
.ip_egress_bytes
));
1153 /* Try to propagate the service's return value */
1154 if (c
.result
&& STR_IN_SET(c
.result
, "success", "exit-code") && c
.exit_code
== CLD_EXITED
)
1155 *retval
= c
.exit_status
;
1157 *retval
= EXIT_FAILURE
;
1163 static int start_transient_scope(
1167 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1168 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1169 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1170 _cleanup_strv_free_
char **env
= NULL
, **user_env
= NULL
;
1171 _cleanup_free_
char *scope
= NULL
;
1172 const char *object
= NULL
;
1178 r
= bus_wait_for_jobs_new(bus
, &w
);
1183 r
= unit_name_mangle_with_suffix(arg_unit
, UNIT_NAME_NOGLOB
, ".scope", &scope
);
1185 return log_error_errno(r
, "Failed to mangle scope name: %m");
1187 r
= make_unit_name(bus
, UNIT_SCOPE
, &scope
);
1192 r
= sd_bus_message_new_method_call(
1195 "org.freedesktop.systemd1",
1196 "/org/freedesktop/systemd1",
1197 "org.freedesktop.systemd1.Manager",
1198 "StartTransientUnit");
1200 return bus_log_create_error(r
);
1202 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1204 return bus_log_create_error(r
);
1207 r
= sd_bus_message_append(m
, "ss", scope
, "fail");
1209 return bus_log_create_error(r
);
1212 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1214 return bus_log_create_error(r
);
1216 r
= transient_scope_set_properties(m
);
1218 return bus_log_create_error(r
);
1220 r
= sd_bus_message_close_container(m
);
1222 return bus_log_create_error(r
);
1224 /* Auxiliary units */
1225 r
= sd_bus_message_append(m
, "a(sa(sv))", 0);
1227 return bus_log_create_error(r
);
1229 polkit_agent_open_if_enabled();
1231 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1233 log_error("Failed to start transient scope unit: %s", bus_error_message(&error
, -r
));
1238 if (setpriority(PRIO_PROCESS
, 0, arg_nice
) < 0)
1239 return log_error_errno(errno
, "Failed to set nice level: %m");
1242 if (arg_exec_group
) {
1245 r
= get_group_creds(&arg_exec_group
, &gid
);
1247 return log_error_errno(r
, "Failed to resolve group %s: %m", arg_exec_group
);
1249 if (setresgid(gid
, gid
, gid
) < 0)
1250 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1253 if (arg_exec_user
) {
1254 const char *home
, *shell
;
1258 r
= get_user_creds_clean(&arg_exec_user
, &uid
, &gid
, &home
, &shell
);
1260 return log_error_errno(r
, "Failed to resolve user %s: %m", arg_exec_user
);
1263 r
= strv_extendf(&user_env
, "HOME=%s", home
);
1269 r
= strv_extendf(&user_env
, "SHELL=%s", shell
);
1274 r
= strv_extendf(&user_env
, "USER=%s", arg_exec_user
);
1278 r
= strv_extendf(&user_env
, "LOGNAME=%s", arg_exec_user
);
1282 if (!arg_exec_group
) {
1283 if (setresgid(gid
, gid
, gid
) < 0)
1284 return log_error_errno(errno
, "Failed to change GID to " GID_FMT
": %m", gid
);
1287 if (setresuid(uid
, uid
, uid
) < 0)
1288 return log_error_errno(errno
, "Failed to change UID to " UID_FMT
": %m", uid
);
1291 env
= strv_env_merge(3, environ
, user_env
, arg_environment
);
1295 r
= sd_bus_message_read(reply
, "o", &object
);
1297 return bus_log_parse_error(r
);
1299 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1304 log_info("Running scope as unit: %s", scope
);
1306 execvpe(argv
[0], argv
, env
);
1308 return log_error_errno(errno
, "Failed to execute: %m");
1311 static int start_transient_timer(
1315 _cleanup_(sd_bus_error_free
) sd_bus_error error
= SD_BUS_ERROR_NULL
;
1316 _cleanup_(sd_bus_message_unrefp
) sd_bus_message
*m
= NULL
, *reply
= NULL
;
1317 _cleanup_(bus_wait_for_jobs_freep
) BusWaitForJobs
*w
= NULL
;
1318 _cleanup_free_
char *timer
= NULL
, *service
= NULL
;
1319 const char *object
= NULL
;
1325 r
= bus_wait_for_jobs_new(bus
, &w
);
1330 switch (unit_name_to_type(arg_unit
)) {
1333 service
= strdup(arg_unit
);
1337 r
= unit_name_change_suffix(service
, ".timer", &timer
);
1339 return log_error_errno(r
, "Failed to change unit suffix: %m");
1343 timer
= strdup(arg_unit
);
1347 r
= unit_name_change_suffix(timer
, ".service", &service
);
1349 return log_error_errno(r
, "Failed to change unit suffix: %m");
1353 r
= unit_name_mangle_with_suffix(arg_unit
, UNIT_NAME_NOGLOB
, ".service", &service
);
1355 return log_error_errno(r
, "Failed to mangle unit name: %m");
1357 r
= unit_name_mangle_with_suffix(arg_unit
, UNIT_NAME_NOGLOB
, ".timer", &timer
);
1359 return log_error_errno(r
, "Failed to mangle unit name: %m");
1364 r
= make_unit_name(bus
, UNIT_SERVICE
, &service
);
1368 r
= unit_name_change_suffix(service
, ".timer", &timer
);
1370 return log_error_errno(r
, "Failed to change unit suffix: %m");
1373 r
= sd_bus_message_new_method_call(
1376 "org.freedesktop.systemd1",
1377 "/org/freedesktop/systemd1",
1378 "org.freedesktop.systemd1.Manager",
1379 "StartTransientUnit");
1381 return bus_log_create_error(r
);
1383 r
= sd_bus_message_set_allow_interactive_authorization(m
, arg_ask_password
);
1385 return bus_log_create_error(r
);
1388 r
= sd_bus_message_append(m
, "ss", timer
, "fail");
1390 return bus_log_create_error(r
);
1393 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1395 return bus_log_create_error(r
);
1397 r
= transient_timer_set_properties(m
);
1399 return bus_log_create_error(r
);
1401 r
= sd_bus_message_close_container(m
);
1403 return bus_log_create_error(r
);
1405 r
= sd_bus_message_open_container(m
, 'a', "(sa(sv))");
1407 return bus_log_create_error(r
);
1409 if (!strv_isempty(argv
)) {
1410 r
= sd_bus_message_open_container(m
, 'r', "sa(sv)");
1412 return bus_log_create_error(r
);
1414 r
= sd_bus_message_append(m
, "s", service
);
1416 return bus_log_create_error(r
);
1418 r
= sd_bus_message_open_container(m
, 'a', "(sv)");
1420 return bus_log_create_error(r
);
1422 r
= transient_service_set_properties(m
, argv
, NULL
);
1424 return bus_log_create_error(r
);
1426 r
= sd_bus_message_close_container(m
);
1428 return bus_log_create_error(r
);
1430 r
= sd_bus_message_close_container(m
);
1432 return bus_log_create_error(r
);
1435 r
= sd_bus_message_close_container(m
);
1437 return bus_log_create_error(r
);
1439 polkit_agent_open_if_enabled();
1441 r
= sd_bus_call(bus
, m
, 0, &error
, &reply
);
1443 log_error("Failed to start transient timer unit: %s", bus_error_message(&error
, -r
));
1447 r
= sd_bus_message_read(reply
, "o", &object
);
1449 return bus_log_parse_error(r
);
1451 r
= bus_wait_for_jobs_one(w
, object
, arg_quiet
);
1456 log_info("Running timer as unit: %s", timer
);
1458 log_info("Will run service as unit: %s", service
);
1464 int main(int argc
, char* argv
[]) {
1465 _cleanup_(sd_bus_flush_close_unrefp
) sd_bus
*bus
= NULL
;
1466 _cleanup_free_
char *description
= NULL
, *command
= NULL
;
1467 int r
, retval
= EXIT_SUCCESS
;
1469 log_parse_environment();
1472 r
= parse_argv(argc
, argv
);
1476 if (argc
> optind
&& arg_transport
== BUS_TRANSPORT_LOCAL
) {
1477 /* Patch in an absolute path */
1479 r
= find_binary(argv
[optind
], &command
);
1481 log_error_errno(r
, "Failed to find executable %s: %m", argv
[optind
]);
1485 argv
[optind
] = command
;
1488 if (!arg_description
) {
1489 description
= strv_join(argv
+ optind
, " ");
1495 if (arg_unit
&& isempty(description
)) {
1496 r
= free_and_strdup(&description
, arg_unit
);
1501 arg_description
= description
;
1504 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the limited direct
1506 if (arg_wait
|| arg_stdio
!= ARG_STDIO_NONE
)
1507 r
= bus_connect_transport(arg_transport
, arg_host
, arg_user
, &bus
);
1509 r
= bus_connect_transport_systemd(arg_transport
, arg_host
, arg_user
, &bus
);
1511 log_error_errno(r
, "Failed to create bus connection: %m");
1516 r
= start_transient_scope(bus
, argv
+ optind
);
1517 else if (with_timer())
1518 r
= start_transient_timer(bus
, argv
+ optind
);
1520 r
= start_transient_service(bus
, argv
+ optind
, &retval
);
1523 strv_free(arg_environment
);
1524 strv_free(arg_property
);
1525 strv_free(arg_timer_property
);
1527 return r
< 0 ? EXIT_FAILURE
: retval
;