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