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