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