]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/run/run.c
Merge pull request #30284 from YHNdnzj/fstab-wantedby-defaultdeps
[thirdparty/systemd.git] / src / run / run.c
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <getopt.h>
4 #include <stdio.h>
5 #include <fcntl.h>
6 #include <sys/stat.h>
7 #include <sys/types.h>
8
9 #include "sd-bus.h"
10 #include "sd-event.h"
11
12 #include "alloc-util.h"
13 #include "build.h"
14 #include "bus-error.h"
15 #include "bus-locator.h"
16 #include "bus-map-properties.h"
17 #include "bus-unit-util.h"
18 #include "bus-wait-for-jobs.h"
19 #include "calendarspec.h"
20 #include "color-util.h"
21 #include "env-util.h"
22 #include "escape.h"
23 #include "exit-status.h"
24 #include "fd-util.h"
25 #include "format-util.h"
26 #include "main-func.h"
27 #include "parse-argument.h"
28 #include "parse-util.h"
29 #include "path-util.h"
30 #include "pretty-print.h"
31 #include "process-util.h"
32 #include "ptyfwd.h"
33 #include "signal-util.h"
34 #include "spawn-polkit-agent.h"
35 #include "strv.h"
36 #include "terminal-util.h"
37 #include "unit-def.h"
38 #include "unit-name.h"
39 #include "user-util.h"
40
41 static bool arg_ask_password = true;
42 static bool arg_scope = false;
43 static bool arg_remain_after_exit = false;
44 static bool arg_no_block = false;
45 static bool arg_wait = false;
46 static const char *arg_unit = NULL;
47 static char *arg_description = NULL;
48 static const char *arg_slice = NULL;
49 static bool arg_slice_inherit = false;
50 static int arg_expand_environment = -1;
51 static bool arg_send_sighup = false;
52 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
53 static const char *arg_host = NULL;
54 static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
55 static const char *arg_service_type = NULL;
56 static const char *arg_exec_user = NULL;
57 static const char *arg_exec_group = NULL;
58 static int arg_nice = 0;
59 static bool arg_nice_set = false;
60 static char **arg_environment = NULL;
61 static char **arg_property = NULL;
62 static enum {
63 ARG_STDIO_NONE, /* The default, as it is for normal services, stdin connected to /dev/null, and stdout+stderr to the journal */
64 ARG_STDIO_PTY, /* Interactive behaviour, requested by --pty: we allocate a pty and connect it to the TTY we are invoked from */
65 ARG_STDIO_DIRECT, /* Directly pass our stdin/stdout/stderr to the activated service, useful for usage in shell pipelines, requested by --pipe */
66 ARG_STDIO_AUTO, /* If --pipe and --pty are used together we use --pty when invoked on a TTY, and --pipe otherwise */
67 } arg_stdio = ARG_STDIO_NONE;
68 static char **arg_path_property = NULL;
69 static char **arg_socket_property = NULL;
70 static char **arg_timer_property = NULL;
71 static bool arg_with_timer = false;
72 static bool arg_quiet = false;
73 static bool arg_aggressive_gc = false;
74 static char *arg_working_directory = NULL;
75 static bool arg_shell = false;
76 static char **arg_cmdline = NULL;
77 static char *arg_exec_path = NULL;
78 static bool arg_ignore_failure = false;
79 static char *arg_background = NULL;
80
81 STATIC_DESTRUCTOR_REGISTER(arg_description, freep);
82 STATIC_DESTRUCTOR_REGISTER(arg_environment, strv_freep);
83 STATIC_DESTRUCTOR_REGISTER(arg_property, strv_freep);
84 STATIC_DESTRUCTOR_REGISTER(arg_path_property, strv_freep);
85 STATIC_DESTRUCTOR_REGISTER(arg_socket_property, strv_freep);
86 STATIC_DESTRUCTOR_REGISTER(arg_timer_property, strv_freep);
87 STATIC_DESTRUCTOR_REGISTER(arg_working_directory, freep);
88 STATIC_DESTRUCTOR_REGISTER(arg_cmdline, strv_freep);
89 STATIC_DESTRUCTOR_REGISTER(arg_exec_path, freep);
90 STATIC_DESTRUCTOR_REGISTER(arg_background, freep);
91
92 static int help(void) {
93 _cleanup_free_ char *link = NULL;
94 int r;
95
96 r = terminal_urlify_man("systemd-run", "1", &link);
97 if (r < 0)
98 return log_oom();
99
100 printf("%1$s [OPTIONS...] COMMAND [ARGUMENTS...]\n"
101 "\n%5$sRun the specified command in a transient scope or service.%6$s\n\n"
102 " -h --help Show this help\n"
103 " --version Show package version\n"
104 " --no-ask-password Do not prompt for password\n"
105 " --user Run as user unit\n"
106 " -H --host=[USER@]HOST Operate on remote host\n"
107 " -M --machine=CONTAINER Operate on local container\n"
108 " --scope Run this as scope rather than service\n"
109 " -u --unit=UNIT Run under the specified unit name\n"
110 " -p --property=NAME=VALUE Set service or scope unit property\n"
111 " --description=TEXT Description for unit\n"
112 " --slice=SLICE Run in the specified slice\n"
113 " --slice-inherit Inherit the slice from the caller\n"
114 " --expand-environment=BOOL Control expansion of environment variables\n"
115 " --no-block Do not wait until operation finished\n"
116 " -r --remain-after-exit Leave service around until explicitly stopped\n"
117 " --wait Wait until service stopped again\n"
118 " --send-sighup Send SIGHUP when terminating\n"
119 " --service-type=TYPE Service type\n"
120 " --uid=USER Run as system user\n"
121 " --gid=GROUP Run as system group\n"
122 " --nice=NICE Nice level\n"
123 " --working-directory=PATH Set working directory\n"
124 " -d --same-dir Inherit working directory from caller\n"
125 " -E --setenv=NAME[=VALUE] Set environment variable\n"
126 " -t --pty Run service on pseudo TTY as STDIN/STDOUT/\n"
127 " STDERR\n"
128 " -P --pipe Pass STDIN/STDOUT/STDERR directly to service\n"
129 " -q --quiet Suppress information messages during runtime\n"
130 " -G --collect Unload unit after it ran, even when failed\n"
131 " -S --shell Invoke a $SHELL interactively\n"
132 " --ignore-failure Ignore the exit status of the invoked process\n"
133 " --background=COLOR Set ANSI color for background\n"
134 "\n%3$sPath options:%4$s\n"
135 " --path-property=NAME=VALUE Set path unit property\n"
136 "\n%3$sSocket options:%4$s\n"
137 " --socket-property=NAME=VALUE Set socket unit property\n"
138 "\n%3$sTimer options:%4$s\n"
139 " --on-active=SECONDS Run after SECONDS delay\n"
140 " --on-boot=SECONDS Run SECONDS after machine was booted up\n"
141 " --on-startup=SECONDS Run SECONDS after systemd activation\n"
142 " --on-unit-active=SECONDS Run SECONDS after the last activation\n"
143 " --on-unit-inactive=SECONDS Run SECONDS after the last deactivation\n"
144 " --on-calendar=SPEC Realtime timer\n"
145 " --on-timezone-change Run when the timezone changes\n"
146 " --on-clock-change Run when the realtime clock jumps\n"
147 " --timer-property=NAME=VALUE Set timer unit property\n"
148 "\nSee the %2$s for details.\n",
149 program_invocation_short_name,
150 link,
151 ansi_underline(), ansi_normal(),
152 ansi_highlight(), ansi_normal());
153
154 return 0;
155 }
156
157 static int help_sudo_mode(void) {
158 _cleanup_free_ char *link = NULL;
159 int r;
160
161 r = terminal_urlify_man("uid0", "1", &link);
162 if (r < 0)
163 return log_oom();
164
165 printf("%s [OPTIONS...] COMMAND [ARGUMENTS...]\n"
166 "\n%sElevate privileges interactively.%s\n\n"
167 " -h --help Show this help\n"
168 " -V --version Show package version\n"
169 " --no-ask-password Do not prompt for password\n"
170 " --machine=CONTAINER Operate on local container\n"
171 " --unit=UNIT Run under the specified unit name\n"
172 " --property=NAME=VALUE Set service or scope unit property\n"
173 " --description=TEXT Description for unit\n"
174 " --slice=SLICE Run in the specified slice\n"
175 " --slice-inherit Inherit the slice\n"
176 " -u --user=USER Run as system user\n"
177 " -g --group=GROUP Run as system group\n"
178 " --nice=NICE Nice level\n"
179 " -D --chdir=PATH Set working directory\n"
180 " --setenv=NAME[=VALUE] Set environment variable\n"
181 " --background=COLOR Set ANSI color for background\n"
182 "\nSee the %s for details.\n",
183 program_invocation_short_name,
184 ansi_highlight(),
185 ansi_normal(),
186 link);
187
188 return 0;
189 }
190
191 static int add_timer_property(const char *name, const char *val) {
192 char *p;
193
194 assert(name);
195 assert(val);
196
197 p = strjoin(name, "=", val);
198 if (!p)
199 return log_oom();
200
201 if (strv_consume(&arg_timer_property, p) < 0)
202 return log_oom();
203
204 return 0;
205 }
206
207 static char **make_login_shell_cmdline(const char *shell) {
208 _cleanup_free_ char *argv0 = NULL;
209
210 assert(shell);
211
212 argv0 = strjoin("-", shell); /* The - is how shells determine if they shall be consider login shells */
213 if (!argv0)
214 return NULL;
215
216 return strv_new(argv0);
217 }
218
219 static int parse_argv(int argc, char *argv[]) {
220
221 enum {
222 ARG_VERSION = 0x100,
223 ARG_USER,
224 ARG_SYSTEM,
225 ARG_SCOPE,
226 ARG_DESCRIPTION,
227 ARG_SLICE,
228 ARG_SLICE_INHERIT,
229 ARG_EXPAND_ENVIRONMENT,
230 ARG_SEND_SIGHUP,
231 ARG_SERVICE_TYPE,
232 ARG_EXEC_USER,
233 ARG_EXEC_GROUP,
234 ARG_NICE,
235 ARG_ON_ACTIVE,
236 ARG_ON_BOOT,
237 ARG_ON_STARTUP,
238 ARG_ON_UNIT_ACTIVE,
239 ARG_ON_UNIT_INACTIVE,
240 ARG_ON_CALENDAR,
241 ARG_ON_TIMEZONE_CHANGE,
242 ARG_ON_CLOCK_CHANGE,
243 ARG_TIMER_PROPERTY,
244 ARG_PATH_PROPERTY,
245 ARG_SOCKET_PROPERTY,
246 ARG_NO_BLOCK,
247 ARG_NO_ASK_PASSWORD,
248 ARG_WAIT,
249 ARG_WORKING_DIRECTORY,
250 ARG_SHELL,
251 ARG_IGNORE_FAILURE,
252 ARG_BACKGROUND,
253 };
254
255 static const struct option options[] = {
256 { "help", no_argument, NULL, 'h' },
257 { "version", no_argument, NULL, ARG_VERSION },
258 { "user", no_argument, NULL, ARG_USER },
259 { "system", no_argument, NULL, ARG_SYSTEM },
260 { "scope", no_argument, NULL, ARG_SCOPE },
261 { "unit", required_argument, NULL, 'u' },
262 { "description", required_argument, NULL, ARG_DESCRIPTION },
263 { "slice", required_argument, NULL, ARG_SLICE },
264 { "slice-inherit", no_argument, NULL, ARG_SLICE_INHERIT },
265 { "remain-after-exit", no_argument, NULL, 'r' },
266 { "expand-environment", required_argument, NULL, ARG_EXPAND_ENVIRONMENT },
267 { "send-sighup", no_argument, NULL, ARG_SEND_SIGHUP },
268 { "host", required_argument, NULL, 'H' },
269 { "machine", required_argument, NULL, 'M' },
270 { "service-type", required_argument, NULL, ARG_SERVICE_TYPE },
271 { "wait", no_argument, NULL, ARG_WAIT },
272 { "uid", required_argument, NULL, ARG_EXEC_USER },
273 { "gid", required_argument, NULL, ARG_EXEC_GROUP },
274 { "nice", required_argument, NULL, ARG_NICE },
275 { "setenv", required_argument, NULL, 'E' },
276 { "property", required_argument, NULL, 'p' },
277 { "tty", no_argument, NULL, 't' }, /* deprecated alias */
278 { "pty", no_argument, NULL, 't' },
279 { "pipe", no_argument, NULL, 'P' },
280 { "quiet", no_argument, NULL, 'q' },
281 { "on-active", required_argument, NULL, ARG_ON_ACTIVE },
282 { "on-boot", required_argument, NULL, ARG_ON_BOOT },
283 { "on-startup", required_argument, NULL, ARG_ON_STARTUP },
284 { "on-unit-active", required_argument, NULL, ARG_ON_UNIT_ACTIVE },
285 { "on-unit-inactive", required_argument, NULL, ARG_ON_UNIT_INACTIVE },
286 { "on-calendar", required_argument, NULL, ARG_ON_CALENDAR },
287 { "on-timezone-change", no_argument, NULL, ARG_ON_TIMEZONE_CHANGE },
288 { "on-clock-change", no_argument, NULL, ARG_ON_CLOCK_CHANGE },
289 { "timer-property", required_argument, NULL, ARG_TIMER_PROPERTY },
290 { "path-property", required_argument, NULL, ARG_PATH_PROPERTY },
291 { "socket-property", required_argument, NULL, ARG_SOCKET_PROPERTY },
292 { "no-block", no_argument, NULL, ARG_NO_BLOCK },
293 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
294 { "collect", no_argument, NULL, 'G' },
295 { "working-directory", required_argument, NULL, ARG_WORKING_DIRECTORY },
296 { "same-dir", no_argument, NULL, 'd' },
297 { "shell", no_argument, NULL, 'S' },
298 { "ignore-failure", no_argument, NULL, ARG_IGNORE_FAILURE },
299 { "background", no_argument, NULL, ARG_BACKGROUND },
300 {},
301 };
302
303 bool with_trigger = false;
304 int r, c;
305
306 assert(argc >= 0);
307 assert(argv);
308
309 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
310 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
311 optind = 0;
312 while ((c = getopt_long(argc, argv, "+hrH:M:E:p:tPqGdSu:", options, NULL)) >= 0)
313
314 switch (c) {
315
316 case 'h':
317 return help();
318
319 case ARG_VERSION:
320 return version();
321
322 case ARG_NO_ASK_PASSWORD:
323 arg_ask_password = false;
324 break;
325
326 case ARG_USER:
327 arg_runtime_scope = RUNTIME_SCOPE_USER;
328 break;
329
330 case ARG_SYSTEM:
331 arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
332 break;
333
334 case ARG_SCOPE:
335 arg_scope = true;
336 break;
337
338 case 'u':
339 arg_unit = optarg;
340 break;
341
342 case ARG_DESCRIPTION:
343 r = free_and_strdup_warn(&arg_description, optarg);
344 if (r < 0)
345 return r;
346 break;
347
348 case ARG_SLICE:
349 arg_slice = optarg;
350 break;
351
352 case ARG_SLICE_INHERIT:
353 arg_slice_inherit = true;
354 break;
355
356 case ARG_EXPAND_ENVIRONMENT: {
357 bool b;
358
359 r = parse_boolean_argument("--expand-environment=", optarg, &b);
360 if (r < 0)
361 return r;
362
363 arg_expand_environment = b;
364
365 break;
366 }
367
368 case ARG_SEND_SIGHUP:
369 arg_send_sighup = true;
370 break;
371
372 case 'r':
373 arg_remain_after_exit = true;
374 break;
375
376 case 'H':
377 arg_transport = BUS_TRANSPORT_REMOTE;
378 arg_host = optarg;
379 break;
380
381 case 'M':
382 arg_transport = BUS_TRANSPORT_MACHINE;
383 arg_host = optarg;
384 break;
385
386 case ARG_SERVICE_TYPE:
387 arg_service_type = optarg;
388 break;
389
390 case ARG_EXEC_USER:
391 arg_exec_user = optarg;
392 break;
393
394 case ARG_EXEC_GROUP:
395 arg_exec_group = optarg;
396 break;
397
398 case ARG_NICE:
399 r = parse_nice(optarg, &arg_nice);
400 if (r < 0)
401 return log_error_errno(r, "Failed to parse nice value: %s", optarg);
402
403 arg_nice_set = true;
404 break;
405
406 case 'E':
407 r = strv_env_replace_strdup_passthrough(&arg_environment, optarg);
408 if (r < 0)
409 return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
410
411 break;
412
413 case 'p':
414 if (strv_extend(&arg_property, optarg) < 0)
415 return log_oom();
416
417 break;
418
419 case 't': /* --pty */
420 if (IN_SET(arg_stdio, ARG_STDIO_DIRECT, ARG_STDIO_AUTO)) /* if --pipe is already used, upgrade to auto mode */
421 arg_stdio = ARG_STDIO_AUTO;
422 else
423 arg_stdio = ARG_STDIO_PTY;
424 break;
425
426 case 'P': /* --pipe */
427 if (IN_SET(arg_stdio, ARG_STDIO_PTY, ARG_STDIO_AUTO)) /* If --pty is already used, upgrade to auto mode */
428 arg_stdio = ARG_STDIO_AUTO;
429 else
430 arg_stdio = ARG_STDIO_DIRECT;
431 break;
432
433 case 'q':
434 arg_quiet = true;
435 break;
436
437 case ARG_ON_ACTIVE:
438 r = add_timer_property("OnActiveSec", optarg);
439 if (r < 0)
440 return r;
441
442 arg_with_timer = true;
443 break;
444
445 case ARG_ON_BOOT:
446 r = add_timer_property("OnBootSec", optarg);
447 if (r < 0)
448 return r;
449
450 arg_with_timer = true;
451 break;
452
453 case ARG_ON_STARTUP:
454 r = add_timer_property("OnStartupSec", optarg);
455 if (r < 0)
456 return r;
457
458 arg_with_timer = true;
459 break;
460
461 case ARG_ON_UNIT_ACTIVE:
462 r = add_timer_property("OnUnitActiveSec", optarg);
463 if (r < 0)
464 return r;
465
466 arg_with_timer = true;
467 break;
468
469 case ARG_ON_UNIT_INACTIVE:
470 r = add_timer_property("OnUnitInactiveSec", optarg);
471 if (r < 0)
472 return r;
473
474 arg_with_timer = true;
475 break;
476
477 case ARG_ON_CALENDAR: {
478 _cleanup_(calendar_spec_freep) CalendarSpec *cs = NULL;
479
480 r = calendar_spec_from_string(optarg, &cs);
481 if (r < 0)
482 return log_error_errno(r, "Failed to parse calendar event specification: %m");
483
484 /* Let's make sure the given calendar event is not in the past */
485 r = calendar_spec_next_usec(cs, now(CLOCK_REALTIME), NULL);
486 if (r == -ENOENT)
487 /* The calendar event is in the past — let's warn about this, but install it
488 * anyway as is. The service manager will trigger the service right away.
489 * Moreover, the server side might have a different clock or timezone than we
490 * do, hence it should decide when or whether to run something. */
491 log_warning("Specified calendar expression is in the past, proceeding anyway.");
492 else if (r < 0)
493 return log_error_errno(r, "Failed to calculate next time calendar expression elapses: %m");
494
495 r = add_timer_property("OnCalendar", optarg);
496 if (r < 0)
497 return r;
498
499 arg_with_timer = true;
500 break;
501 }
502
503 case ARG_ON_TIMEZONE_CHANGE:
504 r = add_timer_property("OnTimezoneChange", "yes");
505 if (r < 0)
506 return r;
507
508 arg_with_timer = true;
509 break;
510
511 case ARG_ON_CLOCK_CHANGE:
512 r = add_timer_property("OnClockChange", "yes");
513 if (r < 0)
514 return r;
515
516 arg_with_timer = true;
517 break;
518
519 case ARG_TIMER_PROPERTY:
520
521 if (strv_extend(&arg_timer_property, optarg) < 0)
522 return log_oom();
523
524 arg_with_timer = arg_with_timer ||
525 STARTSWITH_SET(optarg,
526 "OnActiveSec=",
527 "OnBootSec=",
528 "OnStartupSec=",
529 "OnUnitActiveSec=",
530 "OnUnitInactiveSec=",
531 "OnCalendar=");
532 break;
533
534 case ARG_PATH_PROPERTY:
535
536 if (strv_extend(&arg_path_property, optarg) < 0)
537 return log_oom();
538
539 break;
540
541 case ARG_SOCKET_PROPERTY:
542
543 if (strv_extend(&arg_socket_property, optarg) < 0)
544 return log_oom();
545
546 break;
547
548 case ARG_NO_BLOCK:
549 arg_no_block = true;
550 break;
551
552 case ARG_WAIT:
553 arg_wait = true;
554 break;
555
556 case ARG_WORKING_DIRECTORY:
557 r = parse_path_argument(optarg, true, &arg_working_directory);
558 if (r < 0)
559 return r;
560
561 break;
562
563 case 'd': {
564 _cleanup_free_ char *p = NULL;
565
566 r = safe_getcwd(&p);
567 if (r < 0)
568 return log_error_errno(r, "Failed to get current working directory: %m");
569
570 if (empty_or_root(p))
571 arg_working_directory = mfree(arg_working_directory);
572 else
573 free_and_replace(arg_working_directory, p);
574 break;
575 }
576
577 case 'G':
578 arg_aggressive_gc = true;
579 break;
580
581 case 'S':
582 arg_shell = true;
583 break;
584
585 case ARG_IGNORE_FAILURE:
586 arg_ignore_failure = true;
587 break;
588
589 case ARG_BACKGROUND:
590 r = free_and_strdup_warn(&arg_background, optarg);
591 if (r < 0)
592 return r;
593 break;
594
595 case '?':
596 return -EINVAL;
597
598 default:
599 assert_not_reached();
600 }
601
602 /* If we are talking to the per-user instance PolicyKit isn't going to help */
603 if (arg_runtime_scope == RUNTIME_SCOPE_USER)
604 arg_ask_password = false;
605
606 with_trigger = !!arg_path_property || !!arg_socket_property || arg_with_timer;
607
608 /* currently, only single trigger (path, socket, timer) unit can be created simultaneously */
609 if ((int) !!arg_path_property + (int) !!arg_socket_property + (int) arg_with_timer > 1)
610 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
611 "Only single trigger (path, socket, timer) unit can be created.");
612
613 if (arg_shell) {
614 /* If --shell is imply --pty --pipe --same-dir --service-type=exec --wait --collect, unless otherwise
615 * specified. */
616
617 if (!arg_scope) {
618 if (arg_stdio == ARG_STDIO_NONE)
619 arg_stdio = ARG_STDIO_AUTO;
620
621 if (!arg_working_directory) {
622 r = safe_getcwd(&arg_working_directory);
623 if (r < 0)
624 return log_error_errno(r, "Failed to get current working directory: %m");
625 }
626
627 if (!arg_service_type)
628 arg_service_type = "exec";
629
630 arg_wait = true;
631 }
632
633 arg_aggressive_gc = true;
634 }
635
636 if (arg_stdio == ARG_STDIO_AUTO)
637 /* If we both --pty and --pipe are specified we'll automatically pick --pty if we are connected fully
638 * to a TTY and pick direct fd passing otherwise. This way, we automatically adapt to usage in a shell
639 * pipeline, but we are neatly interactive with tty-level isolation otherwise. */
640 arg_stdio = isatty(STDIN_FILENO) && isatty(STDOUT_FILENO) && isatty(STDERR_FILENO) ?
641 ARG_STDIO_PTY :
642 ARG_STDIO_DIRECT;
643
644 if (argc > optind) {
645 char **l;
646
647 if (arg_shell)
648 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "If --shell is used, no command line is expected.");
649
650 l = strv_copy(argv + optind);
651 if (!l)
652 return log_oom();
653
654 strv_free_and_replace(arg_cmdline, l);
655
656 } else if (arg_shell) {
657 _cleanup_free_ char *s = NULL;
658 char **l;
659
660 r = get_shell(&s);
661 if (r < 0)
662 return log_error_errno(r, "Failed to determine shell: %m");
663
664 l = strv_new(s);
665 if (!l)
666 return log_oom();
667
668 strv_free_and_replace(arg_cmdline, l);
669
670 } else if (!arg_unit || !with_trigger)
671 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Command line to execute required.");
672
673 if (arg_runtime_scope == RUNTIME_SCOPE_USER && arg_transport == BUS_TRANSPORT_REMOTE)
674 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
675 "Execution in user context is not supported on remote systems.");
676
677 if (arg_scope && arg_transport == BUS_TRANSPORT_REMOTE)
678 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
679 "Scope execution is not supported on remote systems.");
680
681 if (arg_scope && (arg_remain_after_exit || arg_service_type))
682 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
683 "--remain-after-exit and --service-type= are not supported in --scope mode.");
684
685 if (arg_stdio != ARG_STDIO_NONE && (with_trigger || arg_scope))
686 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
687 "--pty/--pipe is not compatible in timer or --scope mode.");
688
689 if (arg_stdio != ARG_STDIO_NONE && arg_transport == BUS_TRANSPORT_REMOTE)
690 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
691 "--pty/--pipe is only supported when connecting to the local system or containers.");
692
693 if (arg_stdio != ARG_STDIO_NONE && arg_no_block)
694 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
695 "--pty/--pipe is not compatible with --no-block.");
696
697 if (arg_scope && with_trigger)
698 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
699 "Path, socket or timer options are not supported in --scope mode.");
700
701 if (arg_timer_property && !arg_with_timer)
702 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
703 "--timer-property= has no effect without any other timer options.");
704
705 if (arg_wait) {
706 if (arg_no_block)
707 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
708 "--wait may not be combined with --no-block.");
709
710 if (with_trigger)
711 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
712 "--wait may not be combined with path, socket or timer operations.");
713
714 if (arg_scope)
715 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
716 "--wait may not be combined with --scope.");
717 }
718
719 return 1;
720 }
721
722 static int parse_argv_sudo_mode(int argc, char *argv[]) {
723
724 enum {
725 ARG_NO_ASK_PASSWORD = 0x100,
726 ARG_HOST,
727 ARG_MACHINE,
728 ARG_UNIT,
729 ARG_PROPERTY,
730 ARG_DESCRIPTION,
731 ARG_SLICE,
732 ARG_SLICE_INHERIT,
733 ARG_NICE,
734 ARG_SETENV,
735 ARG_BACKGROUND,
736 };
737
738 /* If invoked as "uid0" binary, let's expose a more sudo-like interface. We add various extensions
739 * though (but limit the extension to long options). */
740
741 static const struct option options[] = {
742 { "help", no_argument, NULL, 'h' },
743 { "version", no_argument, NULL, 'V' },
744 { "no-ask-password", no_argument, NULL, ARG_NO_ASK_PASSWORD },
745 { "machine", required_argument, NULL, ARG_MACHINE },
746 { "unit", required_argument, NULL, ARG_UNIT },
747 { "property", required_argument, NULL, ARG_PROPERTY },
748 { "description", required_argument, NULL, ARG_DESCRIPTION },
749 { "slice", required_argument, NULL, ARG_SLICE },
750 { "slice-inherit", no_argument, NULL, ARG_SLICE_INHERIT },
751 { "user", required_argument, NULL, 'u' },
752 { "group", required_argument, NULL, 'g' },
753 { "nice", required_argument, NULL, ARG_NICE },
754 { "chdir", required_argument, NULL, 'D' },
755 { "setenv", required_argument, NULL, ARG_SETENV },
756 { "background", required_argument, NULL, ARG_BACKGROUND },
757 {},
758 };
759
760 int r, c;
761
762 assert(argc >= 0);
763 assert(argv);
764
765 /* Resetting to 0 forces the invocation of an internal initialization routine of getopt_long()
766 * that checks for GNU extensions in optstring ('-' or '+' at the beginning). */
767 optind = 0;
768 while ((c = getopt_long(argc, argv, "+hVu:g:D:", options, NULL)) >= 0)
769
770 switch (c) {
771
772 case 'h':
773 return help_sudo_mode();
774
775 case 'V':
776 return version();
777
778 case ARG_NO_ASK_PASSWORD:
779 arg_ask_password = false;
780 break;
781
782 case ARG_MACHINE:
783 arg_transport = BUS_TRANSPORT_MACHINE;
784 arg_host = optarg;
785 break;
786
787 case ARG_UNIT:
788 arg_unit = optarg;
789 break;
790
791 case ARG_PROPERTY:
792 if (strv_extend(&arg_property, optarg) < 0)
793 return log_oom();
794
795 break;
796
797 case ARG_DESCRIPTION:
798 r = free_and_strdup_warn(&arg_description, optarg);
799 if (r < 0)
800 return r;
801 break;
802
803 case ARG_SLICE:
804 arg_slice = optarg;
805 break;
806
807 case ARG_SLICE_INHERIT:
808 arg_slice_inherit = true;
809 break;
810
811 case 'u':
812 arg_exec_user = optarg;
813 break;
814
815 case 'g':
816 arg_exec_group = optarg;
817 break;
818
819 case ARG_NICE:
820 r = parse_nice(optarg, &arg_nice);
821 if (r < 0)
822 return log_error_errno(r, "Failed to parse nice value: %s", optarg);
823
824 arg_nice_set = true;
825 break;
826
827 case 'D':
828 r = parse_path_argument(optarg, true, &arg_working_directory);
829 if (r < 0)
830 return r;
831
832 break;
833
834 case ARG_SETENV:
835 r = strv_env_replace_strdup_passthrough(&arg_environment, optarg);
836 if (r < 0)
837 return log_error_errno(r, "Cannot assign environment variable %s: %m", optarg);
838
839 break;
840
841 case ARG_BACKGROUND:
842 r = free_and_strdup_warn(&arg_background, optarg);
843 if (r < 0)
844 return r;
845
846 break;
847
848 case '?':
849 return -EINVAL;
850
851 default:
852 assert_not_reached();
853 }
854
855 if (!arg_working_directory) {
856 if (arg_exec_user) {
857 /* When switching to a specific user, also switch to its home directory. */
858 arg_working_directory = strdup("~");
859 if (!arg_working_directory)
860 return log_oom();
861 } else {
862 /* When switching to root without this being specified, then stay in the current directory */
863 r = safe_getcwd(&arg_working_directory);
864 if (r < 0)
865 return log_error_errno(r, "Failed to get current working directory: %m");
866 }
867 }
868
869 arg_service_type = "exec";
870 arg_quiet = true;
871 arg_wait = true;
872 arg_aggressive_gc = true;
873
874 arg_stdio = isatty(STDIN_FILENO) && isatty(STDOUT_FILENO) && isatty(STDERR_FILENO) ? ARG_STDIO_PTY : ARG_STDIO_DIRECT;
875 arg_expand_environment = false;
876 arg_send_sighup = true;
877
878 _cleanup_strv_free_ char **l = NULL;
879 if (argc > optind)
880 l = strv_copy(argv + optind);
881 else {
882 const char *e;
883
884 e = strv_env_get(arg_environment, "SHELL");
885 if (e)
886 arg_exec_path = strdup(e);
887 else {
888 if (arg_transport == BUS_TRANSPORT_LOCAL) {
889 r = get_shell(&arg_exec_path);
890 if (r < 0)
891 return log_error_errno(r, "Failed to determine shell: %m");
892 } else
893 arg_exec_path = strdup("/bin/sh");
894 }
895 if (!arg_exec_path)
896 return log_oom();
897
898 l = make_login_shell_cmdline(arg_exec_path);
899 }
900 if (!l)
901 return log_oom();
902
903 strv_free_and_replace(arg_cmdline, l);
904
905 if (!arg_slice) {
906 arg_slice = strdup("user.slice");
907 if (!arg_slice)
908 return log_oom();
909 }
910
911 _cleanup_free_ char *un = NULL;
912 un = getusername_malloc();
913 if (!un)
914 return log_oom();
915
916 /* Set a bunch of environment variables in a roughly sudo-compatible way */
917 r = strv_env_assign(&arg_environment, "SUDO_USER", un);
918 if (r < 0)
919 return log_error_errno(r, "Failed to set $SUDO_USER environment variable: %m");
920
921 r = strv_env_assignf(&arg_environment, "SUDO_UID", UID_FMT, getuid());
922 if (r < 0)
923 return log_error_errno(r, "Failed to set $SUDO_UID environment variable: %m");
924
925 r = strv_env_assignf(&arg_environment, "SUDO_GID", GID_FMT, getgid());
926 if (r < 0)
927 return log_error_errno(r, "Failed to set $SUDO_GID environment variable: %m");
928
929 if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_UID=" UID_FMT, getuid()) < 0)
930 return log_oom();
931
932 if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_GID=" GID_FMT, getgid()) < 0)
933 return log_oom();
934
935 if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_USER=%s", un) < 0)
936 return log_oom();
937
938 if (strv_extend(&arg_property, "PAMName=systemd-uid0") < 0)
939 return log_oom();
940
941 if (!arg_background && arg_stdio == ARG_STDIO_PTY) {
942 double red, green, blue;
943
944 r = get_default_background_color(&red, &green, &blue);
945 if (r < 0)
946 log_debug_errno(r, "Unable to get terminal background color, not tinting background: %m");
947 else {
948 double h, s, v;
949
950 rgb_to_hsv(red, green, blue, &h, &s, &v);
951
952 if (!arg_exec_user || STR_IN_SET(arg_exec_user, "root", "0"))
953 h = 0; /* red */
954 else
955 h = 60 /* yellow */;
956
957 if (v > 50) /* If the background is bright, then pull down saturation */
958 s = 25;
959 else /* otherwise pump it up */
960 s = 75;
961
962 v = MAX(30, v); /* Make sure we don't hide the color in black */
963
964 uint8_t r8, g8, b8;
965 hsv_to_rgb(h, s, v, &r8, &g8, &b8);
966
967 if (asprintf(&arg_background, "48;2;%u;%u;%u", r8, g8, b8) < 0)
968 return log_oom();
969 }
970 }
971
972 return 1;
973 }
974
975 static int transient_unit_set_properties(sd_bus_message *m, UnitType t, char **properties) {
976 int r;
977
978 assert(m);
979
980 r = sd_bus_message_append(m, "(sv)", "Description", "s", arg_description);
981 if (r < 0)
982 return bus_log_create_error(r);
983
984 if (arg_aggressive_gc) {
985 r = sd_bus_message_append(m, "(sv)", "CollectMode", "s", "inactive-or-failed");
986 if (r < 0)
987 return bus_log_create_error(r);
988 }
989
990 r = sd_bus_is_bus_client(sd_bus_message_get_bus(m));
991 if (r < 0)
992 return log_error_errno(r, "Can't determine if bus connection is direct or to broker: %m");
993 if (r > 0) {
994 /* Pin the object as least as long as we are around. Note that AddRef (currently) only works
995 * if we talk via the bus though. */
996 r = sd_bus_message_append(m, "(sv)", "AddRef", "b", 1);
997 if (r < 0)
998 return bus_log_create_error(r);
999 }
1000
1001 return bus_append_unit_property_assignment_many(m, t, properties);
1002 }
1003
1004 static int transient_cgroup_set_properties(sd_bus_message *m) {
1005 _cleanup_free_ char *name = NULL;
1006 _cleanup_free_ char *slice = NULL;
1007 int r;
1008 assert(m);
1009
1010 if (arg_slice_inherit) {
1011 char *end;
1012
1013 switch (arg_runtime_scope) {
1014
1015 case RUNTIME_SCOPE_USER:
1016 r = cg_pid_get_user_slice(0, &name);
1017 break;
1018
1019 case RUNTIME_SCOPE_SYSTEM:
1020 r = cg_pid_get_slice(0, &name);
1021 break;
1022
1023 default:
1024 assert_not_reached();
1025 }
1026
1027 if (r < 0)
1028 return log_error_errno(r, "Failed to get PID slice: %m");
1029
1030 end = endswith(name, ".slice");
1031 if (!end)
1032 return -ENXIO;
1033 *end = 0;
1034 }
1035
1036 if (!isempty(arg_slice) && !strextend_with_separator(&name, "-", arg_slice))
1037 return log_oom();
1038
1039 if (!name)
1040 return 0;
1041
1042 r = unit_name_mangle_with_suffix(name, "as slice",
1043 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
1044 ".slice", &slice);
1045 if (r < 0)
1046 return log_error_errno(r, "Failed to mangle name '%s': %m", arg_slice);
1047
1048 r = sd_bus_message_append(m, "(sv)", "Slice", "s", slice);
1049 if (r < 0)
1050 return bus_log_create_error(r);
1051
1052 return 0;
1053 }
1054
1055 static int transient_kill_set_properties(sd_bus_message *m) {
1056 int r;
1057
1058 assert(m);
1059
1060 if (arg_send_sighup) {
1061 r = sd_bus_message_append(m, "(sv)", "SendSIGHUP", "b", arg_send_sighup);
1062 if (r < 0)
1063 return bus_log_create_error(r);
1064 }
1065
1066 return 0;
1067 }
1068
1069 static int transient_service_set_properties(sd_bus_message *m, const char *pty_path) {
1070 bool send_term = false;
1071 int r;
1072
1073 /* We disable environment expansion on the server side via ExecStartEx=:.
1074 * ExecStartEx was added relatively recently (v243), and some bugs were fixed only later.
1075 * So use that feature only if required. It will fail with older systemds. */
1076 bool use_ex_prop = arg_expand_environment == 0;
1077
1078 assert(m);
1079
1080 r = transient_unit_set_properties(m, UNIT_SERVICE, arg_property);
1081 if (r < 0)
1082 return r;
1083
1084 r = transient_kill_set_properties(m);
1085 if (r < 0)
1086 return r;
1087
1088 r = transient_cgroup_set_properties(m);
1089 if (r < 0)
1090 return r;
1091
1092 if (arg_remain_after_exit) {
1093 r = sd_bus_message_append(m, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit);
1094 if (r < 0)
1095 return bus_log_create_error(r);
1096 }
1097
1098 if (arg_service_type) {
1099 r = sd_bus_message_append(m, "(sv)", "Type", "s", arg_service_type);
1100 if (r < 0)
1101 return bus_log_create_error(r);
1102 }
1103
1104 if (arg_exec_user) {
1105 r = sd_bus_message_append(m, "(sv)", "User", "s", arg_exec_user);
1106 if (r < 0)
1107 return bus_log_create_error(r);
1108 }
1109
1110 if (arg_exec_group) {
1111 r = sd_bus_message_append(m, "(sv)", "Group", "s", arg_exec_group);
1112 if (r < 0)
1113 return bus_log_create_error(r);
1114 }
1115
1116 if (arg_nice_set) {
1117 r = sd_bus_message_append(m, "(sv)", "Nice", "i", arg_nice);
1118 if (r < 0)
1119 return bus_log_create_error(r);
1120 }
1121
1122 if (arg_working_directory) {
1123 r = sd_bus_message_append(m, "(sv)", "WorkingDirectory", "s", arg_working_directory);
1124 if (r < 0)
1125 return bus_log_create_error(r);
1126 }
1127
1128 if (pty_path) {
1129 r = sd_bus_message_append(m,
1130 "(sv)(sv)(sv)(sv)",
1131 "StandardInput", "s", "tty",
1132 "StandardOutput", "s", "tty",
1133 "StandardError", "s", "tty",
1134 "TTYPath", "s", pty_path);
1135 if (r < 0)
1136 return bus_log_create_error(r);
1137
1138 send_term = true;
1139
1140 } else if (arg_stdio == ARG_STDIO_DIRECT) {
1141 r = sd_bus_message_append(m,
1142 "(sv)(sv)(sv)",
1143 "StandardInputFileDescriptor", "h", STDIN_FILENO,
1144 "StandardOutputFileDescriptor", "h", STDOUT_FILENO,
1145 "StandardErrorFileDescriptor", "h", STDERR_FILENO);
1146 if (r < 0)
1147 return bus_log_create_error(r);
1148
1149 send_term = isatty(STDIN_FILENO) || isatty(STDOUT_FILENO) || isatty(STDERR_FILENO);
1150 }
1151
1152 if (send_term) {
1153 const char *e;
1154
1155 e = getenv("TERM");
1156 if (e) {
1157 _cleanup_free_ char *n = NULL;
1158
1159 n = strjoin("TERM=", e);
1160 if (!n)
1161 return log_oom();
1162
1163 r = sd_bus_message_append(m,
1164 "(sv)",
1165 "Environment", "as", 1, n);
1166 if (r < 0)
1167 return bus_log_create_error(r);
1168 }
1169 }
1170
1171 if (!strv_isempty(arg_environment)) {
1172 r = sd_bus_message_open_container(m, 'r', "sv");
1173 if (r < 0)
1174 return bus_log_create_error(r);
1175
1176 r = sd_bus_message_append(m, "s", "Environment");
1177 if (r < 0)
1178 return bus_log_create_error(r);
1179
1180 r = sd_bus_message_open_container(m, 'v', "as");
1181 if (r < 0)
1182 return bus_log_create_error(r);
1183
1184 r = sd_bus_message_append_strv(m, arg_environment);
1185 if (r < 0)
1186 return bus_log_create_error(r);
1187
1188 r = sd_bus_message_close_container(m);
1189 if (r < 0)
1190 return bus_log_create_error(r);
1191
1192 r = sd_bus_message_close_container(m);
1193 if (r < 0)
1194 return bus_log_create_error(r);
1195 }
1196
1197 /* Exec container */
1198 if (!strv_isempty(arg_cmdline)) {
1199 r = sd_bus_message_open_container(m, 'r', "sv");
1200 if (r < 0)
1201 return bus_log_create_error(r);
1202
1203 r = sd_bus_message_append(m, "s",
1204 use_ex_prop ? "ExecStartEx" : "ExecStart");
1205 if (r < 0)
1206 return bus_log_create_error(r);
1207
1208 r = sd_bus_message_open_container(m, 'v',
1209 use_ex_prop ? "a(sasas)" : "a(sasb)");
1210 if (r < 0)
1211 return bus_log_create_error(r);
1212
1213 r = sd_bus_message_open_container(m, 'a',
1214 use_ex_prop ? "(sasas)" : "(sasb)");
1215 if (r < 0)
1216 return bus_log_create_error(r);
1217
1218 r = sd_bus_message_open_container(m, 'r',
1219 use_ex_prop ? "sasas" : "sasb");
1220 if (r < 0)
1221 return bus_log_create_error(r);
1222
1223 r = sd_bus_message_append(m, "s", arg_exec_path ?: arg_cmdline[0]);
1224 if (r < 0)
1225 return bus_log_create_error(r);
1226
1227 r = sd_bus_message_append_strv(m, arg_cmdline);
1228 if (r < 0)
1229 return bus_log_create_error(r);
1230
1231 if (use_ex_prop)
1232 r = sd_bus_message_append_strv(
1233 m,
1234 STRV_MAKE(arg_expand_environment > 0 ? NULL : "no-env-expand",
1235 arg_ignore_failure ? "ignore-failure" : NULL));
1236 else
1237 r = sd_bus_message_append(m, "b", arg_ignore_failure);
1238 if (r < 0)
1239 return bus_log_create_error(r);
1240
1241 r = sd_bus_message_close_container(m);
1242 if (r < 0)
1243 return bus_log_create_error(r);
1244
1245 r = sd_bus_message_close_container(m);
1246 if (r < 0)
1247 return bus_log_create_error(r);
1248
1249 r = sd_bus_message_close_container(m);
1250 if (r < 0)
1251 return bus_log_create_error(r);
1252
1253 r = sd_bus_message_close_container(m);
1254 if (r < 0)
1255 return bus_log_create_error(r);
1256 }
1257
1258 return 0;
1259 }
1260
1261 static int transient_scope_set_properties(sd_bus_message *m, bool allow_pidfd) {
1262 int r;
1263
1264 assert(m);
1265
1266 r = transient_unit_set_properties(m, UNIT_SCOPE, arg_property);
1267 if (r < 0)
1268 return r;
1269
1270 r = transient_kill_set_properties(m);
1271 if (r < 0)
1272 return r;
1273
1274 r = transient_cgroup_set_properties(m);
1275 if (r < 0)
1276 return r;
1277
1278 if (allow_pidfd) {
1279 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
1280
1281 r = pidref_set_self(&pidref);
1282 if (r < 0)
1283 return r;
1284
1285 r = bus_append_scope_pidref(m, &pidref);
1286 } else
1287 r = sd_bus_message_append(
1288 m, "(sv)",
1289 "PIDs", "au", 1, getpid_cached());
1290 if (r < 0)
1291 return bus_log_create_error(r);
1292
1293 return 0;
1294 }
1295
1296 static int transient_timer_set_properties(sd_bus_message *m) {
1297 int r;
1298
1299 assert(m);
1300
1301 r = transient_unit_set_properties(m, UNIT_TIMER, arg_timer_property);
1302 if (r < 0)
1303 return r;
1304
1305 /* Automatically clean up our transient timers */
1306 r = sd_bus_message_append(m, "(sv)", "RemainAfterElapse", "b", false);
1307 if (r < 0)
1308 return bus_log_create_error(r);
1309
1310 return 0;
1311 }
1312
1313 static int make_unit_name(sd_bus *bus, UnitType t, char **ret) {
1314 const char *unique, *id;
1315 char *p;
1316 int r;
1317
1318 assert(bus);
1319 assert(t >= 0);
1320 assert(t < _UNIT_TYPE_MAX);
1321
1322 r = sd_bus_get_unique_name(bus, &unique);
1323 if (r < 0) {
1324 sd_id128_t rnd;
1325
1326 /* We couldn't get the unique name, which is a pretty
1327 * common case if we are connected to systemd
1328 * directly. In that case, just pick a random uuid as
1329 * name */
1330
1331 r = sd_id128_randomize(&rnd);
1332 if (r < 0)
1333 return log_error_errno(r, "Failed to generate random run unit name: %m");
1334
1335 if (asprintf(ret, "run-r" SD_ID128_FORMAT_STR ".%s", SD_ID128_FORMAT_VAL(rnd), unit_type_to_string(t)) < 0)
1336 return log_oom();
1337
1338 return 0;
1339 }
1340
1341 /* We managed to get the unique name, then let's use that to name our transient units. */
1342
1343 id = startswith(unique, ":1."); /* let' strip the usual prefix */
1344 if (!id)
1345 id = startswith(unique, ":"); /* the spec only requires things to start with a colon, hence
1346 * let's add a generic fallback for that. */
1347 if (!id)
1348 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
1349 "Unique name %s has unexpected format.",
1350 unique);
1351
1352 p = strjoin("run-u", id, ".", unit_type_to_string(t));
1353 if (!p)
1354 return log_oom();
1355
1356 *ret = p;
1357 return 0;
1358 }
1359
1360 typedef struct RunContext {
1361 sd_bus *bus;
1362 sd_event *event;
1363 PTYForward *forward;
1364 sd_bus_slot *match;
1365
1366 /* Current state of the unit */
1367 char *active_state;
1368 bool has_job;
1369
1370 /* The exit data of the unit */
1371 uint64_t inactive_exit_usec;
1372 uint64_t inactive_enter_usec;
1373 char *result;
1374 uint64_t cpu_usage_nsec;
1375 uint64_t memory_peak;
1376 uint64_t memory_swap_peak;
1377 uint64_t ip_ingress_bytes;
1378 uint64_t ip_egress_bytes;
1379 uint64_t io_read_bytes;
1380 uint64_t io_write_bytes;
1381 uint32_t exit_code;
1382 uint32_t exit_status;
1383 } RunContext;
1384
1385 static void run_context_free(RunContext *c) {
1386 assert(c);
1387
1388 c->forward = pty_forward_free(c->forward);
1389 c->match = sd_bus_slot_unref(c->match);
1390 c->bus = sd_bus_unref(c->bus);
1391 c->event = sd_event_unref(c->event);
1392
1393 free(c->active_state);
1394 free(c->result);
1395 }
1396
1397 static void run_context_check_done(RunContext *c) {
1398 bool done;
1399
1400 assert(c);
1401
1402 if (c->match)
1403 done = STRPTR_IN_SET(c->active_state, "inactive", "failed") && !c->has_job;
1404 else
1405 done = true;
1406
1407 if (c->forward && done) /* If the service is gone, it's time to drain the output */
1408 done = pty_forward_drain(c->forward);
1409
1410 if (done)
1411 sd_event_exit(c->event, EXIT_SUCCESS);
1412 }
1413
1414 static int map_job(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1415 bool *b = userdata;
1416 const char *job;
1417 uint32_t id;
1418 int r;
1419
1420 r = sd_bus_message_read(m, "(uo)", &id, &job);
1421 if (r < 0)
1422 return r;
1423
1424 *b = id != 0 || !streq(job, "/");
1425 return 0;
1426 }
1427
1428 static int run_context_update(RunContext *c, const char *path) {
1429
1430 static const struct bus_properties_map map[] = {
1431 { "ActiveState", "s", NULL, offsetof(RunContext, active_state) },
1432 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(RunContext, inactive_exit_usec) },
1433 { "InactiveEnterTimestampMonotonic", "t", NULL, offsetof(RunContext, inactive_enter_usec) },
1434 { "Result", "s", NULL, offsetof(RunContext, result) },
1435 { "ExecMainCode", "i", NULL, offsetof(RunContext, exit_code) },
1436 { "ExecMainStatus", "i", NULL, offsetof(RunContext, exit_status) },
1437 { "CPUUsageNSec", "t", NULL, offsetof(RunContext, cpu_usage_nsec) },
1438 { "MemoryPeak", "t", NULL, offsetof(RunContext, memory_peak) },
1439 { "MemorySwapPeak", "t", NULL, offsetof(RunContext, memory_swap_peak) },
1440 { "IPIngressBytes", "t", NULL, offsetof(RunContext, ip_ingress_bytes) },
1441 { "IPEgressBytes", "t", NULL, offsetof(RunContext, ip_egress_bytes) },
1442 { "IOReadBytes", "t", NULL, offsetof(RunContext, io_read_bytes) },
1443 { "IOWriteBytes", "t", NULL, offsetof(RunContext, io_write_bytes) },
1444 { "Job", "(uo)", map_job, offsetof(RunContext, has_job) },
1445 {}
1446 };
1447
1448 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1449 int r;
1450
1451 r = bus_map_all_properties(c->bus,
1452 "org.freedesktop.systemd1",
1453 path,
1454 map,
1455 BUS_MAP_STRDUP,
1456 &error,
1457 NULL,
1458 c);
1459 if (r < 0) {
1460 sd_event_exit(c->event, EXIT_FAILURE);
1461 return log_error_errno(r, "Failed to query unit state: %s", bus_error_message(&error, r));
1462 }
1463
1464 run_context_check_done(c);
1465 return 0;
1466 }
1467
1468 static int on_properties_changed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1469 RunContext *c = ASSERT_PTR(userdata);
1470
1471 assert(m);
1472
1473 return run_context_update(c, sd_bus_message_get_path(m));
1474 }
1475
1476 static int pty_forward_handler(PTYForward *f, int rcode, void *userdata) {
1477 RunContext *c = userdata;
1478
1479 assert(f);
1480
1481 if (rcode < 0) {
1482 sd_event_exit(c->event, EXIT_FAILURE);
1483 return log_error_errno(rcode, "Error on PTY forwarding logic: %m");
1484 }
1485
1486 run_context_check_done(c);
1487 return 0;
1488 }
1489
1490 static int make_transient_service_unit(
1491 sd_bus *bus,
1492 sd_bus_message **message,
1493 const char *service,
1494 const char *pty_path) {
1495
1496 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1497 int r;
1498
1499 assert(bus);
1500 assert(message);
1501 assert(service);
1502
1503 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
1504 if (r < 0)
1505 return bus_log_create_error(r);
1506
1507 r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
1508 if (r < 0)
1509 return bus_log_create_error(r);
1510
1511 /* Name and mode */
1512 r = sd_bus_message_append(m, "ss", service, "fail");
1513 if (r < 0)
1514 return bus_log_create_error(r);
1515
1516 /* Properties */
1517 r = sd_bus_message_open_container(m, 'a', "(sv)");
1518 if (r < 0)
1519 return bus_log_create_error(r);
1520
1521 r = transient_service_set_properties(m, pty_path);
1522 if (r < 0)
1523 return r;
1524
1525 r = sd_bus_message_close_container(m);
1526 if (r < 0)
1527 return bus_log_create_error(r);
1528
1529 /* Auxiliary units */
1530 r = sd_bus_message_append(m, "a(sa(sv))", 0);
1531 if (r < 0)
1532 return bus_log_create_error(r);
1533
1534 *message = TAKE_PTR(m);
1535 return 0;
1536 }
1537
1538 static int bus_call_with_hint(
1539 sd_bus *bus,
1540 sd_bus_message *message,
1541 const char *name,
1542 sd_bus_message **reply) {
1543
1544 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1545 int r;
1546
1547 r = sd_bus_call(bus, message, 0, &error, reply);
1548 if (r < 0) {
1549 log_error_errno(r, "Failed to start transient %s unit: %s", name, bus_error_message(&error, r));
1550
1551 if (arg_expand_environment == 0 &&
1552 sd_bus_error_has_names(&error,
1553 SD_BUS_ERROR_UNKNOWN_PROPERTY,
1554 SD_BUS_ERROR_PROPERTY_READ_ONLY))
1555 log_notice_errno(r, "Hint: --expand-environment=no is not supported by old systemd");
1556 }
1557
1558 return r;
1559 }
1560
1561 static int acquire_invocation_id(sd_bus *bus, const char *unit, sd_id128_t *ret) {
1562 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1563 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1564 _cleanup_free_ char *object = NULL;
1565 const void *p;
1566 size_t l;
1567 int r;
1568
1569 assert(bus);
1570 assert(ret);
1571
1572 if (unit) {
1573 object = unit_dbus_path_from_name(unit);
1574 if (!object)
1575 return log_oom();
1576 }
1577
1578 r = sd_bus_get_property(bus,
1579 "org.freedesktop.systemd1",
1580 object ?: "/org/freedesktop/systemd1/unit/self",
1581 "org.freedesktop.systemd1.Unit",
1582 "InvocationID",
1583 &error,
1584 &reply,
1585 "ay");
1586 if (r < 0)
1587 return log_error_errno(r, "Failed to request invocation ID for unit: %s", bus_error_message(&error, r));
1588
1589 r = sd_bus_message_read_array(reply, 'y', &p, &l);
1590 if (r < 0)
1591 return bus_log_parse_error(r);
1592
1593 if (l == 0) {
1594 *ret = SD_ID128_NULL;
1595 return 0; /* no uuid set */
1596 }
1597
1598 if (l != sizeof(sd_id128_t))
1599 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid UUID size, %zu != %zu.", l, sizeof(sd_id128_t));
1600
1601 memcpy(ret, p, l);
1602 return !sd_id128_is_null(*ret);
1603 }
1604
1605 static int start_transient_service(sd_bus *bus) {
1606 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
1607 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1608 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
1609 _cleanup_free_ char *service = NULL, *pty_path = NULL;
1610 _cleanup_close_ int master = -EBADF;
1611 int r;
1612
1613 assert(bus);
1614
1615 if (arg_stdio == ARG_STDIO_PTY) {
1616
1617 if (arg_transport == BUS_TRANSPORT_LOCAL) {
1618 master = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
1619 if (master < 0)
1620 return log_error_errno(errno, "Failed to acquire pseudo tty: %m");
1621
1622 r = ptsname_malloc(master, &pty_path);
1623 if (r < 0)
1624 return log_error_errno(r, "Failed to determine tty name: %m");
1625
1626 if (unlockpt(master) < 0)
1627 return log_error_errno(errno, "Failed to unlock tty: %m");
1628
1629 } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
1630 _cleanup_(sd_bus_unrefp) sd_bus *system_bus = NULL;
1631 _cleanup_(sd_bus_message_unrefp) sd_bus_message *pty_reply = NULL;
1632 const char *s;
1633
1634 r = sd_bus_default_system(&system_bus);
1635 if (r < 0)
1636 return log_error_errno(r, "Failed to connect to system bus: %m");
1637
1638 r = bus_call_method(system_bus,
1639 bus_machine_mgr,
1640 "OpenMachinePTY",
1641 &error,
1642 &pty_reply,
1643 "s", arg_host);
1644 if (r < 0)
1645 return log_error_errno(r, "Failed to get machine PTY: %s", bus_error_message(&error, r));
1646
1647 r = sd_bus_message_read(pty_reply, "hs", &master, &s);
1648 if (r < 0)
1649 return bus_log_parse_error(r);
1650
1651 master = fcntl(master, F_DUPFD_CLOEXEC, 3);
1652 if (master < 0)
1653 return log_error_errno(errno, "Failed to duplicate master fd: %m");
1654
1655 pty_path = strdup(s);
1656 if (!pty_path)
1657 return log_oom();
1658 } else
1659 assert_not_reached();
1660 }
1661
1662 /* Optionally, wait for the start job to complete. If we are supposed to read the service's stdin
1663 * lets skip this however, because we should start that already when the start job is running, and
1664 * there's little point in waiting for the start job to complete in that case anyway, as we'll wait
1665 * for EOF anyway, which is going to be much later. */
1666 if (!arg_no_block && arg_stdio == ARG_STDIO_NONE) {
1667 r = bus_wait_for_jobs_new(bus, &w);
1668 if (r < 0)
1669 return log_error_errno(r, "Could not watch jobs: %m");
1670 }
1671
1672 if (arg_unit) {
1673 r = unit_name_mangle_with_suffix(arg_unit, "as unit",
1674 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
1675 ".service", &service);
1676 if (r < 0)
1677 return log_error_errno(r, "Failed to mangle unit name: %m");
1678 } else {
1679 r = make_unit_name(bus, UNIT_SERVICE, &service);
1680 if (r < 0)
1681 return r;
1682 }
1683
1684 r = make_transient_service_unit(bus, &m, service, pty_path);
1685 if (r < 0)
1686 return r;
1687
1688 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1689
1690 r = bus_call_with_hint(bus, m, "service", &reply);
1691 if (r < 0)
1692 return r;
1693
1694 if (w) {
1695 const char *object;
1696
1697 r = sd_bus_message_read(reply, "o", &object);
1698 if (r < 0)
1699 return bus_log_parse_error(r);
1700
1701 r = bus_wait_for_jobs_one(w,
1702 object,
1703 arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
1704 arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
1705 if (r < 0)
1706 return r;
1707 }
1708
1709 if (!arg_quiet) {
1710 sd_id128_t invocation_id;
1711
1712 r = acquire_invocation_id(bus, service, &invocation_id);
1713 if (r < 0)
1714 return r;
1715 if (r == 0) /* No invocation UUID set */
1716 log_info("Running as unit: %s", service);
1717 else
1718 log_info("Running as unit: %s; invocation ID: " SD_ID128_FORMAT_STR, service, SD_ID128_FORMAT_VAL(invocation_id));
1719 }
1720
1721 if (arg_wait || arg_stdio != ARG_STDIO_NONE) {
1722 _cleanup_(run_context_free) RunContext c = {
1723 .cpu_usage_nsec = NSEC_INFINITY,
1724 .memory_peak = UINT64_MAX,
1725 .memory_swap_peak = UINT64_MAX,
1726 .ip_ingress_bytes = UINT64_MAX,
1727 .ip_egress_bytes = UINT64_MAX,
1728 .io_read_bytes = UINT64_MAX,
1729 .io_write_bytes = UINT64_MAX,
1730 .inactive_exit_usec = USEC_INFINITY,
1731 .inactive_enter_usec = USEC_INFINITY,
1732 };
1733 _cleanup_free_ char *path = NULL;
1734
1735 c.bus = sd_bus_ref(bus);
1736
1737 r = sd_event_default(&c.event);
1738 if (r < 0)
1739 return log_error_errno(r, "Failed to get event loop: %m");
1740
1741 if (master >= 0) {
1742 assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGWINCH, SIGTERM, SIGINT, -1) >= 0);
1743 (void) sd_event_add_signal(c.event, NULL, SIGINT, NULL, NULL);
1744 (void) sd_event_add_signal(c.event, NULL, SIGTERM, NULL, NULL);
1745
1746 if (!arg_quiet)
1747 log_info("Press ^] three times within 1s to disconnect TTY.");
1748
1749 r = pty_forward_new(c.event, master, PTY_FORWARD_IGNORE_INITIAL_VHANGUP, &c.forward);
1750 if (r < 0)
1751 return log_error_errno(r, "Failed to create PTY forwarder: %m");
1752
1753 pty_forward_set_handler(c.forward, pty_forward_handler, &c);
1754
1755 /* Make sure to process any TTY events before we process bus events */
1756 (void) pty_forward_set_priority(c.forward, SD_EVENT_PRIORITY_IMPORTANT);
1757
1758 if (!isempty(arg_background))
1759 (void) pty_forward_set_background_color(c.forward, arg_background);
1760 }
1761
1762 path = unit_dbus_path_from_name(service);
1763 if (!path)
1764 return log_oom();
1765
1766 r = sd_bus_match_signal_async(
1767 bus,
1768 &c.match,
1769 "org.freedesktop.systemd1",
1770 path,
1771 "org.freedesktop.DBus.Properties",
1772 "PropertiesChanged",
1773 on_properties_changed, NULL, &c);
1774 if (r < 0)
1775 return log_error_errno(r, "Failed to request properties changed signal match: %m");
1776
1777 r = sd_bus_attach_event(bus, c.event, SD_EVENT_PRIORITY_NORMAL);
1778 if (r < 0)
1779 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1780
1781 r = run_context_update(&c, path);
1782 if (r < 0)
1783 return r;
1784
1785 r = sd_event_loop(c.event);
1786 if (r < 0)
1787 return log_error_errno(r, "Failed to run event loop: %m");
1788
1789 if (c.forward) {
1790 char last_char = 0;
1791
1792 r = pty_forward_get_last_char(c.forward, &last_char);
1793 if (r >= 0 && !arg_quiet && last_char != '\n')
1794 fputc('\n', stdout);
1795 }
1796
1797 if (arg_wait && !arg_quiet) {
1798
1799 /* Explicitly destroy the PTY forwarder, so that the PTY device is usable again, with its
1800 * original settings (i.e. proper line breaks), so that we can show the summary in a pretty
1801 * way. */
1802 c.forward = pty_forward_free(c.forward);
1803
1804 if (!isempty(c.result))
1805 log_info("Finished with result: %s", strna(c.result));
1806
1807 if (c.exit_code == CLD_EXITED)
1808 log_info("Main processes terminated with: code=%s/status=%u",
1809 sigchld_code_to_string(c.exit_code), c.exit_status);
1810 else if (c.exit_code > 0)
1811 log_info("Main processes terminated with: code=%s/status=%s",
1812 sigchld_code_to_string(c.exit_code), signal_to_string(c.exit_status));
1813
1814 if (timestamp_is_set(c.inactive_enter_usec) &&
1815 timestamp_is_set(c.inactive_exit_usec) &&
1816 c.inactive_enter_usec > c.inactive_exit_usec)
1817 log_info("Service runtime: %s",
1818 FORMAT_TIMESPAN(c.inactive_enter_usec - c.inactive_exit_usec, USEC_PER_MSEC));
1819
1820 if (c.cpu_usage_nsec != NSEC_INFINITY)
1821 log_info("CPU time consumed: %s",
1822 FORMAT_TIMESPAN(DIV_ROUND_UP(c.cpu_usage_nsec, NSEC_PER_USEC), USEC_PER_MSEC));
1823
1824 if (c.memory_peak != UINT64_MAX)
1825 log_info("Memory peak: %s", FORMAT_BYTES(c.memory_peak));
1826
1827 if (c.memory_swap_peak != UINT64_MAX)
1828 log_info("Memory swap peak: %s", FORMAT_BYTES(c.memory_swap_peak));
1829
1830 if (c.ip_ingress_bytes != UINT64_MAX)
1831 log_info("IP traffic received: %s", FORMAT_BYTES(c.ip_ingress_bytes));
1832
1833 if (c.ip_egress_bytes != UINT64_MAX)
1834 log_info("IP traffic sent: %s", FORMAT_BYTES(c.ip_egress_bytes));
1835
1836 if (c.io_read_bytes != UINT64_MAX)
1837 log_info("IO bytes read: %s", FORMAT_BYTES(c.io_read_bytes));
1838
1839 if (c.io_write_bytes != UINT64_MAX)
1840 log_info("IO bytes written: %s", FORMAT_BYTES(c.io_write_bytes));
1841 }
1842
1843 /* Try to propagate the service's return value. But if the service defines
1844 * e.g. SuccessExitStatus, honour this, and return 0 to mean "success". */
1845 if (streq_ptr(c.result, "success"))
1846 return EXIT_SUCCESS;
1847 if (streq_ptr(c.result, "exit-code") && c.exit_status > 0)
1848 return c.exit_status;
1849 if (streq_ptr(c.result, "signal"))
1850 return EXIT_EXCEPTION;
1851 return EXIT_FAILURE;
1852 }
1853
1854 return EXIT_SUCCESS;
1855 }
1856
1857 static int start_transient_scope(sd_bus *bus) {
1858 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1859 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
1860 _cleanup_strv_free_ char **env = NULL, **user_env = NULL;
1861 _cleanup_free_ char *scope = NULL;
1862 const char *object = NULL;
1863 sd_id128_t invocation_id;
1864 bool allow_pidfd = true;
1865 int r;
1866
1867 assert(bus);
1868 assert(!strv_isempty(arg_cmdline));
1869
1870 r = bus_wait_for_jobs_new(bus, &w);
1871 if (r < 0)
1872 return log_error_errno(r, "Could not watch jobs: %m");
1873
1874 if (arg_unit) {
1875 r = unit_name_mangle_with_suffix(arg_unit, "as unit",
1876 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
1877 ".scope", &scope);
1878 if (r < 0)
1879 return log_error_errno(r, "Failed to mangle scope name: %m");
1880 } else {
1881 r = make_unit_name(bus, UNIT_SCOPE, &scope);
1882 if (r < 0)
1883 return r;
1884 }
1885
1886 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1887
1888 for (;;) {
1889 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1890 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1891
1892 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
1893 if (r < 0)
1894 return bus_log_create_error(r);
1895
1896 r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
1897 if (r < 0)
1898 return bus_log_create_error(r);
1899
1900 /* Name and Mode */
1901 r = sd_bus_message_append(m, "ss", scope, "fail");
1902 if (r < 0)
1903 return bus_log_create_error(r);
1904
1905 /* Properties */
1906 r = sd_bus_message_open_container(m, 'a', "(sv)");
1907 if (r < 0)
1908 return bus_log_create_error(r);
1909
1910 r = transient_scope_set_properties(m, allow_pidfd);
1911 if (r < 0)
1912 return r;
1913
1914 r = sd_bus_message_close_container(m);
1915 if (r < 0)
1916 return bus_log_create_error(r);
1917
1918 /* Auxiliary units */
1919 r = sd_bus_message_append(m, "a(sa(sv))", 0);
1920 if (r < 0)
1921 return bus_log_create_error(r);
1922
1923 r = sd_bus_call(bus, m, 0, &error, &reply);
1924 if (r < 0) {
1925 if (sd_bus_error_has_names(&error, SD_BUS_ERROR_UNKNOWN_PROPERTY, SD_BUS_ERROR_PROPERTY_READ_ONLY) && allow_pidfd) {
1926 log_debug("Retrying with classic PIDs.");
1927 allow_pidfd = false;
1928 continue;
1929 }
1930
1931 return log_error_errno(r, "Failed to start transient scope unit: %s", bus_error_message(&error, r));
1932 }
1933
1934 break;
1935 }
1936
1937 r = sd_bus_message_read(reply, "o", &object);
1938 if (r < 0)
1939 return bus_log_parse_error(r);
1940
1941 r = bus_wait_for_jobs_one(w, object, arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
1942 arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
1943 if (r < 0)
1944 return r;
1945
1946 r = acquire_invocation_id(bus, NULL, &invocation_id);
1947 if (r < 0)
1948 return r;
1949 if (r == 0)
1950 log_debug("No invocation ID set.");
1951 else {
1952 if (strv_extendf(&user_env, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(invocation_id)) < 0)
1953 return log_oom();
1954 }
1955
1956 if (arg_nice_set) {
1957 if (setpriority(PRIO_PROCESS, 0, arg_nice) < 0)
1958 return log_error_errno(errno, "Failed to set nice level: %m");
1959 }
1960
1961 if (arg_exec_group) {
1962 gid_t gid;
1963
1964 r = get_group_creds(&arg_exec_group, &gid, 0);
1965 if (r < 0)
1966 return log_error_errno(r, "Failed to resolve group %s: %m", arg_exec_group);
1967
1968 if (setresgid(gid, gid, gid) < 0)
1969 return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
1970 }
1971
1972 if (arg_exec_user) {
1973 const char *home, *shell;
1974 uid_t uid;
1975 gid_t gid;
1976
1977 r = get_user_creds(&arg_exec_user, &uid, &gid, &home, &shell, USER_CREDS_CLEAN|USER_CREDS_PREFER_NSS);
1978 if (r < 0)
1979 return log_error_errno(r, "Failed to resolve user %s: %m", arg_exec_user);
1980
1981 if (home) {
1982 r = strv_extendf(&user_env, "HOME=%s", home);
1983 if (r < 0)
1984 return log_oom();
1985 }
1986
1987 if (shell) {
1988 r = strv_extendf(&user_env, "SHELL=%s", shell);
1989 if (r < 0)
1990 return log_oom();
1991 }
1992
1993 r = strv_extendf(&user_env, "USER=%s", arg_exec_user);
1994 if (r < 0)
1995 return log_oom();
1996
1997 r = strv_extendf(&user_env, "LOGNAME=%s", arg_exec_user);
1998 if (r < 0)
1999 return log_oom();
2000
2001 if (!arg_exec_group) {
2002 if (setresgid(gid, gid, gid) < 0)
2003 return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
2004 }
2005
2006 if (setresuid(uid, uid, uid) < 0)
2007 return log_error_errno(errno, "Failed to change UID to " UID_FMT ": %m", uid);
2008 }
2009
2010 if (arg_working_directory && chdir(arg_working_directory) < 0)
2011 return log_error_errno(errno, "Failed to change directory to '%s': %m", arg_working_directory);
2012
2013 env = strv_env_merge(environ, user_env, arg_environment);
2014 if (!env)
2015 return log_oom();
2016
2017 if (!arg_quiet) {
2018 if (sd_id128_is_null(invocation_id))
2019 log_info("Running as unit: %s", scope);
2020 else
2021 log_info("Running as unit: %s; invocation ID: " SD_ID128_FORMAT_STR, scope, SD_ID128_FORMAT_VAL(invocation_id));
2022 }
2023
2024 if (arg_expand_environment > 0) {
2025 _cleanup_strv_free_ char **expanded_cmdline = NULL, **unset_variables = NULL, **bad_variables = NULL;
2026
2027 r = replace_env_argv(arg_cmdline, env, &expanded_cmdline, &unset_variables, &bad_variables);
2028 if (r < 0)
2029 return log_error_errno(r, "Failed to expand environment variables: %m");
2030
2031 free_and_replace(arg_cmdline, expanded_cmdline);
2032
2033 if (!strv_isempty(unset_variables)) {
2034 _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
2035 log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
2036 }
2037
2038 if (!strv_isempty(bad_variables)) {
2039 _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
2040 log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb));
2041 }
2042 }
2043
2044 execvpe(arg_cmdline[0], arg_cmdline, env);
2045
2046 return log_error_errno(errno, "Failed to execute: %m");
2047 }
2048
2049 static int make_transient_trigger_unit(
2050 sd_bus *bus,
2051 sd_bus_message **message,
2052 const char *suffix,
2053 const char *trigger,
2054 const char *service) {
2055
2056 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2057 int r;
2058
2059 assert(bus);
2060 assert(message);
2061 assert(suffix);
2062 assert(trigger);
2063 assert(service);
2064
2065 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
2066 if (r < 0)
2067 return bus_log_create_error(r);
2068
2069 r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
2070 if (r < 0)
2071 return bus_log_create_error(r);
2072
2073 /* Name and Mode */
2074 r = sd_bus_message_append(m, "ss", trigger, "fail");
2075 if (r < 0)
2076 return bus_log_create_error(r);
2077
2078 /* Properties */
2079 r = sd_bus_message_open_container(m, 'a', "(sv)");
2080 if (r < 0)
2081 return bus_log_create_error(r);
2082
2083 if (streq(suffix, ".path"))
2084 r = transient_unit_set_properties(m, UNIT_PATH, arg_path_property);
2085 else if (streq(suffix, ".socket"))
2086 r = transient_unit_set_properties(m, UNIT_SOCKET, arg_socket_property);
2087 else if (streq(suffix, ".timer"))
2088 r = transient_timer_set_properties(m);
2089 else
2090 assert_not_reached();
2091 if (r < 0)
2092 return r;
2093
2094 r = sd_bus_message_close_container(m);
2095 if (r < 0)
2096 return bus_log_create_error(r);
2097
2098 r = sd_bus_message_open_container(m, 'a', "(sa(sv))");
2099 if (r < 0)
2100 return bus_log_create_error(r);
2101
2102 if (!strv_isempty(arg_cmdline)) {
2103 r = sd_bus_message_open_container(m, 'r', "sa(sv)");
2104 if (r < 0)
2105 return bus_log_create_error(r);
2106
2107 r = sd_bus_message_append(m, "s", service);
2108 if (r < 0)
2109 return bus_log_create_error(r);
2110
2111 r = sd_bus_message_open_container(m, 'a', "(sv)");
2112 if (r < 0)
2113 return bus_log_create_error(r);
2114
2115 r = transient_service_set_properties(m, NULL);
2116 if (r < 0)
2117 return r;
2118
2119 r = sd_bus_message_close_container(m);
2120 if (r < 0)
2121 return bus_log_create_error(r);
2122
2123 r = sd_bus_message_close_container(m);
2124 if (r < 0)
2125 return bus_log_create_error(r);
2126 }
2127
2128 r = sd_bus_message_close_container(m);
2129 if (r < 0)
2130 return bus_log_create_error(r);
2131
2132 *message = TAKE_PTR(m);
2133 return 0;
2134 }
2135
2136 static int start_transient_trigger(sd_bus *bus, const char *suffix) {
2137 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
2138 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
2139 _cleanup_free_ char *trigger = NULL, *service = NULL;
2140 const char *object = NULL;
2141 int r;
2142
2143 assert(bus);
2144 assert(suffix);
2145
2146 r = bus_wait_for_jobs_new(bus, &w);
2147 if (r < 0)
2148 return log_error_errno(r, "Could not watch jobs: %m");
2149
2150 if (arg_unit) {
2151 switch (unit_name_to_type(arg_unit)) {
2152
2153 case UNIT_SERVICE:
2154 service = strdup(arg_unit);
2155 if (!service)
2156 return log_oom();
2157
2158 r = unit_name_change_suffix(service, suffix, &trigger);
2159 if (r < 0)
2160 return log_error_errno(r, "Failed to change unit suffix: %m");
2161 break;
2162
2163 case UNIT_TIMER:
2164 trigger = strdup(arg_unit);
2165 if (!trigger)
2166 return log_oom();
2167
2168 r = unit_name_change_suffix(trigger, ".service", &service);
2169 if (r < 0)
2170 return log_error_errno(r, "Failed to change unit suffix: %m");
2171 break;
2172
2173 default:
2174 r = unit_name_mangle_with_suffix(arg_unit, "as unit",
2175 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
2176 ".service", &service);
2177 if (r < 0)
2178 return log_error_errno(r, "Failed to mangle unit name: %m");
2179
2180 r = unit_name_mangle_with_suffix(arg_unit, "as trigger",
2181 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
2182 suffix, &trigger);
2183 if (r < 0)
2184 return log_error_errno(r, "Failed to mangle unit name: %m");
2185
2186 break;
2187 }
2188 } else {
2189 r = make_unit_name(bus, UNIT_SERVICE, &service);
2190 if (r < 0)
2191 return r;
2192
2193 r = unit_name_change_suffix(service, suffix, &trigger);
2194 if (r < 0)
2195 return log_error_errno(r, "Failed to change unit suffix: %m");
2196 }
2197
2198 r = make_transient_trigger_unit(bus, &m, suffix, trigger, service);
2199 if (r < 0)
2200 return r;
2201
2202 polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2203
2204 r = bus_call_with_hint(bus, m, suffix + 1, &reply);
2205 if (r < 0)
2206 return r;
2207
2208 r = sd_bus_message_read(reply, "o", &object);
2209 if (r < 0)
2210 return bus_log_parse_error(r);
2211
2212 r = bus_wait_for_jobs_one(w, object, arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
2213 arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
2214 if (r < 0)
2215 return r;
2216
2217 if (!arg_quiet) {
2218 log_info("Running %s as unit: %s", suffix + 1, trigger);
2219 if (!strv_isempty(arg_cmdline))
2220 log_info("Will run service as unit: %s", service);
2221 }
2222
2223 return EXIT_SUCCESS;
2224 }
2225
2226 static bool shall_make_executable_absolute(void) {
2227 if (arg_exec_path)
2228 return false;
2229 if (strv_isempty(arg_cmdline))
2230 return false;
2231 if (arg_transport != BUS_TRANSPORT_LOCAL)
2232 return false;
2233
2234 FOREACH_STRING(f, "RootDirectory=", "RootImage=", "ExecSearchPath=", "MountImages=", "ExtensionImages=")
2235 if (strv_find_startswith(arg_property, f))
2236 return false;
2237
2238 return true;
2239 }
2240
2241 static int run(int argc, char* argv[]) {
2242 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2243 int r;
2244
2245 log_show_color(true);
2246 log_parse_environment();
2247 log_open();
2248
2249 if (invoked_as(argv, "uid0"))
2250 r = parse_argv_sudo_mode(argc, argv);
2251 else
2252 r = parse_argv(argc, argv);
2253 if (r <= 0)
2254 return r;
2255
2256 if (shall_make_executable_absolute()) {
2257 /* Patch in an absolute path to fail early for user convenience, but only when we can do it
2258 * (i.e. we will be running from the same file system). This also uses the user's $PATH,
2259 * while we use a fixed search path in the manager. */
2260
2261 _cleanup_free_ char *command = NULL;
2262 r = find_executable(arg_cmdline[0], &command);
2263 if (r < 0)
2264 return log_error_errno(r, "Failed to find executable %s: %m", arg_cmdline[0]);
2265
2266 free_and_replace(arg_cmdline[0], command);
2267 }
2268
2269 if (!arg_description) {
2270 char *t;
2271
2272 if (strv_isempty(arg_cmdline))
2273 t = strdup(arg_unit);
2274 else
2275 t = quote_command_line(arg_cmdline, SHELL_ESCAPE_EMPTY);
2276 if (!t)
2277 return log_oom();
2278
2279 free_and_replace(arg_description, t);
2280 }
2281
2282 /* For backward compatibility reasons env var expansion is disabled by default for scopes, and
2283 * enabled by default for everything else. Try to detect it and print a warning, so that we can
2284 * change it in the future and harmonize it. */
2285 if (arg_expand_environment < 0) {
2286 arg_expand_environment = !arg_scope;
2287
2288 if (!arg_quiet && arg_scope && strchr(arg_description, '$'))
2289 log_warning("Scope command line contains environment variable, which is not expanded"
2290 " by default for now, but will be expanded by default in the future."
2291 " Use --expand-environment=yes/no to explicitly control it as needed.");
2292 }
2293
2294 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the
2295 * limited direct connection */
2296 if (arg_wait ||
2297 arg_stdio != ARG_STDIO_NONE ||
2298 (arg_runtime_scope == RUNTIME_SCOPE_USER && arg_transport != BUS_TRANSPORT_LOCAL))
2299 r = bus_connect_transport(arg_transport, arg_host, arg_runtime_scope, &bus);
2300 else
2301 r = bus_connect_transport_systemd(arg_transport, arg_host, arg_runtime_scope, &bus);
2302 if (r < 0)
2303 return bus_log_connect_error(r, arg_transport);
2304
2305 if (arg_scope)
2306 return start_transient_scope(bus);
2307 if (arg_path_property)
2308 return start_transient_trigger(bus, ".path");
2309 if (arg_socket_property)
2310 return start_transient_trigger(bus, ".socket");
2311 if (arg_with_timer)
2312 return start_transient_trigger(bus, ".timer");
2313 return start_transient_service(bus);
2314 }
2315
2316 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);