]> git.ipfire.org Git - thirdparty/systemd.git/blame - src/run/run.c
coccinelle: make use of SYNTHETIC_ERRNO
[thirdparty/systemd.git] / src / run / run.c
CommitLineData
53e1b683 1/* SPDX-License-Identifier: LGPL-2.1+ */
c2756a68 2
6c12b52e 3#include <getopt.h>
3f6fd1ba 4#include <stdio.h>
c2756a68
LP
5
6#include "sd-bus.h"
9b15b784 7#include "sd-event.h"
3f6fd1ba 8
b5efdb8a 9#include "alloc-util.h"
3f6fd1ba 10#include "bus-error.h"
20b16441 11#include "bus-unit-util.h"
40ca29a1 12#include "bus-util.h"
3f6fd1ba 13#include "calendarspec.h"
4de33e7f 14#include "env-util.h"
3ffd4af2 15#include "fd-util.h"
f97b34a6 16#include "format-util.h"
cf0fbc49 17#include "parse-util.h"
4bcc8c3c 18#include "path-util.h"
294bf0c3 19#include "pretty-print.h"
2a453c2e 20#include "process-util.h"
9b15b784 21#include "ptyfwd.h"
24882e06 22#include "signal-util.h"
8c7db2fb 23#include "spawn-polkit-agent.h"
3f6fd1ba 24#include "strv.h"
66cb2fde 25#include "terminal-util.h"
89ada3ba 26#include "unit-def.h"
3f6fd1ba 27#include "unit-name.h"
b1d4f8e1 28#include "user-util.h"
c2756a68 29
8c7db2fb 30static bool arg_ask_password = true;
6c12b52e 31static bool arg_scope = false;
6577c7ce 32static bool arg_remain_after_exit = false;
3d161f99 33static bool arg_no_block = false;
2a453c2e 34static bool arg_wait = false;
6c12b52e 35static const char *arg_unit = NULL;
9f2e86af 36static const char *arg_description = NULL;
c221420b 37static const char *arg_slice = NULL;
a6c0353b 38static bool arg_send_sighup = false;
d21ed1ea 39static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
1ac67edb 40static const char *arg_host = NULL;
d21ed1ea 41static bool arg_user = false;
c7040b5d
LP
42static const char *arg_service_type = NULL;
43static const char *arg_exec_user = NULL;
44static const char *arg_exec_group = NULL;
45static int arg_nice = 0;
46static bool arg_nice_set = false;
47static char **arg_environment = NULL;
df31a6c0 48static char **arg_property = NULL;
5dca7739
LP
49static enum {
50 ARG_STDIO_NONE, /* The default, as it is for normal services, stdin connected to /dev/null, and stdout+stderr to the journal */
51 ARG_STDIO_PTY, /* Interactive behaviour, requested by --pty: we allocate a pty and connect it to the TTY we are invoked from */
52 ARG_STDIO_DIRECT, /* Directly pass our stdin/stdout/stderr to the activated service, useful for usage in shell pipelines, requested by --pipe */
53 ARG_STDIO_AUTO, /* If --pipe and --pty are used together we use --pty when invoked on a TTY, and --pipe otherwise */
54} arg_stdio = ARG_STDIO_NONE;
d59ef3e2
YW
55static char **arg_path_property = NULL;
56static char **arg_socket_property = NULL;
4c213d6c 57static char **arg_timer_property = NULL;
f2b9f2c8 58static bool with_timer = false;
095dc596 59static bool arg_quiet = false;
fe9d0be9 60static bool arg_aggressive_gc = false;
c2756a68 61
37ec0fdd
LP
62static int help(void) {
63 _cleanup_free_ char *link = NULL;
64 int r;
65
66 r = terminal_urlify_man("systemd-run", "1", &link);
67 if (r < 0)
68 return log_oom();
69
4c213d6c 70 printf("%s [OPTIONS...] {COMMAND} [ARGS...]\n\n"
ad2c1701 71 "Run the specified command in a transient scope or service.\n\n"
4c213d6c
WC
72 " -h --help Show this help\n"
73 " --version Show package version\n"
8c7db2fb 74 " --no-ask-password Do not prompt for password\n"
4c213d6c
WC
75 " --user Run as user unit\n"
76 " -H --host=[USER@]HOST Operate on remote host\n"
77 " -M --machine=CONTAINER Operate on local container\n"
78 " --scope Run this as scope rather than service\n"
79 " --unit=UNIT Run under the specified unit name\n"
ad2c1701 80 " -p --property=NAME=VALUE Set service or scope unit property\n"
4c213d6c
WC
81 " --description=TEXT Description for unit\n"
82 " --slice=SLICE Run in the specified slice\n"
3d161f99 83 " --no-block Do not wait until operation finished\n"
4c213d6c 84 " -r --remain-after-exit Leave service around until explicitly stopped\n"
2a453c2e 85 " --wait Wait until service stopped again\n"
4c213d6c
WC
86 " --send-sighup Send SIGHUP when terminating\n"
87 " --service-type=TYPE Service type\n"
88 " --uid=USER Run as system user\n"
89 " --gid=GROUP Run as system group\n"
90 " --nice=NICE Nice level\n"
b5911366 91 " -E --setenv=NAME=VALUE Set environment\n"
5dca7739
LP
92 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
93 " STDERR\n"
94 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
fe9d0be9
LP
95 " -q --quiet Suppress information messages during runtime\n"
96 " -G --collect Unload unit after it ran, even when failed\n\n"
d59ef3e2
YW
97 "Path options:\n"
98 " --path-property=NAME=VALUE Set path unit property\n\n"
99 "Socket options:\n"
100 " --socket-property=NAME=VALUE Set socket unit property\n\n"
ad2c1701 101 "Timer options:\n"
b57b0625
ZJS
102 " --on-active=SECONDS Run after SECONDS delay\n"
103 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
104 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
105 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
106 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
4c213d6c 107 " --on-calendar=SPEC Realtime timer\n"
ad2c1701 108 " --timer-property=NAME=VALUE Set timer unit property\n"
37ec0fdd
LP
109 "\nSee the %s for details.\n"
110 , program_invocation_short_name
111 , link
112 );
113
114 return 0;
6c12b52e
LP
115}
116
f2b9f2c8 117static int add_timer_property(const char *name, const char *val) {
18939728 118 char *p;
f2b9f2c8
YW
119
120 assert(name);
121 assert(val);
122
123 p = strjoin(name, "=", val);
124 if (!p)
125 return log_oom();
126
127 if (strv_consume(&arg_timer_property, p) < 0)
128 return log_oom();
129
f2b9f2c8 130 return 0;
4c213d6c
WC
131}
132
6c12b52e
LP
133static int parse_argv(int argc, char *argv[]) {
134
135 enum {
136 ARG_VERSION = 0x100,
137 ARG_USER,
66b1e746 138 ARG_SYSTEM,
6c12b52e 139 ARG_SCOPE,
9f2e86af 140 ARG_UNIT,
c221420b 141 ARG_DESCRIPTION,
a6c0353b
LP
142 ARG_SLICE,
143 ARG_SEND_SIGHUP,
5cfde70c 144 ARG_SERVICE_TYPE,
c7040b5d
LP
145 ARG_EXEC_USER,
146 ARG_EXEC_GROUP,
c7040b5d 147 ARG_NICE,
4c213d6c
WC
148 ARG_ON_ACTIVE,
149 ARG_ON_BOOT,
150 ARG_ON_STARTUP,
151 ARG_ON_UNIT_ACTIVE,
152 ARG_ON_UNIT_INACTIVE,
153 ARG_ON_CALENDAR,
3d161f99 154 ARG_TIMER_PROPERTY,
d59ef3e2
YW
155 ARG_PATH_PROPERTY,
156 ARG_SOCKET_PROPERTY,
3d161f99 157 ARG_NO_BLOCK,
5cfde70c 158 ARG_NO_ASK_PASSWORD,
2a453c2e 159 ARG_WAIT,
6c12b52e
LP
160 };
161
162 static const struct option options[] = {
4c213d6c
WC
163 { "help", no_argument, NULL, 'h' },
164 { "version", no_argument, NULL, ARG_VERSION },
165 { "user", no_argument, NULL, ARG_USER },
166 { "system", no_argument, NULL, ARG_SYSTEM },
167 { "scope", no_argument, NULL, ARG_SCOPE },
168 { "unit", required_argument, NULL, ARG_UNIT },
169 { "description", required_argument, NULL, ARG_DESCRIPTION },
170 { "slice", required_argument, NULL, ARG_SLICE },
171 { "remain-after-exit", no_argument, NULL, 'r' },
172 { "send-sighup", no_argument, NULL, ARG_SEND_SIGHUP },
173 { "host", required_argument, NULL, 'H' },
174 { "machine", required_argument, NULL, 'M' },
175 { "service-type", required_argument, NULL, ARG_SERVICE_TYPE },
2a453c2e 176 { "wait", no_argument, NULL, ARG_WAIT },
4c213d6c
WC
177 { "uid", required_argument, NULL, ARG_EXEC_USER },
178 { "gid", required_argument, NULL, ARG_EXEC_GROUP },
179 { "nice", required_argument, NULL, ARG_NICE },
b5911366 180 { "setenv", required_argument, NULL, 'E' },
4c213d6c 181 { "property", required_argument, NULL, 'p' },
5dca7739 182 { "tty", no_argument, NULL, 't' }, /* deprecated alias */
5cfde70c 183 { "pty", no_argument, NULL, 't' },
5dca7739 184 { "pipe", no_argument, NULL, 'P' },
095dc596 185 { "quiet", no_argument, NULL, 'q' },
4c213d6c
WC
186 { "on-active", required_argument, NULL, ARG_ON_ACTIVE },
187 { "on-boot", required_argument, NULL, ARG_ON_BOOT },
188 { "on-startup", required_argument, NULL, ARG_ON_STARTUP },
189 { "on-unit-active", required_argument, NULL, ARG_ON_UNIT_ACTIVE },
190 { "on-unit-inactive", required_argument, NULL, ARG_ON_UNIT_INACTIVE },
191 { "on-calendar", required_argument, NULL, ARG_ON_CALENDAR },
192 { "timer-property", required_argument, NULL, ARG_TIMER_PROPERTY },
d59ef3e2
YW
193 { "path-property", required_argument, NULL, ARG_PATH_PROPERTY },
194 { "socket-property", required_argument, NULL, ARG_SOCKET_PROPERTY },
3d161f99 195 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
ad2c1701 196 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
fe9d0be9 197 { "collect", no_argument, NULL, 'G' },
eb9da376 198 {},
6c12b52e
LP
199 };
200
d59ef3e2 201 bool with_trigger = false;
c7040b5d 202 int r, c;
6c12b52e
LP
203
204 assert(argc >= 0);
205 assert(argv);
206
fe9d0be9 207 while ((c = getopt_long(argc, argv, "+hrH:M:E:p:tPqG", options, NULL)) >= 0)
6c12b52e
LP
208
209 switch (c) {
210
211 case 'h':
37ec0fdd 212 return help();
6c12b52e 213
ad2c1701
LP
214 case ARG_VERSION:
215 return version();
216
8c7db2fb
EV
217 case ARG_NO_ASK_PASSWORD:
218 arg_ask_password = false;
219 break;
220
6c12b52e
LP
221 case ARG_USER:
222 arg_user = true;
223 break;
224
66b1e746
LP
225 case ARG_SYSTEM:
226 arg_user = false;
227 break;
228
6c12b52e
LP
229 case ARG_SCOPE:
230 arg_scope = true;
231 break;
232
233 case ARG_UNIT:
234 arg_unit = optarg;
235 break;
236
9f2e86af
LP
237 case ARG_DESCRIPTION:
238 arg_description = optarg;
239 break;
240
c221420b
LP
241 case ARG_SLICE:
242 arg_slice = optarg;
243 break;
244
a6c0353b
LP
245 case ARG_SEND_SIGHUP:
246 arg_send_sighup = true;
247 break;
248
6577c7ce
LP
249 case 'r':
250 arg_remain_after_exit = true;
251 break;
252
d21ed1ea
LP
253 case 'H':
254 arg_transport = BUS_TRANSPORT_REMOTE;
255 arg_host = optarg;
256 break;
257
258 case 'M':
de33fc62 259 arg_transport = BUS_TRANSPORT_MACHINE;
d21ed1ea
LP
260 arg_host = optarg;
261 break;
262
c7040b5d
LP
263 case ARG_SERVICE_TYPE:
264 arg_service_type = optarg;
265 break;
266
267 case ARG_EXEC_USER:
268 arg_exec_user = optarg;
269 break;
270
271 case ARG_EXEC_GROUP:
272 arg_exec_group = optarg;
273 break;
274
275 case ARG_NICE:
41bf0590
LP
276 r = parse_nice(optarg, &arg_nice);
277 if (r < 0)
278 return log_error_errno(r, "Failed to parse nice value: %s", optarg);
c7040b5d
LP
279
280 arg_nice_set = true;
281 break;
282
b5911366 283 case 'E':
c7040b5d
LP
284 if (strv_extend(&arg_environment, optarg) < 0)
285 return log_oom();
286
287 break;
288
df31a6c0 289 case 'p':
df31a6c0
LP
290 if (strv_extend(&arg_property, optarg) < 0)
291 return log_oom();
292
293 break;
294
5dca7739
LP
295 case 't': /* --pty */
296 if (IN_SET(arg_stdio, ARG_STDIO_DIRECT, ARG_STDIO_AUTO)) /* if --pipe is already used, upgrade to auto mode */
297 arg_stdio = ARG_STDIO_AUTO;
298 else
299 arg_stdio = ARG_STDIO_PTY;
300 break;
301
302 case 'P': /* --pipe */
303 if (IN_SET(arg_stdio, ARG_STDIO_PTY, ARG_STDIO_AUTO)) /* If --pty is already used, upgrade to auto mode */
304 arg_stdio = ARG_STDIO_AUTO;
305 else
306 arg_stdio = ARG_STDIO_DIRECT;
9b15b784
LP
307 break;
308
095dc596
LP
309 case 'q':
310 arg_quiet = true;
311 break;
312
4c213d6c 313 case ARG_ON_ACTIVE:
f2b9f2c8
YW
314 r = add_timer_property("OnActiveSec", optarg);
315 if (r < 0)
4c213d6c 316 return r;
4c213d6c 317
f2b9f2c8 318 with_timer = true;
4c213d6c
WC
319 break;
320
321 case ARG_ON_BOOT:
f2b9f2c8
YW
322 r = add_timer_property("OnBootSec", optarg);
323 if (r < 0)
4c213d6c 324 return r;
4c213d6c 325
f2b9f2c8 326 with_timer = true;
4c213d6c
WC
327 break;
328
329 case ARG_ON_STARTUP:
f2b9f2c8
YW
330 r = add_timer_property("OnStartupSec", optarg);
331 if (r < 0)
4c213d6c 332 return r;
4c213d6c 333
f2b9f2c8 334 with_timer = true;
4c213d6c
WC
335 break;
336
337 case ARG_ON_UNIT_ACTIVE:
f2b9f2c8
YW
338 r = add_timer_property("OnUnitActiveSec", optarg);
339 if (r < 0)
4c213d6c 340 return r;
4c213d6c 341
f2b9f2c8 342 with_timer = true;
4c213d6c
WC
343 break;
344
345 case ARG_ON_UNIT_INACTIVE:
f2b9f2c8
YW
346 r = add_timer_property("OnUnitInactiveSec", optarg);
347 if (r < 0)
4c213d6c 348 return r;
4c213d6c 349
f2b9f2c8 350 with_timer = true;
4c213d6c
WC
351 break;
352
f2b9f2c8
YW
353 case ARG_ON_CALENDAR:
354 r = add_timer_property("OnCalendar", optarg);
355 if (r < 0)
4c213d6c 356 return r;
024a8ec1 357
f2b9f2c8 358 with_timer = true;
4c213d6c
WC
359 break;
360
361 case ARG_TIMER_PROPERTY:
362
363 if (strv_extend(&arg_timer_property, optarg) < 0)
364 return log_oom();
365
f2b9f2c8
YW
366 with_timer = with_timer ||
367 !!startswith(optarg, "OnActiveSec=") ||
368 !!startswith(optarg, "OnBootSec=") ||
369 !!startswith(optarg, "OnStartupSec=") ||
370 !!startswith(optarg, "OnUnitActiveSec=") ||
371 !!startswith(optarg, "OnUnitInactiveSec=") ||
372 !!startswith(optarg, "OnCalendar=");
4c213d6c
WC
373 break;
374
d59ef3e2
YW
375 case ARG_PATH_PROPERTY:
376
377 if (strv_extend(&arg_path_property, optarg) < 0)
378 return log_oom();
379
380 break;
381
382 case ARG_SOCKET_PROPERTY:
383
384 if (strv_extend(&arg_socket_property, optarg) < 0)
385 return log_oom();
386
387 break;
388
3d161f99
LP
389 case ARG_NO_BLOCK:
390 arg_no_block = true;
391 break;
392
2a453c2e
LP
393 case ARG_WAIT:
394 arg_wait = true;
395 break;
396
fe9d0be9
LP
397 case 'G':
398 arg_aggressive_gc = true;
399 break;
400
6c12b52e
LP
401 case '?':
402 return -EINVAL;
403
404 default:
eb9da376 405 assert_not_reached("Unhandled option");
6c12b52e 406 }
6c12b52e 407
d59ef3e2
YW
408 with_trigger = !!arg_path_property || !!arg_socket_property || with_timer;
409
410 /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
baaa35ad
ZJS
411 if ((int) !!arg_path_property + (int) !!arg_socket_property + (int) with_timer > 1)
412 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
413 "Only single trigger (path, socket, timer) unit can be created.");
5dca7739
LP
414
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) ?
420 ARG_STDIO_PTY :
421 ARG_STDIO_DIRECT;
422 }
423
baaa35ad
ZJS
424 if ((optind >= argc) && (!arg_unit || !with_trigger))
425 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
426 "Command line to execute required.");
6c12b52e 427
baaa35ad
ZJS
428 if (arg_user && arg_transport != BUS_TRANSPORT_LOCAL)
429 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
430 "Execution in user context is not supported on non-local systems.");
d21ed1ea 431
baaa35ad
ZJS
432 if (arg_scope && arg_transport != BUS_TRANSPORT_LOCAL)
433 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
434 "Scope execution is not supported on non-local systems.");
d21ed1ea 435
baaa35ad
ZJS
436 if (arg_scope && (arg_remain_after_exit || arg_service_type))
437 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
438 "--remain-after-exit and --service-type= are not supported in --scope mode.");
c7040b5d 439
baaa35ad
ZJS
440 if (arg_stdio != ARG_STDIO_NONE && (with_trigger || arg_scope))
441 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
442 "--pty/--pipe is not compatible in timer or --scope mode.");
9b15b784 443
baaa35ad
ZJS
444 if (arg_stdio != ARG_STDIO_NONE && arg_transport == BUS_TRANSPORT_REMOTE)
445 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
446 "--pty/--pipe is only supported when connecting to the local system or containers.");
024a8ec1 447
baaa35ad
ZJS
448 if (arg_stdio != ARG_STDIO_NONE && arg_no_block)
449 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
450 "--pty/--pipe is not compatible with --no-block.");
578c03bc 451
baaa35ad
ZJS
452 if (arg_scope && with_trigger)
453 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
454 "Path, socket or timer options are not supported in --scope mode.");
4c213d6c 455
baaa35ad
ZJS
456 if (arg_timer_property && !with_timer)
457 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
458 "--timer-property= has no effect without any other timer options.");
4c213d6c 459
2a453c2e 460 if (arg_wait) {
baaa35ad
ZJS
461 if (arg_no_block)
462 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
463 "--wait may not be combined with --no-block.");
2a453c2e 464
baaa35ad
ZJS
465 if (with_trigger)
466 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
467 "--wait may not be combined with path, socket or timer operations.");
2a453c2e 468
baaa35ad
ZJS
469 if (arg_scope)
470 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
471 "--wait may not be combined with --scope.");
2a453c2e
LP
472 }
473
6c12b52e
LP
474 return 1;
475}
476
89ada3ba 477static int transient_unit_set_properties(sd_bus_message *m, UnitType t, char **properties) {
c2756a68
LP
478 int r;
479
9b15b784
LP
480 r = sd_bus_message_append(m, "(sv)", "Description", "s", arg_description);
481 if (r < 0)
f53bddf3 482 return bus_log_create_error(r);
9b15b784 483
fe9d0be9
LP
484 if (arg_aggressive_gc) {
485 r = sd_bus_message_append(m, "(sv)", "CollectMode", "s", "inactive-or-failed");
486 if (r < 0)
f53bddf3 487 return bus_log_create_error(r);
fe9d0be9
LP
488 }
489
89ada3ba 490 r = bus_append_unit_property_assignment_many(m, t, properties);
8673cf13
LP
491 if (r < 0)
492 return r;
df31a6c0 493
9b15b784
LP
494 return 0;
495}
496
497static int transient_cgroup_set_properties(sd_bus_message *m) {
498 int r;
499 assert(m);
c2756a68 500
c221420b 501 if (!isempty(arg_slice)) {
f53bddf3 502 _cleanup_free_ char *slice = NULL;
c221420b 503
37cbc1d5 504 r = unit_name_mangle_with_suffix(arg_slice, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".slice", &slice);
7410616c 505 if (r < 0)
f53bddf3 506 return log_error_errno(r, "Failed to mangle name '%s': %m", arg_slice);
c221420b
LP
507
508 r = sd_bus_message_append(m, "(sv)", "Slice", "s", slice);
509 if (r < 0)
f53bddf3 510 return bus_log_create_error(r);
c221420b
LP
511 }
512
9b15b784
LP
513 return 0;
514}
515
516static int transient_kill_set_properties(sd_bus_message *m) {
f53bddf3
LP
517 int r;
518
9b15b784
LP
519 assert(m);
520
f53bddf3
LP
521 if (arg_send_sighup) {
522 r = sd_bus_message_append(m, "(sv)", "SendSIGHUP", "b", arg_send_sighup);
523 if (r < 0)
524 return bus_log_create_error(r);
525 }
526
527 return 0;
6c12b52e
LP
528}
529
9b15b784 530static int transient_service_set_properties(sd_bus_message *m, char **argv, const char *pty_path) {
5dca7739 531 bool send_term = false;
6c12b52e
LP
532 int r;
533
8159d91a
LP
534 assert(m);
535
89ada3ba 536 r = transient_unit_set_properties(m, UNIT_SERVICE, arg_property);
9b15b784
LP
537 if (r < 0)
538 return r;
539
540 r = transient_kill_set_properties(m);
541 if (r < 0)
542 return r;
543
544 r = transient_cgroup_set_properties(m);
86b8d289
LP
545 if (r < 0)
546 return r;
547
5dca7739 548 if (arg_wait || arg_stdio != ARG_STDIO_NONE) {
2a453c2e
LP
549 r = sd_bus_message_append(m, "(sv)", "AddRef", "b", 1);
550 if (r < 0)
f53bddf3 551 return bus_log_create_error(r);
2a453c2e
LP
552 }
553
df31a6c0
LP
554 if (arg_remain_after_exit) {
555 r = sd_bus_message_append(m, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit);
556 if (r < 0)
f53bddf3 557 return bus_log_create_error(r);
df31a6c0 558 }
6577c7ce 559
c7040b5d
LP
560 if (arg_service_type) {
561 r = sd_bus_message_append(m, "(sv)", "Type", "s", arg_service_type);
562 if (r < 0)
f53bddf3 563 return bus_log_create_error(r);
c7040b5d
LP
564 }
565
566 if (arg_exec_user) {
567 r = sd_bus_message_append(m, "(sv)", "User", "s", arg_exec_user);
568 if (r < 0)
f53bddf3 569 return bus_log_create_error(r);
c7040b5d
LP
570 }
571
572 if (arg_exec_group) {
573 r = sd_bus_message_append(m, "(sv)", "Group", "s", arg_exec_group);
574 if (r < 0)
f53bddf3 575 return bus_log_create_error(r);
c7040b5d
LP
576 }
577
578 if (arg_nice_set) {
579 r = sd_bus_message_append(m, "(sv)", "Nice", "i", arg_nice);
580 if (r < 0)
f53bddf3 581 return bus_log_create_error(r);
c7040b5d
LP
582 }
583
9b15b784 584 if (pty_path) {
9b15b784
LP
585 r = sd_bus_message_append(m,
586 "(sv)(sv)(sv)(sv)",
587 "StandardInput", "s", "tty",
588 "StandardOutput", "s", "tty",
589 "StandardError", "s", "tty",
590 "TTYPath", "s", pty_path);
591 if (r < 0)
f53bddf3 592 return bus_log_create_error(r);
9b15b784 593
5dca7739
LP
594 send_term = true;
595
596 } else if (arg_stdio == ARG_STDIO_DIRECT) {
597 r = sd_bus_message_append(m,
598 "(sv)(sv)(sv)",
599 "StandardInputFileDescriptor", "h", STDIN_FILENO,
600 "StandardOutputFileDescriptor", "h", STDOUT_FILENO,
601 "StandardErrorFileDescriptor", "h", STDERR_FILENO);
602 if (r < 0)
f53bddf3 603 return bus_log_create_error(r);
5dca7739
LP
604
605 send_term = isatty(STDIN_FILENO) || isatty(STDOUT_FILENO) || isatty(STDERR_FILENO);
606 }
607
608 if (send_term) {
609 const char *e;
610
9b15b784
LP
611 e = getenv("TERM");
612 if (e) {
613 char *n;
614
63c372cb 615 n = strjoina("TERM=", e);
9b15b784
LP
616 r = sd_bus_message_append(m,
617 "(sv)",
618 "Environment", "as", 1, n);
619 if (r < 0)
f53bddf3 620 return bus_log_create_error(r);
9b15b784
LP
621 }
622 }
623
c7040b5d
LP
624 if (!strv_isempty(arg_environment)) {
625 r = sd_bus_message_open_container(m, 'r', "sv");
626 if (r < 0)
f53bddf3 627 return bus_log_create_error(r);
c7040b5d
LP
628
629 r = sd_bus_message_append(m, "s", "Environment");
630 if (r < 0)
f53bddf3 631 return bus_log_create_error(r);
c7040b5d
LP
632
633 r = sd_bus_message_open_container(m, 'v', "as");
634 if (r < 0)
f53bddf3 635 return bus_log_create_error(r);
c7040b5d
LP
636
637 r = sd_bus_message_append_strv(m, arg_environment);
638 if (r < 0)
f53bddf3 639 return bus_log_create_error(r);
c7040b5d
LP
640
641 r = sd_bus_message_close_container(m);
642 if (r < 0)
f53bddf3 643 return bus_log_create_error(r);
c7040b5d
LP
644
645 r = sd_bus_message_close_container(m);
646 if (r < 0)
f53bddf3 647 return bus_log_create_error(r);
4c213d6c
WC
648 }
649
650 /* Exec container */
651 {
652 r = sd_bus_message_open_container(m, 'r', "sv");
653 if (r < 0)
f53bddf3 654 return bus_log_create_error(r);
4c213d6c
WC
655
656 r = sd_bus_message_append(m, "s", "ExecStart");
657 if (r < 0)
f53bddf3 658 return bus_log_create_error(r);
4c213d6c
WC
659
660 r = sd_bus_message_open_container(m, 'v', "a(sasb)");
661 if (r < 0)
f53bddf3 662 return bus_log_create_error(r);
4c213d6c
WC
663
664 r = sd_bus_message_open_container(m, 'a', "(sasb)");
665 if (r < 0)
f53bddf3 666 return bus_log_create_error(r);
4c213d6c
WC
667
668 r = sd_bus_message_open_container(m, 'r', "sasb");
669 if (r < 0)
f53bddf3 670 return bus_log_create_error(r);
4c213d6c
WC
671
672 r = sd_bus_message_append(m, "s", argv[0]);
673 if (r < 0)
f53bddf3 674 return bus_log_create_error(r);
4c213d6c
WC
675
676 r = sd_bus_message_append_strv(m, argv);
677 if (r < 0)
f53bddf3 678 return bus_log_create_error(r);
4c213d6c
WC
679
680 r = sd_bus_message_append(m, "b", false);
681 if (r < 0)
f53bddf3 682 return bus_log_create_error(r);
4c213d6c
WC
683
684 r = sd_bus_message_close_container(m);
685 if (r < 0)
f53bddf3 686 return bus_log_create_error(r);
4c213d6c
WC
687
688 r = sd_bus_message_close_container(m);
689 if (r < 0)
f53bddf3 690 return bus_log_create_error(r);
4c213d6c
WC
691
692 r = sd_bus_message_close_container(m);
693 if (r < 0)
f53bddf3 694 return bus_log_create_error(r);
4c213d6c
WC
695
696 r = sd_bus_message_close_container(m);
697 if (r < 0)
f53bddf3 698 return bus_log_create_error(r);
4c213d6c
WC
699 }
700
701 return 0;
702}
703
9b15b784
LP
704static int transient_scope_set_properties(sd_bus_message *m) {
705 int r;
706
707 assert(m);
708
89ada3ba 709 r = transient_unit_set_properties(m, UNIT_SCOPE, arg_property);
9b15b784
LP
710 if (r < 0)
711 return r;
712
713 r = transient_kill_set_properties(m);
714 if (r < 0)
715 return r;
716
37e605f9
LP
717 r = transient_cgroup_set_properties(m);
718 if (r < 0)
719 return r;
720
df0ff127 721 r = sd_bus_message_append(m, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached());
9b15b784 722 if (r < 0)
f53bddf3 723 return bus_log_create_error(r);
9b15b784
LP
724
725 return 0;
726}
727
4c213d6c
WC
728static int transient_timer_set_properties(sd_bus_message *m) {
729 int r;
730
731 assert(m);
732
89ada3ba 733 r = transient_unit_set_properties(m, UNIT_TIMER, arg_timer_property);
4c213d6c
WC
734 if (r < 0)
735 return r;
736
6348d701
LP
737 /* Automatically clean up our transient timers */
738 r = sd_bus_message_append(m, "(sv)", "RemainAfterElapse", "b", false);
739 if (r < 0)
f53bddf3 740 return bus_log_create_error(r);
6348d701 741
4c213d6c
WC
742 return 0;
743}
744
9c8d1e1a
LP
745static int make_unit_name(sd_bus *bus, UnitType t, char **ret) {
746 const char *unique, *id;
747 char *p;
748 int r;
749
750 assert(bus);
751 assert(t >= 0);
752 assert(t < _UNIT_TYPE_MAX);
753
754 r = sd_bus_get_unique_name(bus, &unique);
755 if (r < 0) {
756 sd_id128_t rnd;
757
758 /* We couldn't get the unique name, which is a pretty
759 * common case if we are connected to systemd
760 * directly. In that case, just pick a random uuid as
761 * name */
762
763 r = sd_id128_randomize(&rnd);
764 if (r < 0)
765 return log_error_errno(r, "Failed to generate random run unit name: %m");
766
767 if (asprintf(ret, "run-r" SD_ID128_FORMAT_STR ".%s", SD_ID128_FORMAT_VAL(rnd), unit_type_to_string(t)) < 0)
768 return log_oom();
769
770 return 0;
771 }
772
773 /* We managed to get the unique name, then let's use that to
774 * name our transient units. */
775
776 id = startswith(unique, ":1.");
baaa35ad
ZJS
777 if (!id)
778 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
779 "Unique name %s has unexpected format.",
780 unique);
9c8d1e1a 781
605405c6 782 p = strjoin("run-u", id, ".", unit_type_to_string(t));
9c8d1e1a
LP
783 if (!p)
784 return log_oom();
785
786 *ret = p;
787 return 0;
788}
789
2a453c2e
LP
790typedef struct RunContext {
791 sd_bus *bus;
792 sd_event *event;
793 PTYForward *forward;
794 sd_bus_slot *match;
795
796 /* The exit data of the unit */
797 char *active_state;
798 uint64_t inactive_exit_usec;
799 uint64_t inactive_enter_usec;
800 char *result;
801 uint64_t cpu_usage_nsec;
655aab20
LP
802 uint64_t ip_ingress_bytes;
803 uint64_t ip_egress_bytes;
2a453c2e
LP
804 uint32_t exit_code;
805 uint32_t exit_status;
806} RunContext;
807
808static void run_context_free(RunContext *c) {
809 assert(c);
810
811 c->forward = pty_forward_free(c->forward);
812 c->match = sd_bus_slot_unref(c->match);
813 c->bus = sd_bus_unref(c->bus);
814 c->event = sd_event_unref(c->event);
815
816 free(c->active_state);
817 free(c->result);
818}
819
820static void run_context_check_done(RunContext *c) {
95f1d6bf 821 bool done;
2a453c2e
LP
822
823 assert(c);
824
825 if (c->match)
95f1d6bf
LP
826 done = STRPTR_IN_SET(c->active_state, "inactive", "failed");
827 else
828 done = true;
2a453c2e 829
95f1d6bf
LP
830 if (c->forward && done) /* If the service is gone, it's time to drain the output */
831 done = pty_forward_drain(c->forward);
2a453c2e
LP
832
833 if (done)
834 sd_event_exit(c->event, EXIT_SUCCESS);
835}
836
5b1bad8d 837static int run_context_update(RunContext *c, const char *path) {
2a453c2e
LP
838
839 static const struct bus_properties_map map[] = {
840 { "ActiveState", "s", NULL, offsetof(RunContext, active_state) },
841 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(RunContext, inactive_exit_usec) },
842 { "InactiveEnterTimestampMonotonic", "t", NULL, offsetof(RunContext, inactive_enter_usec) },
843 { "Result", "s", NULL, offsetof(RunContext, result) },
844 { "ExecMainCode", "i", NULL, offsetof(RunContext, exit_code) },
845 { "ExecMainStatus", "i", NULL, offsetof(RunContext, exit_status) },
846 { "CPUUsageNSec", "t", NULL, offsetof(RunContext, cpu_usage_nsec) },
655aab20
LP
847 { "IPIngressBytes", "t", NULL, offsetof(RunContext, ip_ingress_bytes) },
848 { "IPEgressBytes", "t", NULL, offsetof(RunContext, ip_egress_bytes) },
2a453c2e
LP
849 {}
850 };
851
f9e0eefc 852 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2a453c2e
LP
853 int r;
854
855 r = bus_map_all_properties(c->bus,
856 "org.freedesktop.systemd1",
5b1bad8d 857 path,
2a453c2e 858 map,
a7e4861c 859 BUS_MAP_STRDUP,
f9e0eefc 860 &error,
f37f8a61 861 NULL,
2a453c2e
LP
862 c);
863 if (r < 0) {
864 sd_event_exit(c->event, EXIT_FAILURE);
f9e0eefc 865 return log_error_errno(r, "Failed to query unit state: %s", bus_error_message(&error, r));
2a453c2e
LP
866 }
867
868 run_context_check_done(c);
869 return 0;
870}
871
5b1bad8d
LP
872static int on_properties_changed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
873 RunContext *c = userdata;
874
875 assert(m);
876 assert(c);
877
878 return run_context_update(c, sd_bus_message_get_path(m));
879}
880
2a453c2e
LP
881static int pty_forward_handler(PTYForward *f, int rcode, void *userdata) {
882 RunContext *c = userdata;
883
884 assert(f);
885
886 if (rcode < 0) {
887 sd_event_exit(c->event, EXIT_FAILURE);
888 return log_error_errno(rcode, "Error on PTY forwarding logic: %m");
889 }
890
891 run_context_check_done(c);
892 return 0;
893}
894
4c213d6c
WC
895static int start_transient_service(
896 sd_bus *bus,
2a453c2e
LP
897 char **argv,
898 int *retval) {
4c213d6c 899
4afd3348
LP
900 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
901 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
3d161f99 902 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
ee451d76 903 _cleanup_free_ char *service = NULL, *pty_path = NULL;
9b15b784 904 _cleanup_close_ int master = -1;
4c213d6c
WC
905 int r;
906
907 assert(bus);
908 assert(argv);
2a453c2e 909 assert(retval);
4c213d6c 910
5dca7739 911 if (arg_stdio == ARG_STDIO_PTY) {
9b15b784 912
ee451d76 913 if (arg_transport == BUS_TRANSPORT_LOCAL) {
669fc4e5 914 master = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
ee451d76
LP
915 if (master < 0)
916 return log_error_errno(errno, "Failed to acquire pseudo tty: %m");
917
918 r = ptsname_malloc(master, &pty_path);
919 if (r < 0)
920 return log_error_errno(r, "Failed to determine tty name: %m");
921
395745ba
LP
922 if (unlockpt(master) < 0)
923 return log_error_errno(errno, "Failed to unlock tty: %m");
924
de33fc62 925 } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
4afd3348 926 _cleanup_(sd_bus_unrefp) sd_bus *system_bus = NULL;
20fc5811 927 _cleanup_(sd_bus_message_unrefp) sd_bus_message *pty_reply = NULL;
ee451d76
LP
928 const char *s;
929
024a8ec1 930 r = sd_bus_default_system(&system_bus);
ee451d76 931 if (r < 0)
024a8ec1 932 return log_error_errno(r, "Failed to connect to system bus: %m");
ee451d76
LP
933
934 r = sd_bus_call_method(system_bus,
935 "org.freedesktop.machine1",
936 "/org/freedesktop/machine1",
937 "org.freedesktop.machine1.Manager",
938 "OpenMachinePTY",
939 &error,
20fc5811 940 &pty_reply,
ee451d76 941 "s", arg_host);
4ae25393
YW
942 if (r < 0)
943 return log_error_errno(r, "Failed to get machine PTY: %s", bus_error_message(&error, -r));
ee451d76 944
20fc5811 945 r = sd_bus_message_read(pty_reply, "hs", &master, &s);
ee451d76
LP
946 if (r < 0)
947 return bus_log_parse_error(r);
948
949 master = fcntl(master, F_DUPFD_CLOEXEC, 3);
950 if (master < 0)
951 return log_error_errno(errno, "Failed to duplicate master fd: %m");
952
953 pty_path = strdup(s);
954 if (!pty_path)
955 return log_oom();
956 } else
957 assert_not_reached("Can't allocate tty via ssh");
9b15b784
LP
958 }
959
3d161f99
LP
960 if (!arg_no_block) {
961 r = bus_wait_for_jobs_new(bus, &w);
962 if (r < 0)
963 return log_error_errno(r, "Could not watch jobs: %m");
964 }
965
4c213d6c 966 if (arg_unit) {
37cbc1d5 967 r = unit_name_mangle_with_suffix(arg_unit, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".service", &service);
7410616c
LP
968 if (r < 0)
969 return log_error_errno(r, "Failed to mangle unit name: %m");
9c8d1e1a
LP
970 } else {
971 r = make_unit_name(bus, UNIT_SERVICE, &service);
972 if (r < 0)
973 return r;
974 }
4c213d6c
WC
975
976 r = sd_bus_message_new_method_call(
977 bus,
978 &m,
979 "org.freedesktop.systemd1",
980 "/org/freedesktop/systemd1",
981 "org.freedesktop.systemd1.Manager",
982 "StartTransientUnit");
9f2e86af 983 if (r < 0)
7040b626 984 return bus_log_create_error(r);
9f2e86af 985
8c7db2fb
EV
986 r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
987 if (r < 0)
988 return bus_log_create_error(r);
989
9b15b784 990 /* Name and mode */
4c213d6c 991 r = sd_bus_message_append(m, "ss", service, "fail");
c2756a68 992 if (r < 0)
7040b626 993 return bus_log_create_error(r);
c2756a68 994
9b15b784 995 /* Properties */
4c213d6c 996 r = sd_bus_message_open_container(m, 'a', "(sv)");
c2756a68 997 if (r < 0)
7040b626 998 return bus_log_create_error(r);
c2756a68 999
9b15b784 1000 r = transient_service_set_properties(m, argv, pty_path);
c2756a68 1001 if (r < 0)
f53bddf3 1002 return r;
c2756a68 1003
4c213d6c 1004 r = sd_bus_message_close_container(m);
c2756a68 1005 if (r < 0)
7040b626 1006 return bus_log_create_error(r);
c2756a68 1007
9b15b784 1008 /* Auxiliary units */
4c213d6c 1009 r = sd_bus_message_append(m, "a(sa(sv))", 0);
c2756a68 1010 if (r < 0)
7040b626 1011 return bus_log_create_error(r);
c2756a68 1012
8a4b13c5 1013 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
8c7db2fb 1014
3d161f99 1015 r = sd_bus_call(bus, m, 0, &error, &reply);
024a8ec1
LP
1016 if (r < 0)
1017 return log_error_errno(r, "Failed to start transient service unit: %s", bus_error_message(&error, r));
c2756a68 1018
3d161f99
LP
1019 if (w) {
1020 const char *object;
1021
1022 r = sd_bus_message_read(reply, "o", &object);
1023 if (r < 0)
1024 return bus_log_parse_error(r);
1025
1026 r = bus_wait_for_jobs_one(w, object, arg_quiet);
1027 if (r < 0)
1028 return r;
1029 }
1030
2a453c2e
LP
1031 if (!arg_quiet)
1032 log_info("Running as unit: %s", service);
1033
5dca7739 1034 if (arg_wait || arg_stdio != ARG_STDIO_NONE) {
655aab20
LP
1035 _cleanup_(run_context_free) RunContext c = {
1036 .cpu_usage_nsec = NSEC_INFINITY,
1037 .ip_ingress_bytes = UINT64_MAX,
1038 .ip_egress_bytes = UINT64_MAX,
1039 .inactive_exit_usec = USEC_INFINITY,
1040 .inactive_enter_usec = USEC_INFINITY,
1041 };
95f1d6bf 1042 _cleanup_free_ char *path = NULL;
4c213d6c 1043
2a453c2e
LP
1044 c.bus = sd_bus_ref(bus);
1045
1046 r = sd_event_default(&c.event);
4c213d6c 1047 if (r < 0)
9b15b784 1048 return log_error_errno(r, "Failed to get event loop: %m");
4c213d6c 1049
2a453c2e
LP
1050 if (master >= 0) {
1051 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGWINCH, SIGTERM, SIGINT, -1) >= 0);
1052 (void) sd_event_add_signal(c.event, NULL, SIGINT, NULL, NULL);
1053 (void) sd_event_add_signal(c.event, NULL, SIGTERM, NULL, NULL);
1054
1055 if (!arg_quiet)
1056 log_info("Press ^] three times within 1s to disconnect TTY.");
4c213d6c 1057
2a453c2e
LP
1058 r = pty_forward_new(c.event, master, PTY_FORWARD_IGNORE_INITIAL_VHANGUP, &c.forward);
1059 if (r < 0)
1060 return log_error_errno(r, "Failed to create PTY forwarder: %m");
1061
1062 pty_forward_set_handler(c.forward, pty_forward_handler, &c);
d147457c
LP
1063
1064 /* Make sure to process any TTY events before we process bus events */
1065 (void) pty_forward_set_priority(c.forward, SD_EVENT_PRIORITY_IMPORTANT);
2a453c2e 1066 }
4c213d6c 1067
95f1d6bf
LP
1068 path = unit_dbus_path_from_name(service);
1069 if (!path)
1070 return log_oom();
2a453c2e 1071
75152a4d
LP
1072 r = sd_bus_match_signal_async(
1073 bus,
1074 &c.match,
1075 "org.freedesktop.systemd1",
1076 path,
1077 "org.freedesktop.DBus.Properties",
1078 "PropertiesChanged",
1079 on_properties_changed, NULL, &c);
95f1d6bf 1080 if (r < 0)
75152a4d 1081 return log_error_errno(r, "Failed to request properties changed signal match: %m");
4c213d6c 1082
d147457c 1083 r = sd_bus_attach_event(bus, c.event, SD_EVENT_PRIORITY_NORMAL);
95f1d6bf 1084 if (r < 0)
75152a4d 1085 return log_error_errno(r, "Failed to attach bus to event loop: %m");
5b1bad8d 1086
95f1d6bf
LP
1087 r = run_context_update(&c, path);
1088 if (r < 0)
1089 return r;
2a453c2e
LP
1090
1091 r = sd_event_loop(c.event);
4c213d6c 1092 if (r < 0)
9b15b784 1093 return log_error_errno(r, "Failed to run event loop: %m");
4c213d6c 1094
2a453c2e
LP
1095 if (c.forward) {
1096 char last_char = 0;
4c213d6c 1097
2a453c2e
LP
1098 r = pty_forward_get_last_char(c.forward, &last_char);
1099 if (r >= 0 && !arg_quiet && last_char != '\n')
1100 fputc('\n', stdout);
1101 }
4c213d6c 1102
95f1d6bf 1103 if (arg_wait && !arg_quiet) {
9182fb52
LP
1104
1105 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, in its
1106 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1107 * way. */
1108 c.forward = pty_forward_free(c.forward);
1109
2a453c2e
LP
1110 if (!isempty(c.result))
1111 log_info("Finished with result: %s", strna(c.result));
9f2e86af 1112
2a453c2e
LP
1113 if (c.exit_code == CLD_EXITED)
1114 log_info("Main processes terminated with: code=%s/status=%i", sigchld_code_to_string(c.exit_code), c.exit_status);
1115 else if (c.exit_code > 0)
1116 log_info("Main processes terminated with: code=%s/status=%s", sigchld_code_to_string(c.exit_code), signal_to_string(c.exit_status));
1117
1118 if (c.inactive_enter_usec > 0 && c.inactive_enter_usec != USEC_INFINITY &&
1119 c.inactive_exit_usec > 0 && c.inactive_exit_usec != USEC_INFINITY &&
1120 c.inactive_enter_usec > c.inactive_exit_usec) {
1121 char ts[FORMAT_TIMESPAN_MAX];
1122 log_info("Service runtime: %s", format_timespan(ts, sizeof(ts), c.inactive_enter_usec - c.inactive_exit_usec, USEC_PER_MSEC));
1123 }
1124
655aab20 1125 if (c.cpu_usage_nsec != NSEC_INFINITY) {
2a453c2e
LP
1126 char ts[FORMAT_TIMESPAN_MAX];
1127 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));
1128 }
655aab20
LP
1129
1130 if (c.ip_ingress_bytes != UINT64_MAX) {
1131 char bytes[FORMAT_BYTES_MAX];
1132 log_info("IP traffic received: %s", format_bytes(bytes, sizeof(bytes), c.ip_ingress_bytes));
1133 }
1134 if (c.ip_egress_bytes != UINT64_MAX) {
1135 char bytes[FORMAT_BYTES_MAX];
1136 log_info("IP traffic sent: %s", format_bytes(bytes, sizeof(bytes), c.ip_egress_bytes));
1137 }
2a453c2e
LP
1138 }
1139
1140 /* Try to propagate the service's return value */
1141 if (c.result && STR_IN_SET(c.result, "success", "exit-code") && c.exit_code == CLD_EXITED)
1142 *retval = c.exit_status;
1143 else
1144 *retval = EXIT_FAILURE;
1145 }
7040b626
LP
1146
1147 return 0;
6c12b52e
LP
1148}
1149
1150static int start_transient_scope(
1151 sd_bus *bus,
ee451d76 1152 char **argv) {
6c12b52e 1153
4afd3348
LP
1154 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1155 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
de158ed2 1156 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
9b15b784 1157 _cleanup_strv_free_ char **env = NULL, **user_env = NULL;
4c213d6c 1158 _cleanup_free_ char *scope = NULL;
de158ed2 1159 const char *object = NULL;
6c12b52e
LP
1160 int r;
1161
8159d91a 1162 assert(bus);
4c213d6c 1163 assert(argv);
8159d91a 1164
de158ed2
LP
1165 r = bus_wait_for_jobs_new(bus, &w);
1166 if (r < 0)
1167 return log_oom();
1168
7de80bfe 1169 if (arg_unit) {
37cbc1d5 1170 r = unit_name_mangle_with_suffix(arg_unit, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".scope", &scope);
7410616c
LP
1171 if (r < 0)
1172 return log_error_errno(r, "Failed to mangle scope name: %m");
9c8d1e1a
LP
1173 } else {
1174 r = make_unit_name(bus, UNIT_SCOPE, &scope);
1175 if (r < 0)
1176 return r;
1177 }
6c12b52e 1178
4c213d6c 1179 r = sd_bus_message_new_method_call(
9b15b784
LP
1180 bus,
1181 &m,
1182 "org.freedesktop.systemd1",
1183 "/org/freedesktop/systemd1",
1184 "org.freedesktop.systemd1.Manager",
1185 "StartTransientUnit");
c2756a68 1186 if (r < 0)
7040b626 1187 return bus_log_create_error(r);
c2756a68 1188
8c7db2fb
EV
1189 r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
1190 if (r < 0)
1191 return bus_log_create_error(r);
1192
9b15b784 1193 /* Name and Mode */
4c213d6c
WC
1194 r = sd_bus_message_append(m, "ss", scope, "fail");
1195 if (r < 0)
1196 return bus_log_create_error(r);
1197
9b15b784 1198 /* Properties */
4c213d6c
WC
1199 r = sd_bus_message_open_container(m, 'a', "(sv)");
1200 if (r < 0)
1201 return bus_log_create_error(r);
1202
1203 r = transient_scope_set_properties(m);
1204 if (r < 0)
f53bddf3 1205 return r;
4c213d6c
WC
1206
1207 r = sd_bus_message_close_container(m);
1208 if (r < 0)
1209 return bus_log_create_error(r);
1210
ee451d76 1211 /* Auxiliary units */
4c213d6c 1212 r = sd_bus_message_append(m, "a(sa(sv))", 0);
6c12b52e 1213 if (r < 0)
7040b626 1214 return bus_log_create_error(r);
6c12b52e 1215
8a4b13c5 1216 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
8c7db2fb 1217
de158ed2 1218 r = sd_bus_call(bus, m, 0, &error, &reply);
4ae25393
YW
1219 if (r < 0)
1220 return log_error_errno(r, "Failed to start transient scope unit: %s", bus_error_message(&error, -r));
c2756a68 1221
4de33e7f 1222 if (arg_nice_set) {
4a62c710
MS
1223 if (setpriority(PRIO_PROCESS, 0, arg_nice) < 0)
1224 return log_error_errno(errno, "Failed to set nice level: %m");
4de33e7f
LP
1225 }
1226
1227 if (arg_exec_group) {
1228 gid_t gid;
1229
fafff8f1 1230 r = get_group_creds(&arg_exec_group, &gid, 0);
f647962d
MS
1231 if (r < 0)
1232 return log_error_errno(r, "Failed to resolve group %s: %m", arg_exec_group);
4de33e7f 1233
4a62c710
MS
1234 if (setresgid(gid, gid, gid) < 0)
1235 return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
4de33e7f
LP
1236 }
1237
1238 if (arg_exec_user) {
1239 const char *home, *shell;
1240 uid_t uid;
1241 gid_t gid;
1242
43ad3ad7 1243 r = get_user_creds(&arg_exec_user, &uid, &gid, &home, &shell, USER_CREDS_CLEAN|USER_CREDS_PREFER_NSS);
f647962d
MS
1244 if (r < 0)
1245 return log_error_errno(r, "Failed to resolve user %s: %m", arg_exec_user);
4de33e7f 1246
be39ccf3
LP
1247 if (home) {
1248 r = strv_extendf(&user_env, "HOME=%s", home);
1249 if (r < 0)
1250 return log_oom();
1251 }
4de33e7f 1252
be39ccf3
LP
1253 if (shell) {
1254 r = strv_extendf(&user_env, "SHELL=%s", shell);
1255 if (r < 0)
1256 return log_oom();
1257 }
4de33e7f
LP
1258
1259 r = strv_extendf(&user_env, "USER=%s", arg_exec_user);
1260 if (r < 0)
1261 return log_oom();
1262
1263 r = strv_extendf(&user_env, "LOGNAME=%s", arg_exec_user);
1264 if (r < 0)
1265 return log_oom();
1266
1267 if (!arg_exec_group) {
4a62c710
MS
1268 if (setresgid(gid, gid, gid) < 0)
1269 return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
4de33e7f
LP
1270 }
1271
4a62c710
MS
1272 if (setresuid(uid, uid, uid) < 0)
1273 return log_error_errno(errno, "Failed to change UID to " UID_FMT ": %m", uid);
4de33e7f
LP
1274 }
1275
1276 env = strv_env_merge(3, environ, user_env, arg_environment);
1277 if (!env)
1278 return log_oom();
1279
de158ed2
LP
1280 r = sd_bus_message_read(reply, "o", &object);
1281 if (r < 0)
1282 return bus_log_parse_error(r);
1283
1284 r = bus_wait_for_jobs_one(w, object, arg_quiet);
1285 if (r < 0)
1286 return r;
1287
095dc596 1288 if (!arg_quiet)
f3ea87af 1289 log_info("Running scope as unit: %s", scope);
7040b626 1290
4de33e7f 1291 execvpe(argv[0], argv, env);
9b15b784
LP
1292
1293 return log_error_errno(errno, "Failed to execute: %m");
1294}
1295
d59ef3e2 1296static int start_transient_trigger(
9b15b784 1297 sd_bus *bus,
d59ef3e2
YW
1298 char **argv,
1299 const char *suffix) {
9b15b784 1300
4afd3348
LP
1301 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1302 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
de158ed2 1303 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
d59ef3e2 1304 _cleanup_free_ char *trigger = NULL, *service = NULL;
de158ed2 1305 const char *object = NULL;
9b15b784
LP
1306 int r;
1307
1308 assert(bus);
1309 assert(argv);
1310
de158ed2
LP
1311 r = bus_wait_for_jobs_new(bus, &w);
1312 if (r < 0)
1313 return log_oom();
1314
9b15b784 1315 if (arg_unit) {
7410616c 1316 switch (unit_name_to_type(arg_unit)) {
9b15b784
LP
1317
1318 case UNIT_SERVICE:
1319 service = strdup(arg_unit);
1320 if (!service)
1321 return log_oom();
1322
d59ef3e2 1323 r = unit_name_change_suffix(service, suffix, &trigger);
7410616c
LP
1324 if (r < 0)
1325 return log_error_errno(r, "Failed to change unit suffix: %m");
9b15b784
LP
1326 break;
1327
1328 case UNIT_TIMER:
d59ef3e2
YW
1329 trigger = strdup(arg_unit);
1330 if (!trigger)
9b15b784
LP
1331 return log_oom();
1332
d59ef3e2 1333 r = unit_name_change_suffix(trigger, ".service", &service);
7410616c
LP
1334 if (r < 0)
1335 return log_error_errno(r, "Failed to change unit suffix: %m");
9b15b784
LP
1336 break;
1337
1338 default:
37cbc1d5 1339 r = unit_name_mangle_with_suffix(arg_unit, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".service", &service);
7410616c
LP
1340 if (r < 0)
1341 return log_error_errno(r, "Failed to mangle unit name: %m");
9b15b784 1342
37cbc1d5 1343 r = unit_name_mangle_with_suffix(arg_unit, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, suffix, &trigger);
7410616c
LP
1344 if (r < 0)
1345 return log_error_errno(r, "Failed to mangle unit name: %m");
9b15b784
LP
1346
1347 break;
1348 }
9c8d1e1a
LP
1349 } else {
1350 r = make_unit_name(bus, UNIT_SERVICE, &service);
1351 if (r < 0)
1352 return r;
1353
d59ef3e2 1354 r = unit_name_change_suffix(service, suffix, &trigger);
9c8d1e1a
LP
1355 if (r < 0)
1356 return log_error_errno(r, "Failed to change unit suffix: %m");
1357 }
9b15b784
LP
1358
1359 r = sd_bus_message_new_method_call(
1360 bus,
1361 &m,
1362 "org.freedesktop.systemd1",
1363 "/org/freedesktop/systemd1",
1364 "org.freedesktop.systemd1.Manager",
1365 "StartTransientUnit");
1366 if (r < 0)
1367 return bus_log_create_error(r);
1368
8c7db2fb
EV
1369 r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
1370 if (r < 0)
1371 return bus_log_create_error(r);
1372
9b15b784 1373 /* Name and Mode */
d59ef3e2 1374 r = sd_bus_message_append(m, "ss", trigger, "fail");
9b15b784
LP
1375 if (r < 0)
1376 return bus_log_create_error(r);
1377
1378 /* Properties */
1379 r = sd_bus_message_open_container(m, 'a', "(sv)");
1380 if (r < 0)
1381 return bus_log_create_error(r);
1382
d59ef3e2
YW
1383 if (streq(suffix, ".path"))
1384 r = transient_unit_set_properties(m, UNIT_PATH, arg_path_property);
1385 else if (streq(suffix, ".socket"))
1386 r = transient_unit_set_properties(m, UNIT_SOCKET, arg_socket_property);
1387 else if (streq(suffix, ".timer"))
1388 r = transient_timer_set_properties(m);
1389 else
1390 assert_not_reached("Invalid suffix");
9b15b784 1391 if (r < 0)
f53bddf3 1392 return r;
9b15b784
LP
1393
1394 r = sd_bus_message_close_container(m);
1395 if (r < 0)
1396 return bus_log_create_error(r);
1397
1398 r = sd_bus_message_open_container(m, 'a', "(sa(sv))");
1399 if (r < 0)
1400 return bus_log_create_error(r);
1401
ad2c1701 1402 if (!strv_isempty(argv)) {
9b15b784
LP
1403 r = sd_bus_message_open_container(m, 'r', "sa(sv)");
1404 if (r < 0)
1405 return bus_log_create_error(r);
1406
1407 r = sd_bus_message_append(m, "s", service);
1408 if (r < 0)
1409 return bus_log_create_error(r);
1410
1411 r = sd_bus_message_open_container(m, 'a', "(sv)");
1412 if (r < 0)
1413 return bus_log_create_error(r);
1414
1415 r = transient_service_set_properties(m, argv, NULL);
1416 if (r < 0)
f53bddf3 1417 return r;
9b15b784
LP
1418
1419 r = sd_bus_message_close_container(m);
1420 if (r < 0)
1421 return bus_log_create_error(r);
1422
1423 r = sd_bus_message_close_container(m);
1424 if (r < 0)
1425 return bus_log_create_error(r);
1426 }
1427
1428 r = sd_bus_message_close_container(m);
1429 if (r < 0)
1430 return bus_log_create_error(r);
1431
8a4b13c5 1432 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
8c7db2fb 1433
de158ed2 1434 r = sd_bus_call(bus, m, 0, &error, &reply);
4ae25393
YW
1435 if (r < 0)
1436 return log_error_errno(r, "Failed to start transient %s unit: %s", suffix + 1, bus_error_message(&error, -r));
9b15b784 1437
de158ed2
LP
1438 r = sd_bus_message_read(reply, "o", &object);
1439 if (r < 0)
1440 return bus_log_parse_error(r);
1441
1442 r = bus_wait_for_jobs_one(w, object, arg_quiet);
1443 if (r < 0)
1444 return r;
1445
3dea75de 1446 if (!arg_quiet) {
d59ef3e2 1447 log_info("Running %s as unit: %s", suffix + 1, trigger);
3dea75de
NO
1448 if (argv[0])
1449 log_info("Will run service as unit: %s", service);
1450 }
9b15b784
LP
1451
1452 return 0;
c2756a68
LP
1453}
1454
1455int main(int argc, char* argv[]) {
4afd3348 1456 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
c9d954b2 1457 _cleanup_free_ char *description = NULL, *command = NULL;
2a453c2e 1458 int r, retval = EXIT_SUCCESS;
c2756a68
LP
1459
1460 log_parse_environment();
1461 log_open();
1462
6c12b52e
LP
1463 r = parse_argv(argc, argv);
1464 if (r <= 0)
66b1e746 1465 goto finish;
c2756a68 1466
85eca92e
LP
1467 if (argc > optind && arg_transport == BUS_TRANSPORT_LOCAL) {
1468 /* Patch in an absolute path */
1469
1470 r = find_binary(argv[optind], &command);
4c213d6c 1471 if (r < 0) {
85eca92e
LP
1472 log_error_errno(r, "Failed to find executable %s: %m", argv[optind]);
1473 goto finish;
1474 }
85eca92e 1475
4c213d6c 1476 argv[optind] = command;
c9d954b2 1477 }
c9d954b2 1478
9f2e86af
LP
1479 if (!arg_description) {
1480 description = strv_join(argv + optind, " ");
1481 if (!description) {
1482 r = log_oom();
66b1e746 1483 goto finish;
9f2e86af
LP
1484 }
1485
4c213d6c 1486 if (arg_unit && isempty(description)) {
2fc09a9c
DM
1487 r = free_and_strdup(&description, arg_unit);
1488 if (r < 0)
4c213d6c 1489 goto finish;
4c213d6c
WC
1490 }
1491
9f2e86af
LP
1492 arg_description = description;
1493 }
1494
2a453c2e
LP
1495 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the limited direct
1496 * connection */
5dca7739 1497 if (arg_wait || arg_stdio != ARG_STDIO_NONE)
2a453c2e
LP
1498 r = bus_connect_transport(arg_transport, arg_host, arg_user, &bus);
1499 else
1500 r = bus_connect_transport_systemd(arg_transport, arg_host, arg_user, &bus);
c2756a68 1501 if (r < 0) {
da927ba9 1502 log_error_errno(r, "Failed to create bus connection: %m");
66b1e746 1503 goto finish;
c2756a68
LP
1504 }
1505
6c12b52e 1506 if (arg_scope)
ee451d76 1507 r = start_transient_scope(bus, argv + optind);
d59ef3e2
YW
1508 else if (arg_path_property)
1509 r = start_transient_trigger(bus, argv + optind, ".path");
1510 else if (arg_socket_property)
1511 r = start_transient_trigger(bus, argv + optind, ".socket");
f2b9f2c8 1512 else if (with_timer)
d59ef3e2 1513 r = start_transient_trigger(bus, argv + optind, ".timer");
6c12b52e 1514 else
2a453c2e 1515 r = start_transient_service(bus, argv + optind, &retval);
c2756a68 1516
66b1e746 1517finish:
df31a6c0
LP
1518 strv_free(arg_environment);
1519 strv_free(arg_property);
d59ef3e2
YW
1520 strv_free(arg_path_property);
1521 strv_free(arg_socket_property);
4c213d6c 1522 strv_free(arg_timer_property);
df31a6c0 1523
2a453c2e 1524 return r < 0 ? EXIT_FAILURE : retval;
c2756a68 1525}