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