Debian Codegraph @

src/run/run.c

raw
1 /* SPDX-License-Identifier: LGPL-2.1-or-later */
2
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <sys/mount.h>
7 #include <sys/resource.h>
8 #include <sys/stat.h>
9 #include <unistd.h>
10
11 #include "sd-bus.h"
12 #include "sd-daemon.h"
13 #include "sd-event.h"
14 #include "sd-json.h"
15
16 #include "alloc-util.h"
17 #include "argv-util.h"
18 #include "ask-password-agent.h"
19 #include "build.h"
20 #include "bus-error.h"
21 #include "bus-locator.h"
22 #include "bus-map-properties.h"
23 #include "bus-message-util.h"
24 #include "bus-unit-util.h"
25 #include "bus-util.h"
26 #include "bus-wait-for-jobs.h"
27 #include "calendarspec.h"
28 #include "capability-util.h"
29 #include "capsule-util.h"
30 #include "chase.h"
31 #include "env-util.h"
32 #include "errno-util.h"
33 #include "escape.h"
34 #include "event-util.h"
35 #include "exec-util.h"
36 #include "exit-status.h"
37 #include "fd-util.h"
38 #include "fork-notify.h"
39 #include "format-table.h"
40 #include "format-util.h"
41 #include "fs-util.h"
42 #include "help-util.h"
43 #include "hostname-util.h"
44 #include "log.h"
45 #include "main-func.h"
46 #include "options.h"
47 #include "osc-context.h"
48 #include "pager.h"
49 #include "parse-argument.h"
50 #include "parse-util.h"
51 #include "path-util.h"
52 #include "pidref.h"
53 #include "polkit-agent.h"
54 #include "pretty-print.h"
55 #include "process-util.h"
56 #include "ptyfwd.h"
57 #include "runtime-scope.h"
58 #include "signal-util.h"
59 #include "special.h"
60 #include "string-table.h"
61 #include "string-util.h"
62 #include "strv.h"
63 #include "terminal-util.h"
64 #include "time-util.h"
65 #include "unit-def.h"
66 #include "unit-name.h"
67 #include "user-util.h"
68 #include "virt.h"
69
70 static bool arg_ask_password = true;
71 static bool arg_scope = false;
72 static bool arg_remain_after_exit = false;
73 static bool arg_no_block = false;
74 static bool arg_wait = false;
75 static const char *arg_unit = NULL;
76 static char *arg_description = NULL;
77 static char *arg_slice = NULL;
78 static bool arg_slice_inherit = false;
79 static bool arg_expand_environment = true;
80 static bool arg_send_sighup = false;
81 static BusTransport arg_transport = BUS_TRANSPORT_LOCAL;
82 static const char *arg_host = NULL;
83 static RuntimeScope arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
84 static const char *arg_service_type = NULL;
85 static char *arg_exec_user = NULL;
86 static const char *arg_exec_group = NULL;
87 static int arg_nice = 0;
88 static bool arg_nice_set = false;
89 static char **arg_environment = NULL;
90 static char **arg_property = NULL;
91 static enum {
92 ARG_STDIO_NONE = 0, /* The default, as it is for normal services, stdin connected to
93 * /dev/null, and stdout+stderr to the journal */
94 ARG_STDIO_PTY = 1 << 0, /* Interactive behaviour, requested by --pty/--pty-late: we allocate a pty
95 * and connect it to the TTY we are invoked from */
96 ARG_STDIO_DIRECT = 1 << 1, /* Directly pass our stdin/stdout/stderr to the activated service, useful
97 * for usage in shell pipelines, requested by --pipe */
98 ARG_STDIO_AUTO = ARG_STDIO_PTY | ARG_STDIO_DIRECT,
99 /* If --pipe and --pty/--pty-late are used together we use --pty/--pty-late
100 * when invoked on a TTY, and --pipe otherwise */
101 } arg_stdio = ARG_STDIO_NONE;
102 static int arg_pty_late = -1; /* tristate */
103 static char **arg_path_property = NULL;
104 static char **arg_socket_property = NULL;
105 static char **arg_timer_property = NULL;
106 static bool arg_with_timer = false;
107 static bool arg_quiet = false;
108 static bool arg_verbose = false;
109 static OutputMode arg_output = _OUTPUT_MODE_INVALID;
110 static bool arg_aggressive_gc = false;
111 static char *arg_working_directory = NULL;
112 static char *arg_root_directory = NULL;
113 static bool arg_shell = false;
114 static JobMode arg_job_mode = JOB_FAIL;
115 static char **arg_cmdline = NULL;
116 static char *arg_exec_path = NULL;
117 static bool arg_ignore_failure = false;
118 static char *arg_background = NULL;
119 static PagerFlags arg_pager_flags = 0;
120 static sd_json_format_flags_t arg_json_format_flags = SD_JSON_FORMAT_OFF;
121 static char *arg_shell_prompt_prefix = NULL;
122 static int arg_lightweight = -1;
123 static char *arg_area = NULL;
124 static bool arg_via_shell = false;
125 static bool arg_empower = false;
126
127 STATIC_DESTRUCTOR_REGISTER(arg_description, freep);
128 STATIC_DESTRUCTOR_REGISTER(arg_slice, freep);
129 STATIC_DESTRUCTOR_REGISTER(arg_exec_user, freep);
130 STATIC_DESTRUCTOR_REGISTER(arg_environment, strv_freep);
131 STATIC_DESTRUCTOR_REGISTER(arg_property, strv_freep);
132 STATIC_DESTRUCTOR_REGISTER(arg_path_property, strv_freep);
133 STATIC_DESTRUCTOR_REGISTER(arg_socket_property, strv_freep);
134 STATIC_DESTRUCTOR_REGISTER(arg_timer_property, strv_freep);
135 STATIC_DESTRUCTOR_REGISTER(arg_working_directory, freep);
136 STATIC_DESTRUCTOR_REGISTER(arg_cmdline, strv_freep);
137 STATIC_DESTRUCTOR_REGISTER(arg_exec_path, freep);
138 STATIC_DESTRUCTOR_REGISTER(arg_background, freep);
139 STATIC_DESTRUCTOR_REGISTER(arg_shell_prompt_prefix, freep);
140 STATIC_DESTRUCTOR_REGISTER(arg_area, freep);
141
142 static int help(void) {
143 int r;
144
145 pager_open(arg_pager_flags);
146
147 static const char* const groups[] = {
148 NULL,
149 "Path options",
150 "Socket options",
151 "Timer options",
152 };
153
154 Table *tables[ELEMENTSOF(groups)] = {};
155 CLEANUP_ELEMENTS(tables, table_unref_array_clear);
156
157 for (size_t i = 0; i < ELEMENTSOF(groups); i++) {
158 r = option_parser_get_help_table_full("systemd-run", groups[i], &tables[i]);
159 if (r < 0)
160 return r;
161 }
162
163 (void) table_sync_column_widths(0, tables[0], tables[1], tables[2], tables[3]);
164
165 help_cmdline("[OPTIONS...] COMMAND [ARGUMENTS...]");
166 help_abstract("Run the specified command in a transient scope or service.");
167
168 for (size_t i = 0; i < ELEMENTSOF(groups); i++) {
169 help_section(groups[i] ?: "Options");
170
171 r = table_print_or_warn(tables[i]);
172 if (r < 0)
173 return r;
174 }
175
176 help_man_page_reference("systemd-run", "1");
177 return 0;
178 }
179
180 static int help_sudo_mode(void) {
181 _cleanup_(table_unrefp) Table *opts_table = NULL;
182 int r;
183
184 /* NB: Let's not go overboard with short options: we try to keep a modicum of compatibility with
185 * sudo's short switches, hence please do not introduce new short switches unless they have a roughly
186 * equivalent purpose on sudo. Use long options for everything private to run0. */
187
188 r = option_parser_get_help_table_ns("run0", &opts_table);
189 if (r < 0)
190 return r;
191
192 help_cmdline("[OPTIONS...] COMMAND [ARGUMENTS...]");
193 help_abstract("Elevate privileges interactively.");
194
195 help_section("Options");
196
197 r = table_print_or_warn(opts_table);
198 if (r < 0)
199 return r;
200
201 help_man_page_reference("run0", "1");
202 return 0;
203 }
204
205 static bool become_root(void) {
206 if (arg_runtime_scope != RUNTIME_SCOPE_SYSTEM)
207 return false;
208
209 if (!arg_exec_user) {
210 assert(!arg_empower); /* assume default user has been set */
211 return true;
212 }
213
214 return STR_IN_SET(arg_exec_user, "root", "0");
215 }
216
217 static int add_timer_property(const char *name, const char *val) {
218 char *p;
219
220 assert(name);
221 assert(val);
222
223 p = strjoin(name, "=", val);
224 if (!p)
225 return log_oom();
226
227 if (strv_consume(&arg_timer_property, p) < 0)
228 return log_oom();
229
230 return 0;
231 }
232
233 static char** make_login_shell_cmdline(const char *shell) {
234 _cleanup_free_ char *argv0 = NULL;
235
236 assert(shell);
237
238 argv0 = strjoin("-", shell); /* The - is how shells determine if they shall be consider login shells */
239 if (!argv0)
240 return NULL;
241
242 return strv_new(argv0);
243 }
244
245 static int parse_argv(int argc, char *argv[]) {
246 bool with_trigger = false, same_dir = false;
247 int r;
248
249 assert(argc >= 0);
250 assert(argv);
251
252 OptionParser opts = { argc, argv, OPTION_PARSER_STOP_AT_FIRST_NONOPTION, "systemd-run" };
253
254 FOREACH_OPTION_OR_RETURN(c, &opts)
255 switch (c) {
256
257 OPTION_NAMESPACE("systemd-run"): {}
258
259 OPTION_COMMON_HELP:
260 return help();
261
262 OPTION_COMMON_VERSION:
263 return version();
264
265 OPTION_COMMON_NO_ASK_PASSWORD:
266 arg_ask_password = false;
267 break;
268
269 OPTION_LONG("user", NULL, "Run as user unit"):
270 arg_runtime_scope = RUNTIME_SCOPE_USER;
271 break;
272
273 OPTION_LONG("system", NULL, "Talk to the service manager (implied default)"):
274 arg_runtime_scope = RUNTIME_SCOPE_SYSTEM;
275 break;
276
277 OPTION_COMMON_HOST:
278 arg_transport = BUS_TRANSPORT_REMOTE;
279 arg_host = opts.arg;
280 break;
281
282 OPTION_COMMON_MACHINE:
283 r = parse_machine_argument(opts.arg, &arg_host, &arg_transport);
284 if (r < 0)
285 return r;
286 break;
287
288 OPTION('C', "capsule", "NAME", "Operate on specified capsule"):
289 r = capsule_name_is_valid(opts.arg);
290 if (r < 0)
291 return log_error_errno(r, "Unable to validate capsule name '%s': %m", opts.arg);
292 if (r == 0)
293 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid capsule name: %s", opts.arg);
294
295 arg_host = opts.arg;
296 arg_transport = BUS_TRANSPORT_CAPSULE;
297 arg_runtime_scope = RUNTIME_SCOPE_USER;
298 break;
299
300 OPTION_LONG("scope", NULL, "Run this as scope rather than service"):
301 arg_scope = true;
302 break;
303
304 OPTION('u', "unit", "UNIT", "Run under the specified unit name"):
305 arg_unit = opts.arg;
306 break;
307
308 OPTION('p', "property", "NAME=VALUE", "Set service or scope unit property"):
309 if (strv_extend(&arg_property, opts.arg) < 0)
310 return log_oom();
311 break;
312
313 OPTION_LONG("description", "TEXT", "Description for unit"):
314 r = free_and_strdup_warn(&arg_description, opts.arg);
315 if (r < 0)
316 return r;
317 break;
318
319 OPTION_LONG("slice", "SLICE", "Run in the specified slice"):
320 r = free_and_strdup_warn(&arg_slice, opts.arg);
321 if (r < 0)
322 return r;
323 break;
324
325 OPTION_LONG("slice-inherit", NULL, "Inherit the slice from the caller"):
326 arg_slice_inherit = true;
327 break;
328
329 OPTION_LONG("expand-environment", "BOOL",
330 "Control expansion of environment variables"):
331 r = parse_boolean_argument("--expand-environment=", opts.arg, &arg_expand_environment);
332 if (r < 0)
333 return r;
334 break;
335
336 OPTION_LONG("no-block", NULL, "Do not wait until operation finished"):
337 arg_no_block = true;
338 break;
339
340 OPTION('r', "remain-after-exit", NULL,
341 "Leave service around until explicitly stopped"):
342 arg_remain_after_exit = true;
343 break;
344
345 OPTION_LONG("wait", NULL, "Wait until service stopped again"):
346 arg_wait = true;
347 break;
348
349 OPTION_LONG("send-sighup", NULL, "Send SIGHUP when terminating"):
350 arg_send_sighup = true;
351 break;
352
353 OPTION_LONG("service-type", "TYPE", "Service type"):
354 arg_service_type = opts.arg;
355 break;
356
357 OPTION_LONG("uid", "USER", "Run as system user"):
358 r = free_and_strdup_warn(&arg_exec_user, opts.arg);
359 if (r < 0)
360 return r;
361 break;
362
363 OPTION_LONG("gid", "GROUP", "Run as system group"):
364 arg_exec_group = opts.arg;
365 break;
366
367 OPTION_LONG("nice", "NICE", "Nice level"):
368 r = parse_nice(opts.arg, &arg_nice);
369 if (r < 0)
370 return log_error_errno(r, "Failed to parse nice value: %s", opts.arg);
371
372 arg_nice_set = true;
373 break;
374
375 OPTION_LONG("working-directory", "PATH", "Set working directory"):
376 r = parse_path_argument(opts.arg, true, &arg_working_directory);
377 if (r < 0)
378 return r;
379
380 same_dir = false;
381 break;
382
383 OPTION('d', "same-dir", NULL, "Inherit working directory from caller"): {
384 _cleanup_free_ char *p = NULL;
385
386 r = safe_getcwd(&p);
387 if (r < 0)
388 return log_error_errno(r, "Failed to get current working directory: %m");
389
390 if (empty_or_root(p))
391 arg_working_directory = mfree(arg_working_directory);
392 else
393 free_and_replace(arg_working_directory, p);
394
395 same_dir = true;
396 break;
397 }
398
399 OPTION_LONG("root-directory", "PATH", "Set root directory"):
400 r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_root_directory);
401 if (r < 0)
402 return r;
403 break;
404
405 OPTION('R', "same-root-dir", NULL, "Inherit root directory from caller"):
406 r = free_and_strdup_warn(&arg_root_directory, "/");
407 if (r < 0)
408 return r;
409 break;
410
411 OPTION('E', "setenv", "NAME[=VALUE]", "Set environment variable"):
412 r = strv_env_replace_strdup_passthrough(&arg_environment, opts.arg);
413 if (r < 0)
414 return log_error_errno(r, "Cannot assign environment variable %s: %m", opts.arg);
415 break;
416
417 OPTION_LONG("tty", NULL, NULL): {} /* deprecated alias for --pty */
418 OPTION('t', "pty", NULL,
419 "Run service on pseudo TTY as STDIN/STDOUT/STDERR"): {}
420 OPTION('T', "pty-late", NULL,
421 "Just like --pty, but leave TTY access to agents until unit is started up"):
422 arg_stdio |= ARG_STDIO_PTY;
423 arg_pty_late = opts.opt->short_code == 'T';
424 break;
425
426 OPTION('P', "pipe", NULL, "Pass STDIN/STDOUT/STDERR directly to service"):
427 arg_stdio |= ARG_STDIO_DIRECT;
428 break;
429
430 OPTION('q', "quiet", NULL, "Suppress information messages during runtime"):
431 arg_quiet = true;
432 break;
433
434 OPTION('v', "verbose", NULL, "Show unit logs while executing operation"):
435 arg_verbose = true;
436 break;
437
438 OPTION_LONG("output", "MODE",
439 "Controls formatting of verbose logs, see journalctl for valid values"):
440 if (streq(opts.arg, "help"))
441 return DUMP_STRING_TABLE(output_mode, OutputMode, _OUTPUT_MODE_MAX);
442
443 arg_output = output_mode_from_string(opts.arg);
444 if (arg_output < 0)
445 return log_error_errno(arg_output, "Unknown output format '%s'.", opts.arg);
446 break;
447
448 OPTION_COMMON_JSON:
449 r = parse_json_argument(opts.arg, &arg_json_format_flags);
450 if (r <= 0)
451 return r;
452 break;
453
454 OPTION('G', "collect", NULL, "Unload unit after it ran, even when failed"):
455 arg_aggressive_gc = true;
456 break;
457
458 OPTION('S', "shell", NULL, "Invoke a $SHELL interactively"):
459 arg_shell = true;
460 break;
461
462 OPTION_LONG("job-mode", "MODE",
463 "Specify how to deal with already queued jobs, when queueing a new job"):
464 if (streq(opts.arg, "help"))
465 return DUMP_STRING_TABLE(job_mode, JobMode, _JOB_MODE_MAX);
466
467 r = job_mode_from_string(opts.arg);
468 if (r < 0)
469 return log_error_errno(r, "Invalid job mode: %s", opts.arg);
470
471 arg_job_mode = r;
472 break;
473
474 OPTION_LONG("ignore-failure", NULL, "Ignore the exit status of the invoked process"):
475 arg_ignore_failure = true;
476 break;
477
478 OPTION_LONG("background", "COLOR", "Set ANSI color for background"):
479 r = parse_background_argument(opts.arg, &arg_background);
480 if (r < 0)
481 return r;
482 break;
483
484 OPTION_COMMON_NO_PAGER:
485 arg_pager_flags |= PAGER_DISABLE;
486 break;
487
488 OPTION_GROUP("Path options"): {}
489
490 OPTION_LONG("path-property", "NAME=VALUE", "Set path unit property"):
491 if (strv_extend(&arg_path_property, opts.arg) < 0)
492 return log_oom();
493 break;
494
495 OPTION_GROUP("Socket options"): {}
496
497 OPTION_LONG("socket-property", "NAME=VALUE", "Set socket unit property"):
498 if (strv_extend(&arg_socket_property, opts.arg) < 0)
499 return log_oom();
500 break;
501
502 OPTION_GROUP("Timer options"): {}
503
504 OPTION_LONG("on-active", "SECONDS", "Run after SECONDS delay"):
505 r = add_timer_property("OnActiveSec", opts.arg);
506 if (r < 0)
507 return r;
508
509 arg_with_timer = true;
510 break;
511
512 OPTION_LONG("on-boot", "SECONDS", "Run SECONDS after machine was booted up"):
513 r = add_timer_property("OnBootSec", opts.arg);
514 if (r < 0)
515 return r;
516
517 arg_with_timer = true;
518 break;
519
520 OPTION_LONG("on-startup", "SECONDS", "Run SECONDS after systemd activation"):
521 r = add_timer_property("OnStartupSec", opts.arg);
522 if (r < 0)
523 return r;
524
525 arg_with_timer = true;
526 break;
527
528 OPTION_LONG("on-unit-active", "SECONDS", "Run SECONDS after the last activation"):
529 r = add_timer_property("OnUnitActiveSec", opts.arg);
530 if (r < 0)
531 return r;
532
533 arg_with_timer = true;
534 break;
535
536 OPTION_LONG("on-unit-inactive", "SECONDS",
537 "Run SECONDS after the last deactivation"):
538 r = add_timer_property("OnUnitInactiveSec", opts.arg);
539 if (r < 0)
540 return r;
541
542 arg_with_timer = true;
543 break;
544
545 OPTION_LONG("on-calendar", "SPEC", "Realtime timer"): {
546 _cleanup_(calendar_spec_freep) CalendarSpec *cs = NULL;
547
548 r = calendar_spec_from_string(opts.arg, &cs);
549 if (r < 0)
550 return log_error_errno(r, "Failed to parse calendar event specification: %m");
551
552 /* Let's make sure the given calendar event is not in the past */
553 r = calendar_spec_next_usec(cs, now(CLOCK_REALTIME), NULL);
554 if (r == -ENOENT)
555 /* The calendar event is in the past — let's warn about this, but install it
556 * anyway as is. The service manager will trigger the service right away.
557 * Moreover, the server side might have a different clock or timezone than we
558 * do, hence it should decide when or whether to run something. */
559 log_warning("Specified calendar expression is in the past, proceeding anyway.");
560 else if (r < 0)
561 return log_error_errno(r, "Failed to calculate next time calendar expression elapses: %m");
562
563 r = add_timer_property("OnCalendar", opts.arg);
564 if (r < 0)
565 return r;
566
567 arg_with_timer = true;
568 break;
569 }
570
571 OPTION_LONG("on-timezone-change", NULL, "Run when the timezone changes"):
572 r = add_timer_property("OnTimezoneChange", "yes");
573 if (r < 0)
574 return r;
575
576 arg_with_timer = true;
577 break;
578
579 OPTION_LONG("on-clock-change", NULL, "Run when the realtime clock jumps"):
580 r = add_timer_property("OnClockChange", "yes");
581 if (r < 0)
582 return r;
583
584 arg_with_timer = true;
585 break;
586
587 OPTION_LONG("timer-property", "NAME=VALUE", "Set timer unit property"):
588 if (strv_extend(&arg_timer_property, opts.arg) < 0)
589 return log_oom();
590
591 arg_with_timer = arg_with_timer ||
592 STARTSWITH_SET(opts.arg,
593 "OnActiveSec=",
594 "OnBootSec=",
595 "OnStartupSec=",
596 "OnUnitActiveSec=",
597 "OnUnitInactiveSec=",
598 "OnCalendar=");
599 break;
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 (!!arg_path_property + !!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/--pty-late and --pipe are specified we'll automatically pick --pty/--pty-late if we
638 * are connected fully to a TTY and pick direct fd passing otherwise. This way, we
639 * automatically adapt to usage in a shell pipeline, but we are neatly interactive with
640 * tty-level isolation otherwise. */
641 arg_stdio = isatty_safe(STDIN_FILENO) && isatty_safe(STDOUT_FILENO) && isatty_safe(STDERR_FILENO) ?
642 ARG_STDIO_PTY :
643 ARG_STDIO_DIRECT;
644
645 if (arg_pty_late < 0)
646 arg_pty_late = false; /* For systemd-run this defaults to false, for compat reasons */
647
648 char **args = option_parser_get_args(&opts);
649 if (!strv_isempty(args)) {
650 char **l;
651
652 if (arg_shell)
653 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "If --shell is used, no command line is expected.");
654
655 l = strv_copy(args);
656 if (!l)
657 return log_oom();
658
659 strv_free_and_replace(arg_cmdline, l);
660
661 } else if (arg_shell) {
662 _cleanup_free_ char *s = NULL;
663 char **l;
664
665 r = get_shell(&s);
666 if (r < 0)
667 return log_error_errno(r, "Failed to determine shell: %m");
668
669 l = strv_new(s);
670 if (!l)
671 return log_oom();
672
673 strv_free_and_replace(arg_cmdline, l);
674
675 } else if (!arg_unit || !with_trigger)
676 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Command line to execute required.");
677
678 if (arg_runtime_scope == RUNTIME_SCOPE_USER && arg_transport == BUS_TRANSPORT_REMOTE)
679 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
680 "Execution in user context is not supported on remote systems.");
681
682 if (arg_scope && arg_transport == BUS_TRANSPORT_REMOTE)
683 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
684 "Scope execution is not supported on remote systems.");
685
686 if (arg_scope && (arg_remain_after_exit || arg_service_type))
687 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
688 "--remain-after-exit and --service-type= are not supported in --scope mode.");
689
690 if (arg_stdio != ARG_STDIO_NONE) {
691 if (with_trigger || arg_scope)
692 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
693 "--pty/--pty-late/--pipe is not compatible in trigger (path/socket/timer units) or --scope mode.");
694
695 if (arg_transport == BUS_TRANSPORT_REMOTE)
696 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
697 "--pty/--pty-late/--pipe is only supported when connecting to the local system or containers.");
698
699 if (arg_no_block)
700 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
701 "--pty/--pty-late/--pipe is not compatible with --no-block.");
702 }
703
704 if (arg_stdio == ARG_STDIO_PTY && arg_pty_late && streq_ptr(arg_service_type, "oneshot"))
705 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
706 "--pty-late is not compatible with --service-type=oneshot.");
707
708 if (arg_scope && with_trigger)
709 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
710 "Path, socket or timer options are not supported in --scope mode.");
711
712 if (arg_timer_property && !arg_with_timer)
713 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
714 "--timer-property= has no effect without any other timer options.");
715
716 if (arg_wait) {
717 if (arg_no_block)
718 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
719 "--wait may not be combined with --no-block.");
720
721 if (with_trigger)
722 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
723 "--wait may not be combined with path, socket or timer operations.");
724
725 if (arg_scope)
726 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
727 "--wait may not be combined with --scope.");
728 }
729
730 if (arg_scope && arg_root_directory)
731 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
732 "--root-directory= is not supported in --scope mode.");
733
734 if (same_dir && arg_root_directory && !path_equal(arg_root_directory, "/"))
735 return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
736 "--same-dir cannot be used with a root directory other than '/'");
737
738 return 1;
739 }
740
741 static double shell_prompt_hue(void) {
742 if (become_root())
743 return 0; /* red */
744
745 if (arg_empower)
746 return 30; /* orange */
747
748 return 60; /* yellow */
749 }
750
751 static Glyph shell_prompt_glyph(void) {
752 if (become_root())
753 return GLYPH_SUPERHERO;
754
755 if (arg_empower)
756 return GLYPH_PUMPKIN;
757
758 return GLYPH_IDCARD;
759 }
760
761 static Glyph pty_window_glyph(void) {
762 if (become_root())
763 return GLYPH_RED_CIRCLE;
764
765 if (arg_empower)
766 return GLYPH_ORANGE_CIRCLE;
767
768 return GLYPH_YELLOW_CIRCLE;
769 }
770
771 static int parse_argv_sudo_mode(int argc, char *argv[]) {
772 int r;
773
774 /* If invoked as "run0" binary, let's expose a more sudo-like interface. We add various extensions
775 * though (but limit the extension to long options). */
776
777 assert(argc >= 0);
778 assert(argv);
779
780 OptionParser opts = { argc, argv, OPTION_PARSER_STOP_AT_FIRST_NONOPTION, "run0" };
781
782 FOREACH_OPTION_OR_RETURN(c, &opts)
783 switch (c) {
784
785 OPTION_NAMESPACE("run0"): {}
786
787 OPTION_COMMON_HELP:
788 return help_sudo_mode();
789
790 OPTION('V', "version", NULL, "Show package version"):
791 return version();
792
793 OPTION_COMMON_NO_ASK_PASSWORD:
794 arg_ask_password = false;
795 break;
796
797 OPTION_LONG("machine", "CONTAINER", "Operate on local container"):
798 r = parse_machine_argument(opts.arg, &arg_host, &arg_transport);
799 if (r < 0)
800 return r;
801 break;
802
803 OPTION_LONG("unit", "UNIT", "Run under the specified unit name"):
804 arg_unit = opts.arg;
805 break;
806
807 OPTION_LONG("property", "NAME=VALUE", "Set service or scope unit property"):
808 if (strv_extend(&arg_property, opts.arg) < 0)
809 return log_oom();
810 break;
811
812 OPTION_LONG("description", "TEXT", "Description for unit"):
813 r = free_and_strdup_warn(&arg_description, opts.arg);
814 if (r < 0)
815 return r;
816 break;
817
818 OPTION_LONG("slice", "SLICE", "Run in the specified slice"):
819 r = free_and_strdup_warn(&arg_slice, opts.arg);
820 if (r < 0)
821 return r;
822 break;
823
824 OPTION_LONG("slice-inherit", NULL, "Inherit the slice"):
825 arg_slice_inherit = true;
826 break;
827
828 OPTION('u', "user", "USER", "Run as system user"):
829 r = free_and_strdup_warn(&arg_exec_user, opts.arg);
830 if (r < 0)
831 return r;
832 break;
833
834 OPTION('g', "group", "GROUP", "Run as system group"):
835 arg_exec_group = opts.arg;
836 break;
837
838 OPTION_LONG("nice", "NICE", "Nice level"):
839 r = parse_nice(opts.arg, &arg_nice);
840 if (r < 0)
841 return log_error_errno(r, "Failed to parse nice value: %s", opts.arg);
842
843 arg_nice_set = true;
844 break;
845
846 OPTION('D', "chdir", "PATH", "Set working directory"):
847 if (streq(opts.arg, "~"))
848 r = free_and_strdup_warn(&arg_working_directory, opts.arg);
849 else
850 /* Root will be manually suppressed later. */
851 r = parse_path_argument(opts.arg, /* suppress_root= */ false, &arg_working_directory);
852 if (r < 0)
853 return r;
854 break;
855
856 OPTION_LONG("via-shell", NULL, "Invoke command via target user's login shell"):
857 arg_via_shell = true;
858 break;
859
860 OPTION_LONG("login", NULL, NULL): {} /* hidden compat alias for -i */
861 OPTION_SHORT('i', NULL, "Shortcut for --via-shell --chdir='~'"):
862 r = free_and_strdup_warn(&arg_working_directory, "~");
863 if (r < 0)
864 return r;
865
866 arg_via_shell = true;
867 break;
868
869 OPTION_LONG("setenv", "NAME[=VALUE]", "Set environment variable"):
870 r = strv_env_replace_strdup_passthrough(&arg_environment, opts.arg);
871 if (r < 0)
872 return log_error_errno(r, "Cannot assign environment variable %s: %m", opts.arg);
873 break;
874
875 OPTION_LONG("background", "COLOR", "Set ANSI color for background"):
876 r = parse_background_argument(opts.arg, &arg_background);
877 if (r < 0)
878 return r;
879 break;
880
881 OPTION_LONG("pty", NULL, "Request allocation of a pseudo TTY for stdio"): {}
882 OPTION_LONG("pty-late", NULL,
883 "Just like --pty, but leave TTY access to agents until unit is started up"):
884 arg_stdio |= ARG_STDIO_PTY;
885 arg_pty_late = streq(opts.opt->long_code, "pty-late");
886 break;
887
888 OPTION_LONG("pipe", NULL, "Request direct pipe for stdio"):
889 arg_stdio |= ARG_STDIO_DIRECT;
890 break;
891
892 OPTION_LONG("shell-prompt-prefix", "PREFIX", "Set $SHELL_PROMPT_PREFIX"):
893 r = free_and_strdup_warn(&arg_shell_prompt_prefix, opts.arg);
894 if (r < 0)
895 return r;
896 break;
897
898 OPTION_LONG("lightweight", "BOOLEAN",
899 "Control whether to register a session with service manager or without"):
900 r = parse_tristate_argument_with_auto("--lightweight=", opts.arg, &arg_lightweight);
901 if (r < 0)
902 return r;
903 break;
904
905 OPTION_LONG("area", "AREA", "Home area to log into"):
906 /* We allow an empty --area= specification to allow logging into the primary home directory */
907 if (!isempty(opts.arg) && !filename_is_valid(opts.arg))
908 return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid area name, refusing: %s", opts.arg);
909
910 r = free_and_strdup_warn(&arg_area, opts.arg);
911 if (r < 0)
912 return r;
913 break;
914
915 OPTION_LONG("empower", NULL, "Give privileges to selected or current user"):
916 arg_empower = true;
917 break;
918
919 OPTION_LONG("same-root-dir", NULL, NULL): /* hidden */
920 r = free_and_strdup_warn(&arg_root_directory, "/");
921 if (r < 0)
922 return r;
923 break;
924 }
925
926 if (!arg_working_directory) {
927 if (arg_exec_user || arg_area) {
928 /* When switching to a specific user or an area, also switch to its home directory. */
929 arg_working_directory = strdup("~");
930 if (!arg_working_directory)
931 return log_oom();
932 } else {
933 /* When elevating privileges without this being specified, then stay in the current directory */
934 r = safe_getcwd(&arg_working_directory);
935 if (r < 0)
936 return log_error_errno(r, "Failed to get current working directory: %m");
937 }
938 } else {
939 /* Root was not suppressed earlier, to allow the above check to work properly. */
940 if (empty_or_root(arg_working_directory))
941 arg_working_directory = mfree(arg_working_directory);
942 }
943
944 if (!arg_exec_user && (arg_area || arg_empower)) {
945 /* If the user specifies --area= but not --user= then consider this an area switch request,
946 * and default to logging into our own account.
947 *
948 * If the user specifies --empower but not --user= then consider this a request to empower
949 * the current user. */
950
951 arg_exec_user = getusername_malloc();
952 if (!arg_exec_user)
953 return log_oom();
954 }
955
956 arg_service_type = "exec";
957 arg_quiet = true;
958 arg_wait = true;
959 arg_aggressive_gc = true;
960
961 if (IN_SET(arg_stdio, ARG_STDIO_NONE, ARG_STDIO_AUTO))
962 arg_stdio = isatty_safe(STDIN_FILENO) && isatty_safe(STDOUT_FILENO) && isatty_safe(STDERR_FILENO) ? ARG_STDIO_PTY : ARG_STDIO_DIRECT;
963 log_debug("Using %s stdio mode.", arg_stdio == ARG_STDIO_PTY ? "pty" : "direct");
964 if (arg_pty_late < 0)
965 arg_pty_late = arg_ask_password; /* for run0 this defaults to on, except if --no-ask-password is used */
966
967 arg_expand_environment = false;
968 arg_send_sighup = true;
969
970 _cleanup_strv_free_ char **l = NULL;
971 char **args = option_parser_get_args(&opts);
972 if (!strv_isempty(args)) {
973 l = strv_copy(args);
974 if (!l)
975 return log_oom();
976 } else if (!arg_via_shell) {
977 const char *e;
978
979 e = strv_env_get(arg_environment, "SHELL");
980 if (e) {
981 arg_exec_path = strdup(e);
982 if (!arg_exec_path)
983 return log_oom();
984 } else {
985 if (arg_transport == BUS_TRANSPORT_LOCAL) {
986 r = get_shell(&arg_exec_path);
987 if (r < 0)
988 return log_error_errno(r, "Failed to determine shell: %m");
989 } else {
990 arg_exec_path = strdup("/bin/sh");
991 if (!arg_exec_path)
992 return log_oom();
993 }
994
995 r = strv_env_assign(&arg_environment, "SHELL", arg_exec_path);
996 if (r < 0)
997 return log_error_errno(r, "Failed to set $SHELL environment variable: %m");
998 }
999
1000 l = make_login_shell_cmdline(arg_exec_path);
1001 if (!l)
1002 return log_oom();
1003 }
1004
1005 if (arg_via_shell) {
1006 arg_exec_path = strdup(_PATH_BSHELL);
1007 if (!arg_exec_path)
1008 return log_oom();
1009
1010 r = strv_prepend(&l, "-sh");
1011 if (r < 0)
1012 return log_oom();
1013 }
1014
1015 strv_free_and_replace(arg_cmdline, l);
1016
1017 if (!arg_slice) {
1018 arg_slice = strdup(SPECIAL_USER_SLICE);
1019 if (!arg_slice)
1020 return log_oom();
1021 }
1022
1023 _cleanup_free_ char *un = NULL;
1024 un = getusername_malloc();
1025 if (!un)
1026 return log_oom();
1027
1028 /* Set a bunch of environment variables in a roughly sudo-compatible way */
1029 r = strv_env_assign(&arg_environment, "SUDO_USER", un);
1030 if (r < 0)
1031 return log_error_errno(r, "Failed to set $SUDO_USER environment variable: %m");
1032
1033 r = strv_env_assignf(&arg_environment, "SUDO_UID", UID_FMT, getuid());
1034 if (r < 0)
1035 return log_error_errno(r, "Failed to set $SUDO_UID environment variable: %m");
1036
1037 r = strv_env_assignf(&arg_environment, "SUDO_GID", GID_FMT, getgid());
1038 if (r < 0)
1039 return log_error_errno(r, "Failed to set $SUDO_GID environment variable: %m");
1040
1041 if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_UID=" UID_FMT, getuid()) < 0)
1042 return log_oom();
1043
1044 if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_GID=" GID_FMT, getgid()) < 0)
1045 return log_oom();
1046
1047 if (strv_extendf(&arg_property, "LogExtraFields=ELEVATED_USER=%s", un) < 0)
1048 return log_oom();
1049
1050 if (strv_extend(&arg_property, "PAMName=systemd-run0") < 0)
1051 return log_oom();
1052
1053 /* The service manager ignores SIGPIPE for all spawned processes by default. Let's explicitly override
1054 * that here, since we're primarily invoked in interactive environments where this does matter. */
1055 if (strv_extend(&arg_property, "IgnoreSIGPIPE=no") < 0)
1056 return log_oom();
1057
1058 if (!arg_background && arg_stdio == ARG_STDIO_PTY) {
1059 r = terminal_tint_color(shell_prompt_hue(), &arg_background);
1060 if (r < 0)
1061 log_debug_errno(r, "Unable to get terminal background color, not tinting background: %m");
1062 }
1063
1064 if (!arg_shell_prompt_prefix) {
1065 const char *e = secure_getenv("SYSTEMD_RUN_SHELL_PROMPT_PREFIX");
1066 if (e) {
1067 arg_shell_prompt_prefix = strdup(e);
1068 if (!arg_shell_prompt_prefix)
1069 return log_oom();
1070 } else if (emoji_enabled()) {
1071 arg_shell_prompt_prefix = strjoin(glyph(shell_prompt_glyph()), " ");
1072 if (!arg_shell_prompt_prefix)
1073 return log_oom();
1074 }
1075 }
1076
1077 if (!isempty(arg_shell_prompt_prefix)) {
1078 r = strv_env_assign(&arg_environment, "SHELL_PROMPT_PREFIX", arg_shell_prompt_prefix);
1079 if (r < 0)
1080 return log_error_errno(r, "Failed to set $SHELL_PROMPT_PREFIX environment variable: %m");
1081 }
1082
1083 if (!strv_env_get(arg_environment, "XDG_SESSION_CLASS")) {
1084
1085 /* If logging into an area, imply lightweight mode */
1086 if (arg_lightweight < 0 && !isempty(arg_area))
1087 arg_lightweight = true;
1088
1089 /* When using run0 to acquire privileges temporarily, let's not pull in session manager by
1090 * default. Note that pam_logind/systemd-logind doesn't distinguish between run0-style privilege
1091 * escalation on a TTY and first class (getty-style) TTY logins (and thus gives root a per-session
1092 * manager for interactive TTY sessions), hence let's override the logic explicitly here. We only do
1093 * this for root or --empower though, under the assumption that if a regular user temporarily
1094 * transitions into another regular user it's a better default that the full user environment is
1095 * uniformly available. */
1096 if (arg_lightweight < 0 && (become_root() || arg_empower))
1097 arg_lightweight = true;
1098
1099 if (arg_lightweight >= 0) {
1100 const char *class =
1101 arg_lightweight ? (arg_stdio == ARG_STDIO_PTY ? (become_root() ? "user-early-light" : "user-light") : "background-light") :
1102 (arg_stdio == ARG_STDIO_PTY ? (become_root() ? "user-early" : "user") : "background");
1103
1104 log_debug("Setting XDG_SESSION_CLASS to '%s'.", class);
1105
1106 r = strv_env_assign(&arg_environment, "XDG_SESSION_CLASS", class);
1107 if (r < 0)
1108 return log_error_errno(r, "Failed to set $XDG_SESSION_CLASS environment variable: %m");
1109 }
1110 }
1111
1112 if (arg_area) {
1113 r = strv_env_assign(&arg_environment, "XDG_AREA", arg_area);
1114 if (r < 0)
1115 return log_error_errno(r, "Failed to set $XDG_AREA environment variable: %m");
1116 }
1117
1118 return 1;
1119 }
1120
1121 static int transient_unit_set_properties(sd_bus_message *m, UnitType t, char **properties) {
1122 int r;
1123
1124 assert(m);
1125
1126 r = sd_bus_message_append(m, "(sv)", "Description", "s", arg_description);
1127 if (r < 0)
1128 return bus_log_create_error(r);
1129
1130 if (arg_aggressive_gc) {
1131 r = sd_bus_message_append(m, "(sv)", "CollectMode", "s", "inactive-or-failed");
1132 if (r < 0)
1133 return bus_log_create_error(r);
1134 }
1135
1136 r = sd_bus_is_bus_client(sd_bus_message_get_bus(m));
1137 if (r < 0)
1138 return log_error_errno(r, "Can't determine if bus connection is direct or to broker: %m");
1139 if (r > 0) {
1140 /* Pin the object as least as long as we are around. Note that AddRef (currently) only works
1141 * if we talk via the bus though. */
1142 r = sd_bus_message_append(m, "(sv)", "AddRef", "b", 1);
1143 if (r < 0)
1144 return bus_log_create_error(r);
1145 }
1146
1147 return bus_append_unit_property_assignment_many(m, t, properties);
1148 }
1149
1150 static int transient_cgroup_set_properties(sd_bus_message *m) {
1151 _cleanup_free_ char *name = NULL;
1152 _cleanup_free_ char *slice = NULL;
1153 int r;
1154
1155 assert(m);
1156
1157 if (arg_slice_inherit) {
1158 char *end;
1159
1160 switch (arg_runtime_scope) {
1161
1162 case RUNTIME_SCOPE_USER:
1163 r = cg_pid_get_user_slice(0, &name);
1164 break;
1165
1166 case RUNTIME_SCOPE_SYSTEM:
1167 r = cg_pid_get_slice(0, &name);
1168 break;
1169
1170 default:
1171 assert_not_reached();
1172 }
1173
1174 if (r < 0)
1175 return log_error_errno(r, "Failed to get PID slice: %m");
1176
1177 end = endswith(name, ".slice");
1178 if (!end)
1179 return -ENXIO;
1180 *end = 0;
1181 }
1182
1183 if (!isempty(arg_slice) && !strextend_with_separator(&name, "-", arg_slice))
1184 return log_oom();
1185
1186 if (!name)
1187 return 0;
1188
1189 r = unit_name_mangle_with_suffix(name, "as slice",
1190 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
1191 ".slice", &slice);
1192 if (r < 0)
1193 return log_error_errno(r, "Failed to mangle name '%s': %m", arg_slice);
1194
1195 r = sd_bus_message_append(m, "(sv)", "Slice", "s", slice);
1196 if (r < 0)
1197 return bus_log_create_error(r);
1198
1199 return 0;
1200 }
1201
1202 static int transient_kill_set_properties(sd_bus_message *m) {
1203 int r;
1204
1205 assert(m);
1206
1207 if (arg_send_sighup) {
1208 r = sd_bus_message_append(m, "(sv)", "SendSIGHUP", "b", arg_send_sighup);
1209 if (r < 0)
1210 return bus_log_create_error(r);
1211 }
1212
1213 return 0;
1214 }
1215
1216 static int transient_service_set_properties(sd_bus_message *m, const char *pty_path, int pty_fd) {
1217 int r, send_term; /* tri-state */
1218
1219 /* Use ExecStartEx if new exec flags are required. */
1220 bool use_ex_prop = !arg_expand_environment || arg_via_shell;
1221
1222 assert(m);
1223 assert((!!pty_path) == (pty_fd >= 0));
1224
1225 r = transient_unit_set_properties(m, UNIT_SERVICE, arg_property);
1226 if (r < 0)
1227 return r;
1228
1229 r = transient_kill_set_properties(m);
1230 if (r < 0)
1231 return r;
1232
1233 r = transient_cgroup_set_properties(m);
1234 if (r < 0)
1235 return r;
1236
1237 if (arg_remain_after_exit) {
1238 r = sd_bus_message_append(m, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit);
1239 if (r < 0)
1240 return bus_log_create_error(r);
1241 }
1242
1243 if (arg_service_type) {
1244 r = sd_bus_message_append(m, "(sv)", "Type", "s", arg_service_type);
1245 if (r < 0)
1246 return bus_log_create_error(r);
1247 }
1248
1249 if (arg_exec_user) {
1250 r = sd_bus_message_append(m, "(sv)", "User", "s", arg_exec_user);
1251 if (r < 0)
1252 return bus_log_create_error(r);
1253 }
1254
1255 if (arg_exec_group) {
1256 r = sd_bus_message_append(m, "(sv)", "Group", "s", arg_exec_group);
1257 if (r < 0)
1258 return bus_log_create_error(r);
1259 }
1260
1261 if (arg_empower) {
1262 r = sd_bus_message_append(m, "(sv)", "AmbientCapabilities", "t", CAP_MASK_ALL);
1263 if (r < 0)
1264 return bus_log_create_error(r);
1265
1266 r = getgrnam_malloc("empower", /* ret= */ NULL);
1267 if (r < 0 && r != -ESRCH)
1268 return log_error_errno(r, "Failed to look up group 'empower' via NSS: %m");
1269 if (r >= 0) {
1270 r = sd_bus_message_append(m, "(sv)", "SupplementaryGroups", "as", 1, "empower");
1271 if (r < 0)
1272 return bus_log_create_error(r);
1273 }
1274 }
1275
1276 if (arg_nice_set) {
1277 r = sd_bus_message_append(m, "(sv)", "Nice", "i", arg_nice);
1278 if (r < 0)
1279 return bus_log_create_error(r);
1280 }
1281
1282 if (arg_working_directory) {
1283 r = sd_bus_message_append(m, "(sv)", "WorkingDirectory", "s", arg_working_directory);
1284 if (r < 0)
1285 return bus_log_create_error(r);
1286 }
1287
1288 if (arg_root_directory) {
1289 _cleanup_close_ int fd = open_tree(AT_FDCWD, arg_root_directory, OPEN_TREE_CLONE|OPEN_TREE_CLOEXEC|AT_RECURSIVE);
1290 if (fd < 0)
1291 return log_error_errno(errno, "Failed to clone mount tree at '%s': %m", arg_root_directory);
1292
1293 r = sd_bus_message_append(m, "(sv)", "RootDirectoryFileDescriptor", "h", fd);
1294 if (r < 0)
1295 return bus_log_create_error(r);
1296 }
1297
1298 if (pty_path) {
1299 r = sd_bus_message_append(m, "(sv)(sv)(sv)(sv)",
1300 "TTYPath", "s", pty_path,
1301 "StandardInputFileDescriptor", "h", pty_fd,
1302 "StandardOutputFileDescriptor", "h", pty_fd,
1303 "StandardErrorFileDescriptor", "h", pty_fd);
1304 if (r < 0)
1305 return bus_log_create_error(r);
1306
1307 send_term = true;
1308
1309 } else if (arg_stdio == ARG_STDIO_DIRECT) {
1310 r = sd_bus_message_append(m,
1311 "(sv)(sv)(sv)",
1312 "StandardInputFileDescriptor", "h", STDIN_FILENO,
1313 "StandardOutputFileDescriptor", "h", STDOUT_FILENO,
1314 "StandardErrorFileDescriptor", "h", STDERR_FILENO);
1315 if (r < 0)
1316 return bus_log_create_error(r);
1317
1318 send_term = -1;
1319 } else
1320 send_term = false;
1321
1322 if (send_term != 0) {
1323 const char *e, *colorterm = NULL, *no_color = NULL;
1324
1325 /* Propagate $TERM + $COLORTERM + $NO_COLOR if we are actually connected to a TTY */
1326 if (isatty_safe(STDIN_FILENO) || isatty_safe(STDOUT_FILENO) || isatty_safe(STDERR_FILENO)) {
1327 e = strv_find_prefix(environ, "TERM=");
1328 send_term = !!e;
1329
1330 if (send_term) {
1331 /* If we send $TERM along, then also propagate $COLORTERM + $NO_COLOR right with it */
1332 colorterm = strv_find_prefix(environ, "COLORTERM=");
1333 no_color = strv_find_prefix(environ, "NO_COLOR=");
1334 }
1335 } else
1336 /* If we are not connected to any TTY ourselves, then send TERM=dumb, but only if we
1337 * really need to (because we actually allocated a TTY for the service) */
1338 e = "TERM=dumb";
1339
1340 if (send_term > 0) {
1341 r = sd_bus_message_append(
1342 m,
1343 "(sv)",
1344 "Environment", "as", 1, e);
1345 if (r < 0)
1346 return bus_log_create_error(r);
1347
1348 if (colorterm) {
1349 r = sd_bus_message_append(
1350 m,
1351 "(sv)",
1352 "Environment", "as", 1, colorterm);
1353 if (r < 0)
1354 return bus_log_create_error(r);
1355 }
1356
1357 if (no_color) {
1358 r = sd_bus_message_append(
1359 m,
1360 "(sv)",
1361 "Environment", "as", 1, no_color);
1362 if (r < 0)
1363 return bus_log_create_error(r);
1364 }
1365 }
1366 }
1367
1368 if (!strv_isempty(arg_environment)) {
1369 r = sd_bus_message_open_container(m, 'r', "sv");
1370 if (r < 0)
1371 return bus_log_create_error(r);
1372
1373 r = sd_bus_message_append(m, "s", "Environment");
1374 if (r < 0)
1375 return bus_log_create_error(r);
1376
1377 r = sd_bus_message_open_container(m, 'v', "as");
1378 if (r < 0)
1379 return bus_log_create_error(r);
1380
1381 r = sd_bus_message_append_strv(m, arg_environment);
1382 if (r < 0)
1383 return bus_log_create_error(r);
1384
1385 r = sd_bus_message_close_container(m);
1386 if (r < 0)
1387 return bus_log_create_error(r);
1388
1389 r = sd_bus_message_close_container(m);
1390 if (r < 0)
1391 return bus_log_create_error(r);
1392 }
1393
1394 /* Exec container */
1395 if (!strv_isempty(arg_cmdline)) {
1396 r = sd_bus_message_open_container(m, 'r', "sv");
1397 if (r < 0)
1398 return bus_log_create_error(r);
1399
1400 r = sd_bus_message_append(m, "s",
1401 use_ex_prop ? "ExecStartEx" : "ExecStart");
1402 if (r < 0)
1403 return bus_log_create_error(r);
1404
1405 r = sd_bus_message_open_container(m, 'v',
1406 use_ex_prop ? "a(sasas)" : "a(sasb)");
1407 if (r < 0)
1408 return bus_log_create_error(r);
1409
1410 r = sd_bus_message_open_container(m, 'a',
1411 use_ex_prop ? "(sasas)" : "(sasb)");
1412 if (r < 0)
1413 return bus_log_create_error(r);
1414
1415 r = sd_bus_message_open_container(m, 'r',
1416 use_ex_prop ? "sasas" : "sasb");
1417 if (r < 0)
1418 return bus_log_create_error(r);
1419
1420 r = sd_bus_message_append(m, "s", arg_exec_path ?: arg_cmdline[0]);
1421 if (r < 0)
1422 return bus_log_create_error(r);
1423
1424 r = sd_bus_message_append_strv(m, arg_cmdline);
1425 if (r < 0)
1426 return bus_log_create_error(r);
1427
1428 if (use_ex_prop) {
1429 _cleanup_strv_free_ char **opts = NULL;
1430
1431 r = exec_command_flags_to_strv(
1432 (arg_expand_environment ? 0 : EXEC_COMMAND_NO_ENV_EXPAND)|
1433 (arg_ignore_failure ? EXEC_COMMAND_IGNORE_FAILURE : 0)|
1434 (arg_via_shell ? EXEC_COMMAND_VIA_SHELL : 0),
1435 &opts);
1436 if (r < 0)
1437 return log_error_errno(r, "Failed to format execute flags: %m");
1438
1439 r = sd_bus_message_append_strv(m, opts);
1440 } else
1441 r = sd_bus_message_append(m, "b", arg_ignore_failure);
1442 if (r < 0)
1443 return bus_log_create_error(r);
1444
1445 r = sd_bus_message_close_container(m);
1446 if (r < 0)
1447 return bus_log_create_error(r);
1448
1449 r = sd_bus_message_close_container(m);
1450 if (r < 0)
1451 return bus_log_create_error(r);
1452
1453 r = sd_bus_message_close_container(m);
1454 if (r < 0)
1455 return bus_log_create_error(r);
1456
1457 r = sd_bus_message_close_container(m);
1458 if (r < 0)
1459 return bus_log_create_error(r);
1460 }
1461
1462 return 0;
1463 }
1464
1465 static int transient_scope_set_properties(sd_bus_message *m, bool allow_pidfd) {
1466 int r;
1467
1468 assert(m);
1469
1470 r = transient_unit_set_properties(m, UNIT_SCOPE, arg_property);
1471 if (r < 0)
1472 return r;
1473
1474 r = transient_kill_set_properties(m);
1475 if (r < 0)
1476 return r;
1477
1478 r = transient_cgroup_set_properties(m);
1479 if (r < 0)
1480 return r;
1481
1482 _cleanup_(pidref_done) PidRef pidref = PIDREF_NULL;
1483
1484 r = pidref_set_self(&pidref);
1485 if (r < 0)
1486 return r;
1487
1488 r = bus_append_scope_pidref(m, &pidref, allow_pidfd);
1489 if (r < 0)
1490 return bus_log_create_error(r);
1491
1492 return 0;
1493 }
1494
1495 static int transient_timer_set_properties(sd_bus_message *m) {
1496 int r;
1497
1498 assert(m);
1499
1500 r = transient_unit_set_properties(m, UNIT_TIMER, arg_timer_property);
1501 if (r < 0)
1502 return r;
1503
1504 /* Automatically clean up our transient timers */
1505 r = sd_bus_message_append(m, "(sv)", "RemainAfterElapse", "b", false);
1506 if (r < 0)
1507 return bus_log_create_error(r);
1508
1509 return 0;
1510 }
1511
1512 static int make_unit_name(UnitType t, char **ret) {
1513 int r;
1514
1515 assert(t >= 0);
1516 assert(t < _UNIT_TYPE_MAX);
1517 assert(ret);
1518
1519 /* Preferably use our PID + pidfd ID as identifier, if available. It's a boot time unique identifier
1520 * managed by the kernel. Unfortunately only new kernels support this, hence we keep some fallback
1521 * logic in place. */
1522
1523 _cleanup_(pidref_done) PidRef self = PIDREF_NULL;
1524 r = pidref_set_self(&self);
1525 if (r < 0)
1526 return log_error_errno(r, "Failed to get reference to my own process: %m");
1527
1528 r = pidref_acquire_pidfd_id(&self);
1529 if (r < 0) {
1530 log_debug_errno(r, "Failed to acquire pidfd ID of myself, defaulting to randomized unit name: %m");
1531
1532 /* We couldn't get the pidfd id. In that case, just pick a random uuid as name */
1533 sd_id128_t rnd;
1534 r = sd_id128_randomize(&rnd);
1535 if (r < 0)
1536 return log_error_errno(r, "Failed to generate random run unit name: %m");
1537
1538 r = asprintf(ret, "run-r" SD_ID128_FORMAT_STR ".%s", SD_ID128_FORMAT_VAL(rnd), unit_type_to_string(t));
1539 } else
1540 r = asprintf(ret, "run-p" PID_FMT "-i%" PRIu64 ".%s", self.pid, self.fd_id, unit_type_to_string(t));
1541 if (r < 0)
1542 return log_oom();
1543
1544 return 0;
1545 }
1546
1547 static int connect_bus(sd_bus **ret) {
1548 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1549 int r;
1550
1551 assert(ret);
1552
1553 /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the
1554 * limited direct connection */
1555 if (arg_wait ||
1556 arg_stdio != ARG_STDIO_NONE ||
1557 (arg_runtime_scope == RUNTIME_SCOPE_USER && !IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_CAPSULE)))
1558 r = bus_connect_transport(arg_transport, arg_host, arg_runtime_scope, &bus);
1559 else
1560 r = bus_connect_transport_systemd(arg_transport, arg_host, arg_runtime_scope, &bus);
1561 if (r < 0)
1562 return bus_log_connect_error(r, arg_transport, arg_runtime_scope);
1563
1564 (void) sd_bus_set_allow_interactive_authorization(bus, arg_ask_password);
1565
1566 *ret = TAKE_PTR(bus);
1567 return 0;
1568 }
1569
1570 typedef struct RunContext {
1571 sd_event *event;
1572 PTYForward *forward;
1573 char *unit;
1574 char *bus_path;
1575 char *start_job;
1576 int pty_fd;
1577
1578 /* Bus objects */
1579 sd_bus *bus;
1580 sd_bus_slot *match_properties_changed;
1581 sd_bus_slot *match_disconnected;
1582 sd_event_source *retry_timer;
1583
1584 /* Current state of the unit */
1585 char *active_state;
1586 char *job;
1587
1588 /* The exit data of the unit */
1589 uint64_t inactive_exit_usec;
1590 uint64_t inactive_enter_usec;
1591 char *result;
1592 uint64_t cpu_usage_nsec;
1593 uint64_t memory_peak;
1594 uint64_t memory_swap_peak;
1595 uint64_t ip_ingress_bytes;
1596 uint64_t ip_egress_bytes;
1597 uint64_t io_read_bytes;
1598 uint64_t io_write_bytes;
1599 uint32_t exit_code;
1600 uint32_t exit_status;
1601 } RunContext;
1602
1603 static int run_context_update(RunContext *c);
1604 static int run_context_attach_bus(RunContext *c, sd_bus *bus);
1605 static void run_context_detach_bus(RunContext *c);
1606 static int run_context_reconnect(RunContext *c);
1607 static int run_context_setup_ptyfwd(RunContext *c);
1608
1609 static void run_context_done(RunContext *c) {
1610 assert(c);
1611
1612 run_context_detach_bus(c);
1613
1614 c->retry_timer = sd_event_source_disable_unref(c->retry_timer);
1615 c->forward = pty_forward_free(c->forward);
1616 c->event = sd_event_unref(c->event);
1617
1618 free(c->active_state);
1619 free(c->job);
1620 free(c->result);
1621 free(c->unit);
1622 free(c->bus_path);
1623 free(c->start_job);
1624
1625 safe_close(c->pty_fd);
1626 }
1627
1628 static int on_retry_timer(sd_event_source *s, uint64_t usec, void *userdata) {
1629 RunContext *c = ASSERT_PTR(userdata);
1630
1631 c->retry_timer = sd_event_source_disable_unref(c->retry_timer);
1632
1633 return run_context_reconnect(c);
1634 }
1635
1636 static int run_context_reconnect(RunContext *c) {
1637 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1638 _cleanup_(sd_bus_unrefp) sd_bus *bus = NULL;
1639 int r;
1640
1641 assert(c);
1642
1643 run_context_detach_bus(c);
1644
1645 r = connect_bus(&bus);
1646 if (r < 0)
1647 goto retry_timer;
1648
1649 r = sd_bus_call_method(bus,
1650 "org.freedesktop.systemd1",
1651 c->bus_path,
1652 "org.freedesktop.systemd1.Unit",
1653 "Ref",
1654 &error,
1655 /* ret_reply= */ NULL,
1656 /* types= */ NULL);
1657 if (r < 0) {
1658 /* Hmm, the service manager probably hasn't finished reexecution just yet? Try again later. */
1659 if (bus_error_is_connection(&error) || bus_error_is_unknown_service(&error))
1660 goto retry_timer;
1661
1662 if (sd_bus_error_has_name(&error, SD_BUS_ERROR_UNKNOWN_OBJECT))
1663 log_warning_errno(r, "Unit deactivated during reconnection to the bus, exiting.");
1664 else
1665 log_error_errno(r, "Failed to re-add reference to unit: %s", bus_error_message(&error, r));
1666
1667 (void) sd_event_exit(c->event, EXIT_FAILURE);
1668 return r;
1669 }
1670
1671 r = run_context_attach_bus(c, bus);
1672 if (r < 0) {
1673 (void) sd_event_exit(c->event, EXIT_FAILURE);
1674 return r;
1675 }
1676
1677 log_info("Reconnected to bus.");
1678
1679 return run_context_update(c);
1680
1681 retry_timer:
1682 log_warning_errno(r, "Failed to reconnect, retrying in 2s: %m");
1683
1684 r = event_reset_time_relative(
1685 c->event,
1686 &c->retry_timer,
1687 CLOCK_MONOTONIC,
1688 2 * USEC_PER_SEC, /* accuracy= */ 0,
1689 on_retry_timer, c,
1690 SD_EVENT_PRIORITY_NORMAL,
1691 "retry-timeout",
1692 /* force_reset= */ false);
1693 if (r < 0) {
1694 (void) sd_event_exit(c->event, EXIT_FAILURE);
1695 return log_error_errno(r, "Failed to install retry timer: %m");
1696 }
1697
1698 return 0;
1699 }
1700
1701 static int run_context_check_started(RunContext *c) {
1702 int r;
1703
1704 assert(c);
1705
1706 if (!c->start_job)
1707 return 0; /* Already started? */
1708
1709 if (streq_ptr(c->start_job, c->job))
1710 return 0; /* The start job is still active. */
1711
1712 /* The start job is finished. */
1713 c->start_job = mfree(c->start_job);
1714
1715 /* Setup ptyfwd now if --pty-late is specified. */
1716 r = run_context_setup_ptyfwd(c);
1717 if (r < 0) {
1718 (void) sd_event_exit(c->event, EXIT_FAILURE);
1719 return r;
1720 }
1721
1722 if (STRPTR_IN_SET(c->active_state, "inactive", "failed"))
1723 return 0; /* Already finished or failed? */
1724
1725 /* Notify our caller that the service is now running, just in case. */
1726 (void) sd_notifyf(/* unset_environment= */ false,
1727 "READY=1\n"
1728 "RUN_UNIT=%s",
1729 c->unit);
1730 return 0;
1731 }
1732
1733 static void run_context_check_done(RunContext *c) {
1734 int r;
1735
1736 assert(c);
1737
1738 if (!STRPTR_IN_SET(c->active_state, "inactive", "failed") ||
1739 c->start_job || /* our start job */
1740 c->job) /* any other job */
1741 return;
1742
1743 if (!c->forward)
1744 return (void) sd_event_exit(c->event, EXIT_SUCCESS);
1745
1746 /* If the service is gone, it's time to drain the output */
1747 r = pty_forward_drain(c->forward);
1748 if (r < 0) {
1749 log_error_errno(r, "Failed to drain PTY forwarder: %m");
1750 return (void) sd_event_exit(c->event, EXIT_FAILURE);
1751 }
1752
1753 /* Tell the forwarder to exit on the next vhangup(), so that we still flush out what might be queued
1754 * and exit then. */
1755 r = pty_forward_honor_vhangup(c->forward);
1756 if (r < 0) {
1757 log_error_errno(r, "Failed to make PTY forwarder honor vhangup(): %m");
1758 return (void) sd_event_exit(c->event, EXIT_FAILURE);
1759 }
1760 }
1761
1762 static int map_job(sd_bus *bus, const char *member, sd_bus_message *m, sd_bus_error *error, void *userdata) {
1763 char **p = ASSERT_PTR(userdata);
1764 const char *job;
1765 uint32_t id;
1766 int r;
1767
1768 assert(m);
1769
1770 r = sd_bus_message_read(m, "(uo)", &id, &job);
1771 if (r < 0)
1772 return r;
1773
1774 return free_and_strdup(p, id == 0 ? NULL : job);
1775 }
1776
1777 static int run_context_update(RunContext *c) {
1778
1779 static const struct bus_properties_map map[] = {
1780 { "ActiveState", "s", NULL, offsetof(RunContext, active_state) },
1781 { "InactiveExitTimestampMonotonic", "t", NULL, offsetof(RunContext, inactive_exit_usec) },
1782 { "InactiveEnterTimestampMonotonic", "t", NULL, offsetof(RunContext, inactive_enter_usec) },
1783 { "Result", "s", NULL, offsetof(RunContext, result) },
1784 { "ExecMainCode", "i", NULL, offsetof(RunContext, exit_code) },
1785 { "ExecMainStatus", "i", NULL, offsetof(RunContext, exit_status) },
1786 { "CPUUsageNSec", "t", NULL, offsetof(RunContext, cpu_usage_nsec) },
1787 { "MemoryPeak", "t", NULL, offsetof(RunContext, memory_peak) },
1788 { "MemorySwapPeak", "t", NULL, offsetof(RunContext, memory_swap_peak) },
1789 { "IPIngressBytes", "t", NULL, offsetof(RunContext, ip_ingress_bytes) },
1790 { "IPEgressBytes", "t", NULL, offsetof(RunContext, ip_egress_bytes) },
1791 { "IOReadBytes", "t", NULL, offsetof(RunContext, io_read_bytes) },
1792 { "IOWriteBytes", "t", NULL, offsetof(RunContext, io_write_bytes) },
1793 { "Job", "(uo)", map_job, offsetof(RunContext, job) },
1794 {}
1795 };
1796
1797 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1798 int r;
1799
1800 assert(c);
1801 assert(c->bus);
1802
1803 r = bus_map_all_properties(
1804 c->bus,
1805 "org.freedesktop.systemd1",
1806 c->bus_path,
1807 map,
1808 BUS_MAP_STRDUP,
1809 &error,
1810 NULL,
1811 c);
1812 if (r < 0) {
1813 /* If this is a connection error, then try to reconnect. This might be because the service
1814 * manager is being restarted. Handle this gracefully. */
1815 if (bus_error_is_connection(&error) || bus_error_is_unknown_service(&error)) {
1816 log_info_errno(r, "Bus call failed due to connection problems. Trying to reconnect...");
1817 /* Not propagating error, because we handled it already, by reconnecting. */
1818 return run_context_reconnect(c);
1819 }
1820
1821 (void) sd_event_exit(c->event, EXIT_FAILURE);
1822 return log_error_errno(r, "Failed to query unit state: %s", bus_error_message(&error, r));
1823 }
1824
1825 r = run_context_check_started(c);
1826 if (r < 0)
1827 return r;
1828
1829 run_context_check_done(c);
1830 return 0;
1831 }
1832
1833 static int on_properties_changed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1834 return run_context_update(ASSERT_PTR(userdata));
1835 }
1836
1837 static int on_disconnected(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1838 /* If our connection gets terminated, then try to reconnect. This might be because the service
1839 * manager is being restarted. Handle this gracefully. */
1840 log_info("Got disconnected from bus connection. Trying to reconnect...");
1841 return run_context_reconnect(ASSERT_PTR(userdata));
1842 }
1843
1844 static int run_context_attach_bus(RunContext *c, sd_bus *bus) {
1845 int r;
1846
1847 assert(c);
1848 assert(bus);
1849
1850 assert(!c->bus);
1851 assert(!c->match_properties_changed);
1852 assert(!c->match_disconnected);
1853
1854 c->bus = sd_bus_ref(bus);
1855
1856 r = sd_bus_match_signal_async(
1857 c->bus,
1858 &c->match_properties_changed,
1859 "org.freedesktop.systemd1",
1860 c->bus_path,
1861 "org.freedesktop.DBus.Properties",
1862 "PropertiesChanged",
1863 on_properties_changed, NULL, c);
1864 if (r < 0)
1865 return log_error_errno(r, "Failed to request PropertiesChanged signal match: %m");
1866
1867 r = sd_bus_match_signal_async(
1868 bus,
1869 &c->match_disconnected,
1870 "org.freedesktop.DBus.Local",
1871 /* path= */ NULL,
1872 "org.freedesktop.DBus.Local",
1873 "Disconnected",
1874 on_disconnected, NULL, c);
1875 if (r < 0)
1876 return log_error_errno(r, "Failed to request Disconnected signal match: %m");
1877
1878 r = sd_bus_attach_event(c->bus, c->event, SD_EVENT_PRIORITY_NORMAL);
1879 if (r < 0)
1880 return log_error_errno(r, "Failed to attach bus to event loop: %m");
1881
1882 return 0;
1883 }
1884
1885 static void run_context_detach_bus(RunContext *c) {
1886 assert(c);
1887
1888 if (c->bus) {
1889 (void) sd_bus_detach_event(c->bus);
1890 c->bus = sd_bus_unref(c->bus);
1891 }
1892
1893 c->match_properties_changed = sd_bus_slot_unref(c->match_properties_changed);
1894 c->match_disconnected = sd_bus_slot_unref(c->match_disconnected);
1895 }
1896
1897 static int pty_forward_handler(PTYForward *f, int rcode, void *userdata) {
1898 RunContext *c = ASSERT_PTR(userdata);
1899
1900 assert(f);
1901
1902 if (rcode == -ECANCELED) {
1903 log_debug_errno(rcode, "PTY forwarder disconnected.");
1904 if (!arg_wait)
1905 return sd_event_exit(c->event, EXIT_SUCCESS);
1906
1907 /* If --wait is specified, we'll only exit the pty forwarding, but will continue to wait
1908 * for the service to end. If the user hits ^C we'll exit too. */
1909 } else if (rcode < 0) {
1910 (void) sd_event_exit(c->event, EXIT_FAILURE);
1911 return log_error_errno(rcode, "Error on PTY forwarding logic: %m");
1912 }
1913
1914 c->forward = pty_forward_free(c->forward);
1915
1916 run_context_check_done(c);
1917 return 0;
1918 }
1919
1920 static int make_transient_service_unit(
1921 sd_bus *bus,
1922 sd_bus_message **message,
1923 const char *service,
1924 const char *pty_path,
1925 int pty_fd) {
1926
1927 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
1928 int r;
1929
1930 assert(bus);
1931 assert(message);
1932 assert(service);
1933
1934 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
1935 if (r < 0)
1936 return bus_log_create_error(r);
1937
1938 /* Name and mode */
1939 r = sd_bus_message_append(m, "ss", service, job_mode_to_string(arg_job_mode));
1940 if (r < 0)
1941 return bus_log_create_error(r);
1942
1943 /* Properties */
1944 r = sd_bus_message_open_container(m, 'a', "(sv)");
1945 if (r < 0)
1946 return bus_log_create_error(r);
1947
1948 r = transient_service_set_properties(m, pty_path, pty_fd);
1949 if (r < 0)
1950 return r;
1951
1952 r = sd_bus_message_close_container(m);
1953 if (r < 0)
1954 return bus_log_create_error(r);
1955
1956 /* Auxiliary units */
1957 r = sd_bus_message_append(m, "a(sa(sv))", 0);
1958 if (r < 0)
1959 return bus_log_create_error(r);
1960
1961 *message = TAKE_PTR(m);
1962 return 0;
1963 }
1964
1965 static int bus_call_with_hint(
1966 sd_bus *bus,
1967 sd_bus_message *message,
1968 const char *name,
1969 sd_bus_message **reply) {
1970
1971 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1972 int r;
1973
1974 r = sd_bus_call(bus, message, 0, &error, reply);
1975 if (r < 0) {
1976 log_error_errno(r, "Failed to start transient %s unit: %s", name, bus_error_message(&error, r));
1977
1978 if (!arg_expand_environment &&
1979 sd_bus_error_has_names(&error,
1980 SD_BUS_ERROR_UNKNOWN_PROPERTY,
1981 SD_BUS_ERROR_PROPERTY_READ_ONLY))
1982 log_notice_errno(r, "Hint: --expand-environment=no is not supported by old systemd");
1983 }
1984
1985 return r;
1986 }
1987
1988 static int acquire_invocation_id(sd_bus *bus, const char *unit, sd_id128_t *ret) {
1989 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1990 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1991 _cleanup_free_ char *object = NULL;
1992 int r;
1993
1994 assert(bus);
1995 assert(ret);
1996
1997 if (unit) {
1998 object = unit_dbus_path_from_name(unit);
1999 if (!object)
2000 return log_oom();
2001 }
2002
2003 r = sd_bus_get_property(bus,
2004 "org.freedesktop.systemd1",
2005 object ?: "/org/freedesktop/systemd1/unit/self",
2006 "org.freedesktop.systemd1.Unit",
2007 "InvocationID",
2008 &error,
2009 &reply,
2010 "ay");
2011 if (r < 0) {
2012 /* Let's ignore connection errors. This might be caused by that the service manager is being
2013 * restarted. Handle this gracefully. */
2014 if (bus_error_is_connection(&error) || bus_error_is_unknown_service(&error)) {
2015 log_debug_errno(r, "Invocation ID request failed due to bus connection problems, ignoring: %s",
2016 bus_error_message(&error, r));
2017 *ret = SD_ID128_NULL;
2018 return 0;
2019 }
2020
2021 return log_error_errno(r, "Failed to request invocation ID for unit: %s", bus_error_message(&error, r));
2022 }
2023
2024 r = bus_message_read_id128(reply, ret);
2025 if (r < 0)
2026 return bus_log_parse_error(r);
2027
2028 return r; /* Return true when we get a non-null invocation ID. */
2029 }
2030
2031 static int fchown_to_capsule(int fd, const char *capsule) {
2032 _cleanup_free_ char *p = NULL;
2033 int r;
2034
2035 assert(fd >= 0);
2036 assert(capsule);
2037
2038 p = path_join("/run/capsules/", capsule);
2039 if (!p)
2040 return -ENOMEM;
2041
2042 struct stat st;
2043 r = chase_and_stat(p, /* root= */ NULL, CHASE_SAFE|CHASE_PROHIBIT_SYMLINKS, /* ret_path= */ NULL, &st);
2044 if (r < 0)
2045 return r;
2046
2047 return fchmod_and_chown(fd, 0600, st.st_uid, st.st_gid);
2048 }
2049
2050 static int print_unit_invocation(const char *unit, sd_id128_t invocation_id) {
2051 _cleanup_(sd_json_variant_unrefp) sd_json_variant *v = NULL;
2052 int r;
2053
2054 assert(unit);
2055
2056 if (!sd_json_format_enabled(arg_json_format_flags)) {
2057 if (sd_id128_is_null(invocation_id))
2058 log_info("Running as unit: %s", unit);
2059 else
2060 log_info("Running as unit: %s; invocation ID: " SD_ID128_FORMAT_STR, unit, SD_ID128_FORMAT_VAL(invocation_id));
2061 return 0;
2062 }
2063
2064 r = sd_json_variant_set_field_string(&v, "unit", unit);
2065 if (r < 0)
2066 return r;
2067
2068 if (!sd_id128_is_null(invocation_id)) {
2069 r = sd_json_variant_set_field_id128(&v, "invocation_id", invocation_id);
2070 if (r < 0)
2071 return r;
2072 }
2073
2074 return sd_json_variant_dump(v, arg_json_format_flags, stdout, NULL);
2075 }
2076
2077 static int run_context_setup_ptyfwd(RunContext *c) {
2078 int r;
2079
2080 assert(c);
2081
2082 if (c->pty_fd < 0 || c->forward)
2083 return 0;
2084
2085 /* Stop agents now that we are online, to avoid TTY conflicts */
2086 polkit_agent_close();
2087 ask_password_agent_close();
2088
2089 if (!arg_quiet)
2090 log_info("Press ^] three times within 1s to disconnect TTY.");
2091
2092 r = pty_forward_new(c->event, c->pty_fd, PTY_FORWARD_IGNORE_INITIAL_VHANGUP, &c->forward);
2093 if (r < 0)
2094 return log_error_errno(r, "Failed to create PTY forwarder: %m");
2095
2096 pty_forward_set_hangup_handler(c->forward, pty_forward_handler, c);
2097
2098 /* Make sure to process any TTY events before we process bus events */
2099 (void) pty_forward_set_priority(c->forward, SD_EVENT_PRIORITY_IMPORTANT);
2100
2101 if (!isempty(arg_background))
2102 (void) pty_forward_set_background_color(c->forward, arg_background);
2103
2104 (void) pty_forward_set_window_title(c->forward, pty_window_glyph(), arg_host, arg_cmdline);
2105 return 0;
2106 }
2107
2108 static int run_context_show_result(RunContext *c) {
2109 int r;
2110
2111 assert(c);
2112
2113 _cleanup_(table_unrefp) Table *t = table_new_vertical();
2114 if (!t)
2115 return log_oom();
2116
2117 if (!isempty(c->result)) {
2118 r = table_add_many(
2119 t,
2120 TABLE_FIELD, "Finished with result",
2121 TABLE_STRING, c->result,
2122 TABLE_SET_COLOR, streq(c->result, "success") ? ansi_highlight_green() : ansi_highlight_red());
2123 if (r < 0)
2124 return table_log_add_error(r);
2125 }
2126
2127 if (c->exit_code > 0) {
2128 r = table_add_cell(
2129 t,
2130 /* ret_cell= */ NULL,
2131 TABLE_FIELD,
2132 "Main processes terminated with");
2133 if (r < 0)
2134 return table_log_add_error(r);
2135
2136 r = table_add_cell_stringf(
2137 t,
2138 /* ret_cell= */ NULL,
2139 "code=%s, status=%u/%s",
2140 sigchld_code_to_string(c->exit_code),
2141 c->exit_status,
2142 strna(c->exit_code == CLD_EXITED ?
2143 exit_status_to_string(c->exit_status, EXIT_STATUS_FULL) :
2144 signal_to_string(c->exit_status)));
2145 if (r < 0)
2146 return table_log_add_error(r);
2147 }
2148
2149 if (timestamp_is_set(c->inactive_enter_usec) &&
2150 timestamp_is_set(c->inactive_exit_usec) &&
2151 c->inactive_enter_usec > c->inactive_exit_usec) {
2152 r = table_add_many(
2153 t,
2154 TABLE_FIELD, "Service runtime",
2155 TABLE_TIMESPAN_MSEC, c->inactive_enter_usec - c->inactive_exit_usec);
2156 if (r < 0)
2157 return table_log_add_error(r);
2158 }
2159
2160 if (c->cpu_usage_nsec != NSEC_INFINITY) {
2161 r = table_add_many(
2162 t,
2163 TABLE_FIELD, "CPU time consumed",
2164 TABLE_TIMESPAN_MSEC, DIV_ROUND_UP(c->cpu_usage_nsec, NSEC_PER_USEC));
2165 if (r < 0)
2166 return table_log_add_error(r);
2167 }
2168
2169 if (c->memory_peak != UINT64_MAX) {
2170 const char *swap;
2171
2172 if (c->memory_swap_peak != UINT64_MAX)
2173 swap = strjoina(" (swap: ", FORMAT_BYTES(c->memory_swap_peak), ")");
2174 else
2175 swap = "";
2176
2177 r = table_add_cell(
2178 t,
2179 /* ret_cell= */ NULL,
2180 TABLE_FIELD, "Memory peak");
2181 if (r < 0)
2182 return table_log_add_error(r);
2183
2184 r = table_add_cell_stringf(
2185 t,
2186 /* ret_cell= */ NULL,
2187 "%s%s",
2188 FORMAT_BYTES(c->memory_peak), swap);
2189 if (r < 0)
2190 return table_log_add_error(r);
2191 }
2192
2193 const char *ip_ingress = NULL, *ip_egress = NULL;
2194 if (!IN_SET(c->ip_ingress_bytes, 0, UINT64_MAX))
2195 ip_ingress = strjoina("received ", FORMAT_BYTES(c->ip_ingress_bytes));
2196 if (!IN_SET(c->ip_egress_bytes, 0, UINT64_MAX))
2197 ip_egress = strjoina("sent ", FORMAT_BYTES(c->ip_egress_bytes));
2198
2199 if (ip_ingress || ip_egress) {
2200 r = table_add_cell(
2201 t,
2202 /* ret_cell= */ NULL,
2203 TABLE_FIELD, "IP Traffic");
2204 if (r < 0)
2205 return table_log_add_error(r);
2206
2207 r = table_add_cell_stringf(
2208 t,
2209 /* ret_cell= */ NULL,
2210 "%s%s%s", strempty(ip_ingress), ip_ingress && ip_egress ? ", " : "", strempty(ip_egress));
2211 if (r < 0)
2212 return table_log_add_error(r);
2213 }
2214
2215 const char *io_read = NULL, *io_write = NULL;
2216 if (!IN_SET(c->io_read_bytes, 0, UINT64_MAX))
2217 io_read = strjoina("read ", FORMAT_BYTES(c->io_read_bytes));
2218 if (!IN_SET(c->io_write_bytes, 0, UINT64_MAX))
2219 io_write = strjoina("written ", FORMAT_BYTES(c->io_write_bytes));
2220
2221 if (io_read || io_write) {
2222 r = table_add_cell(
2223 t,
2224 /* ret_cell= */ NULL,
2225 TABLE_FIELD, "IO Bytes");
2226 if (r < 0)
2227 return table_log_add_error(r);
2228
2229 r = table_add_cell_stringf(
2230 t,
2231 /* ret_cell= */ NULL,
2232 "%s%s%s", strempty(io_read), io_read && io_write ? ", " : "", strempty(io_write));
2233 if (r < 0)
2234 return table_log_add_error(r);
2235 }
2236
2237 r = table_print_full(t, stderr, /* flush= */ true);
2238 if (r < 0)
2239 return table_log_print_error(r);
2240
2241 return 0;
2242 }
2243
2244 static int start_transient_service(sd_bus *bus) {
2245 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
2246 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2247 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
2248 _cleanup_free_ char *pty_path = NULL;
2249 _cleanup_close_ int peer_fd = -EBADF;
2250 int r;
2251
2252 assert(bus);
2253
2254 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2255 (void) ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
2256
2257 _cleanup_(run_context_done) RunContext c = {
2258 .pty_fd = -EBADF,
2259 .cpu_usage_nsec = NSEC_INFINITY,
2260 .memory_peak = UINT64_MAX,
2261 .memory_swap_peak = UINT64_MAX,
2262 .ip_ingress_bytes = UINT64_MAX,
2263 .ip_egress_bytes = UINT64_MAX,
2264 .io_read_bytes = UINT64_MAX,
2265 .io_write_bytes = UINT64_MAX,
2266 .inactive_exit_usec = USEC_INFINITY,
2267 .inactive_enter_usec = USEC_INFINITY,
2268 };
2269
2270 if (arg_stdio == ARG_STDIO_PTY) {
2271
2272 if (IN_SET(arg_transport, BUS_TRANSPORT_LOCAL, BUS_TRANSPORT_CAPSULE)) {
2273 c.pty_fd = openpt_allocate(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK, &pty_path);
2274 if (c.pty_fd < 0)
2275 return log_error_errno(c.pty_fd, "Failed to acquire pseudo tty: %m");
2276
2277 peer_fd = pty_open_peer(c.pty_fd, O_RDWR|O_NOCTTY|O_CLOEXEC);
2278 if (peer_fd < 0)
2279 return log_error_errno(peer_fd, "Failed to open pty peer: %m");
2280
2281 if (arg_transport == BUS_TRANSPORT_CAPSULE) {
2282 /* If we are in capsule mode, we must give the capsule UID/GID access to the PTY we just allocated first. */
2283
2284 r = fchown_to_capsule(peer_fd, arg_host);
2285 if (r < 0)
2286 return log_error_errno(r, "Failed to chown tty to capsule UID/GID: %m");
2287 }
2288
2289 } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
2290 _cleanup_(sd_bus_unrefp) sd_bus *system_bus = NULL;
2291 _cleanup_(sd_bus_message_unrefp) sd_bus_message *pty_reply = NULL;
2292 const char *s;
2293
2294 r = sd_bus_default_system(&system_bus);
2295 if (r < 0)
2296 return log_error_errno(r, "Failed to connect to system bus: %m");
2297
2298 (void) sd_bus_set_allow_interactive_authorization(system_bus, arg_ask_password);
2299
2300 /* Chop off a username prefix. We allow this for sd-bus machine connections, hence
2301 * support that here too. */
2302 _cleanup_free_ char *h = NULL;
2303 r = split_user_at_host(arg_host, /* ret_user= */ NULL, &h);
2304 if (r < 0)
2305 return log_error_errno(r, "Failed to split host specification '%s': %m", arg_host);
2306
2307 r = bus_call_method(
2308 system_bus,
2309 bus_machine_mgr,
2310 "OpenMachinePTY",
2311 &error,
2312 &pty_reply,
2313 "s", h ?: ".host");
2314 if (r < 0)
2315 return log_error_errno(r, "Failed to get machine PTY: %s", bus_error_message(&error, r));
2316
2317 r = sd_bus_message_read(pty_reply, "hs", &c.pty_fd, &s);
2318 if (r < 0)
2319 return bus_log_parse_error(r);
2320
2321 c.pty_fd = fcntl(c.pty_fd, F_DUPFD_CLOEXEC, 3);
2322 if (c.pty_fd < 0)
2323 return log_error_errno(errno, "Failed to duplicate master fd: %m");
2324
2325 pty_path = strdup(s);
2326 if (!pty_path)
2327 return log_oom();
2328
2329 peer_fd = pty_open_peer(c.pty_fd, O_RDWR|O_NOCTTY|O_CLOEXEC);
2330 if (peer_fd < 0)
2331 return log_error_errno(peer_fd, "Failed to open PTY peer: %m");
2332 } else
2333 assert_not_reached();
2334 }
2335
2336 if (arg_unit) {
2337 r = unit_name_mangle_with_suffix(
2338 arg_unit,
2339 "as unit",
2340 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
2341 ".service",
2342 &c.unit);
2343 if (r < 0)
2344 return log_error_errno(r, "Failed to mangle unit name: %m");
2345 } else {
2346 r = make_unit_name(UNIT_SERVICE, &c.unit);
2347 if (r < 0)
2348 return r;
2349 }
2350
2351 /* Optionally, wait for the start job to complete. If we are supposed to read the service's stdin
2352 * lets skip this however, because we should start that already when the start job is running, and
2353 * there's little point in waiting for the start job to complete in that case anyway, as we'll wait
2354 * for EOF anyway, which is going to be much later. Similar applies to --wait where we're going
2355 * to wait for the service to terminate. */
2356 if (!arg_no_block && !arg_wait && arg_stdio == ARG_STDIO_NONE) {
2357 r = bus_wait_for_jobs_new(bus, &w);
2358 if (r < 0)
2359 return log_error_errno(r, "Could not watch jobs: %m");
2360 }
2361
2362 r = make_transient_service_unit(bus, &m, c.unit, pty_path, peer_fd);
2363 if (r < 0)
2364 return r;
2365 peer_fd = safe_close(peer_fd);
2366
2367 _cleanup_(fork_notify_terminate) PidRef journal_pid = PIDREF_NULL;
2368 if (arg_verbose)
2369 (void) journal_fork(arg_runtime_scope, STRV_MAKE(c.unit), arg_output, &journal_pid);
2370
2371 r = bus_call_with_hint(bus, m, "service", &reply);
2372 if (r < 0)
2373 return r;
2374
2375 const char *object;
2376 r = sd_bus_message_read(reply, "o", &object);
2377 if (r < 0)
2378 return bus_log_parse_error(r);
2379
2380 if (w) {
2381 r = bus_wait_for_jobs_one(
2382 w,
2383 object,
2384 arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
2385 arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
2386 if (r < 0)
2387 return r;
2388 } else if (!arg_no_block) {
2389 c.start_job = strdup(object);
2390 if (!c.start_job)
2391 return log_oom();
2392 }
2393
2394 if (!arg_quiet) {
2395 sd_id128_t invocation_id;
2396
2397 r = acquire_invocation_id(bus, c.unit, &invocation_id);
2398 if (r < 0)
2399 return r;
2400
2401 r = print_unit_invocation(c.unit, invocation_id);
2402 if (r < 0)
2403 return r;
2404 }
2405
2406 if (arg_wait || arg_stdio != ARG_STDIO_NONE) {
2407 c.bus_path = unit_dbus_path_from_name(c.unit);
2408 if (!c.bus_path)
2409 return log_oom();
2410
2411 r = sd_event_default(&c.event);
2412 if (r < 0)
2413 return log_error_errno(r, "Failed to get event loop: %m");
2414
2415 _cleanup_(osc_context_closep) sd_id128_t osc_context_id = SD_ID128_NULL;
2416 if (c.pty_fd >= 0) {
2417 if (arg_exec_user && !terminal_is_dumb()) {
2418 r = osc_context_open_chpriv(arg_exec_user, /* ret_seq= */ NULL, &osc_context_id);
2419 if (r < 0)
2420 return log_error_errno(r, "Failed to set OSC context: %m");
2421 }
2422
2423 (void) sd_event_set_signal_exit(c.event, true);
2424
2425 assert(arg_pty_late >= 0);
2426 if (!arg_pty_late) { /* If late PTY mode is off, start pty forwarder immediately */
2427 r = run_context_setup_ptyfwd(&c);
2428 if (r < 0)
2429 return r;
2430 }
2431 }
2432
2433 r = run_context_attach_bus(&c, bus);
2434 if (r < 0)
2435 return r;
2436
2437 r = run_context_update(&c);
2438 if (r < 0)
2439 return r;
2440
2441 r = sd_event_loop(c.event);
2442 if (r < 0)
2443 return log_error_errno(r, "Failed to run event loop: %m");
2444
2445 /* Close the journal watch logic before we output the exit summary */
2446 fork_notify_terminate(&journal_pid);
2447
2448 if (arg_wait && !arg_quiet)
2449 run_context_show_result(&c);
2450
2451 /* Try to propagate the service's return value. But if the service defines
2452 * e.g. SuccessExitStatus, honour this, and return 0 to mean "success". */
2453 if (streq_ptr(c.result, "success"))
2454 return EXIT_SUCCESS;
2455 if (streq_ptr(c.result, "exit-code") && c.exit_status > 0)
2456 return c.exit_status;
2457 if (streq_ptr(c.result, "signal"))
2458 return EXIT_EXCEPTION;
2459 return EXIT_FAILURE;
2460 }
2461
2462 return EXIT_SUCCESS;
2463 }
2464
2465 static int start_transient_scope(sd_bus *bus) {
2466 _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
2467 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
2468 _cleanup_strv_free_ char **env = NULL, **user_env = NULL;
2469 _cleanup_free_ char *scope = NULL;
2470 const char *object = NULL;
2471 sd_id128_t invocation_id;
2472 bool allow_pidfd = true;
2473 int r;
2474
2475 assert(bus);
2476 assert(!strv_isempty(arg_cmdline));
2477
2478 r = bus_wait_for_jobs_new(bus, &w);
2479 if (r < 0)
2480 return log_error_errno(r, "Could not watch jobs: %m");
2481
2482 if (arg_unit) {
2483 r = unit_name_mangle_with_suffix(arg_unit, "as unit",
2484 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
2485 ".scope", &scope);
2486 if (r < 0)
2487 return log_error_errno(r, "Failed to mangle scope name: %m");
2488 } else {
2489 r = make_unit_name(UNIT_SCOPE, &scope);
2490 if (r < 0)
2491 return r;
2492 }
2493
2494 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2495 (void) ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
2496
2497 for (;;) {
2498 _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
2499 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2500
2501 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
2502 if (r < 0)
2503 return bus_log_create_error(r);
2504
2505 /* Name and Mode */
2506 r = sd_bus_message_append(m, "ss", scope, job_mode_to_string(arg_job_mode));
2507 if (r < 0)
2508 return bus_log_create_error(r);
2509
2510 /* Properties */
2511 r = sd_bus_message_open_container(m, 'a', "(sv)");
2512 if (r < 0)
2513 return bus_log_create_error(r);
2514
2515 r = transient_scope_set_properties(m, allow_pidfd);
2516 if (r < 0)
2517 return r;
2518
2519 r = sd_bus_message_close_container(m);
2520 if (r < 0)
2521 return bus_log_create_error(r);
2522
2523 /* Auxiliary units */
2524 r = sd_bus_message_append(m, "a(sa(sv))", 0);
2525 if (r < 0)
2526 return bus_log_create_error(r);
2527
2528 r = sd_bus_call(bus, m, 0, &error, &reply);
2529 if (r < 0) {
2530 if (sd_bus_error_has_names(&error, SD_BUS_ERROR_UNKNOWN_PROPERTY, SD_BUS_ERROR_PROPERTY_READ_ONLY) && allow_pidfd) {
2531 log_debug("Retrying with classic PIDs.");
2532 allow_pidfd = false;
2533 continue;
2534 }
2535
2536 return log_error_errno(r, "Failed to start transient scope unit: %s", bus_error_message(&error, r));
2537 }
2538
2539 break;
2540 }
2541
2542 r = sd_bus_message_read(reply, "o", &object);
2543 if (r < 0)
2544 return bus_log_parse_error(r);
2545
2546 r = bus_wait_for_jobs_one(w, object, arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
2547 arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
2548 if (r < 0)
2549 return r;
2550
2551 r = acquire_invocation_id(bus, NULL, &invocation_id);
2552 if (r < 0)
2553 return r;
2554 if (r == 0)
2555 log_debug("No invocation ID set.");
2556 else {
2557 if (strv_extendf(&user_env, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(invocation_id)) < 0)
2558 return log_oom();
2559 }
2560
2561 /* Stop agents before we pass control away and before we drop privileges, to avoid TTY conflicts and
2562 * before we become unable to stop agents. */
2563 polkit_agent_close();
2564 ask_password_agent_close();
2565
2566 if (arg_nice_set) {
2567 if (setpriority(PRIO_PROCESS, 0, arg_nice) < 0)
2568 return log_error_errno(errno, "Failed to set nice level: %m");
2569 }
2570
2571 if (arg_exec_group) {
2572 gid_t gid;
2573
2574 r = get_group_creds(arg_exec_group, /* flags= */ 0, /* ret_name= */ NULL, &gid);
2575 if (r < 0)
2576 return log_error_errno(r, "Failed to resolve group '%s': %s",
2577 arg_exec_group, STRERROR_GROUP(r));
2578
2579 if (setresgid(gid, gid, gid) < 0)
2580 return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
2581 }
2582
2583 if (arg_exec_user) {
2584 _cleanup_free_ char *user = NULL, *home = NULL, *shell = NULL;
2585 uid_t uid;
2586 gid_t gid;
2587
2588 r = get_user_creds(arg_exec_user,
2589 USER_CREDS_CLEAN|USER_CREDS_SUPPRESS_PLACEHOLDER|USER_CREDS_PREFER_NSS,
2590 &user, &uid, &gid, &home, &shell);
2591 if (r < 0)
2592 return log_error_errno(r, "Failed to resolve user '%s': %s",
2593 arg_exec_user, STRERROR_USER(r));
2594
2595 free_and_replace(arg_exec_user, user);
2596
2597 if (home) {
2598 r = strv_extendf(&user_env, "HOME=%s", home);
2599 if (r < 0)
2600 return log_oom();
2601 }
2602
2603 if (shell) {
2604 r = strv_extendf(&user_env, "SHELL=%s", shell);
2605 if (r < 0)
2606 return log_oom();
2607 }
2608
2609 r = strv_extendf(&user_env, "USER=%s", arg_exec_user);
2610 if (r < 0)
2611 return log_oom();
2612
2613 r = strv_extendf(&user_env, "LOGNAME=%s", arg_exec_user);
2614 if (r < 0)
2615 return log_oom();
2616
2617 if (!arg_exec_group &&
2618 setresgid(gid, gid, gid) < 0)
2619 return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
2620
2621 if (setresuid(uid, uid, uid) < 0)
2622 return log_error_errno(errno, "Failed to change UID to " UID_FMT ": %m", uid);
2623 }
2624
2625 if (arg_working_directory && chdir(arg_working_directory) < 0)
2626 return log_error_errno(errno, "Failed to change directory to '%s': %m", arg_working_directory);
2627
2628 env = strv_env_merge(environ, user_env, arg_environment);
2629 if (!env)
2630 return log_oom();
2631
2632 if (!arg_quiet) {
2633 r = print_unit_invocation(scope, invocation_id);
2634 if (r < 0)
2635 return r;
2636 }
2637
2638 if (arg_expand_environment) {
2639 _cleanup_strv_free_ char **expanded_cmdline = NULL, **unset_variables = NULL, **bad_variables = NULL;
2640
2641 r = replace_env_argv(arg_cmdline, env, &expanded_cmdline, &unset_variables, &bad_variables);
2642 if (r < 0)
2643 return log_error_errno(r, "Failed to expand environment variables: %m");
2644
2645 free_and_replace(arg_cmdline, expanded_cmdline);
2646
2647 if (!strv_isempty(unset_variables)) {
2648 _cleanup_free_ char *ju = strv_join(unset_variables, ", ");
2649 log_warning("Referenced but unset environment variable evaluates to an empty string: %s", strna(ju));
2650 }
2651
2652 if (!strv_isempty(bad_variables)) {
2653 _cleanup_free_ char *jb = strv_join(bad_variables, ", ");
2654 log_warning("Invalid environment variable name evaluates to an empty string: %s", strna(jb));
2655 }
2656 }
2657
2658 execvpe(arg_cmdline[0], arg_cmdline, env);
2659
2660 return log_error_errno(errno, "Failed to execute: %m");
2661 }
2662
2663 static int make_transient_trigger_unit(
2664 sd_bus *bus,
2665 sd_bus_message **message,
2666 const char *suffix,
2667 const char *trigger,
2668 const char *service) {
2669
2670 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL;
2671 int r;
2672
2673 assert(bus);
2674 assert(message);
2675 assert(suffix);
2676 assert(trigger);
2677 assert(service);
2678
2679 r = bus_message_new_method_call(bus, &m, bus_systemd_mgr, "StartTransientUnit");
2680 if (r < 0)
2681 return bus_log_create_error(r);
2682
2683 /* Name and Mode */
2684 r = sd_bus_message_append(m, "ss", trigger, job_mode_to_string(arg_job_mode));
2685 if (r < 0)
2686 return bus_log_create_error(r);
2687
2688 /* Properties */
2689 r = sd_bus_message_open_container(m, 'a', "(sv)");
2690 if (r < 0)
2691 return bus_log_create_error(r);
2692
2693 if (streq(suffix, ".path"))
2694 r = transient_unit_set_properties(m, UNIT_PATH, arg_path_property);
2695 else if (streq(suffix, ".socket"))
2696 r = transient_unit_set_properties(m, UNIT_SOCKET, arg_socket_property);
2697 else if (streq(suffix, ".timer"))
2698 r = transient_timer_set_properties(m);
2699 else
2700 assert_not_reached();
2701 if (r < 0)
2702 return r;
2703
2704 r = sd_bus_message_close_container(m);
2705 if (r < 0)
2706 return bus_log_create_error(r);
2707
2708 r = sd_bus_message_open_container(m, 'a', "(sa(sv))");
2709 if (r < 0)
2710 return bus_log_create_error(r);
2711
2712 if (!strv_isempty(arg_cmdline)) {
2713 r = sd_bus_message_open_container(m, 'r', "sa(sv)");
2714 if (r < 0)
2715 return bus_log_create_error(r);
2716
2717 r = sd_bus_message_append(m, "s", service);
2718 if (r < 0)
2719 return bus_log_create_error(r);
2720
2721 r = sd_bus_message_open_container(m, 'a', "(sv)");
2722 if (r < 0)
2723 return bus_log_create_error(r);
2724
2725 r = transient_service_set_properties(m, /* pty_path= */ NULL, /* pty_fd= */ -EBADF);
2726 if (r < 0)
2727 return r;
2728
2729 r = sd_bus_message_close_container(m);
2730 if (r < 0)
2731 return bus_log_create_error(r);
2732
2733 r = sd_bus_message_close_container(m);
2734 if (r < 0)
2735 return bus_log_create_error(r);
2736 }
2737
2738 r = sd_bus_message_close_container(m);
2739 if (r < 0)
2740 return bus_log_create_error(r);
2741
2742 *message = TAKE_PTR(m);
2743 return 0;
2744 }
2745
2746 static int start_transient_trigger(sd_bus *bus, const char *suffix) {
2747 _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
2748 _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
2749 _cleanup_free_ char *trigger = NULL, *service = NULL;
2750 const char *object = NULL;
2751 int r;
2752
2753 assert(bus);
2754 assert(suffix);
2755
2756 r = bus_wait_for_jobs_new(bus, &w);
2757 if (r < 0)
2758 return log_error_errno(r, "Could not watch jobs: %m");
2759
2760 if (arg_unit) {
2761 switch (unit_name_to_type(arg_unit)) {
2762
2763 case UNIT_SERVICE:
2764 service = strdup(arg_unit);
2765 if (!service)
2766 return log_oom();
2767
2768 r = unit_name_change_suffix(service, suffix, &trigger);
2769 if (r < 0)
2770 return log_error_errno(r, "Failed to change unit suffix: %m");
2771 break;
2772
2773 case UNIT_TIMER:
2774 trigger = strdup(arg_unit);
2775 if (!trigger)
2776 return log_oom();
2777
2778 r = unit_name_change_suffix(trigger, ".service", &service);
2779 if (r < 0)
2780 return log_error_errno(r, "Failed to change unit suffix: %m");
2781 break;
2782
2783 default:
2784 r = unit_name_mangle_with_suffix(arg_unit, "as unit",
2785 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
2786 ".service", &service);
2787 if (r < 0)
2788 return log_error_errno(r, "Failed to mangle unit name: %m");
2789
2790 r = unit_name_mangle_with_suffix(arg_unit, "as trigger",
2791 arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN,
2792 suffix, &trigger);
2793 if (r < 0)
2794 return log_error_errno(r, "Failed to mangle unit name: %m");
2795
2796 break;
2797 }
2798 } else {
2799 r = make_unit_name(UNIT_SERVICE, &service);
2800 if (r < 0)
2801 return r;
2802
2803 r = unit_name_change_suffix(service, suffix, &trigger);
2804 if (r < 0)
2805 return log_error_errno(r, "Failed to change unit suffix: %m");
2806 }
2807
2808 r = make_transient_trigger_unit(bus, &m, suffix, trigger, service);
2809 if (r < 0)
2810 return r;
2811
2812 (void) polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
2813 (void) ask_password_agent_open_if_enabled(arg_transport, arg_ask_password);
2814
2815 r = bus_call_with_hint(bus, m, suffix + 1, &reply);
2816 if (r < 0)
2817 return r;
2818
2819 r = sd_bus_message_read(reply, "o", &object);
2820 if (r < 0)
2821 return bus_log_parse_error(r);
2822
2823 r = bus_wait_for_jobs_one(w, object, arg_quiet ? 0 : BUS_WAIT_JOBS_LOG_ERROR,
2824 arg_runtime_scope == RUNTIME_SCOPE_USER ? STRV_MAKE_CONST("--user") : NULL);
2825 if (r < 0)
2826 return r;
2827
2828 if (!arg_quiet) {
2829 log_info("Running %s as unit: %s", suffix + 1, trigger);
2830 if (!strv_isempty(arg_cmdline))
2831 log_info("Will run service as unit: %s", service);
2832 }
2833
2834 return EXIT_SUCCESS;
2835 }
2836
2837 static bool shall_make_executable_absolute(void) {
2838 if (arg_exec_path)
2839 return false;
2840 if (strv_isempty(arg_cmdline))
2841 return false;
2842 if (arg_transport != BUS_TRANSPORT_LOCAL)
2843 return false;
2844 if (!empty_or_root(arg_root_directory))
2845 return false;
2846 /* If we're running in a chroot, our view of the filesystem might be completely different from pid1's
2847 * view of the filesystem, hence don't try to resolve the executable in that case. */
2848 if (!arg_root_directory && running_in_chroot() > 0)
2849 return false;
2850
2851 FOREACH_STRING(f, "RootDirectory=", "RootImage=", "RootMStack=", "ExecSearchPath=", "MountImages=", "ExtensionImages=")
2852 if (strv_find_startswith(arg_property, f))
2853 return false;
2854
2855 return true;
2856 }
2857
2858 static int run(int argc, char* argv[]) {
2859 _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
2860 int r;
2861
2862 log_setup();
2863
2864 if (invoked_as(argv, "run0"))
2865 r = parse_argv_sudo_mode(argc, argv);
2866 else
2867 r = parse_argv(argc, argv);
2868 if (r <= 0)
2869 return r;
2870
2871 if (shall_make_executable_absolute()) {
2872 /* Patch in an absolute path to fail early for user convenience, but only when we can do it
2873 * (i.e. we will be running from the same file system). This also uses the user's $PATH,
2874 * while we use a fixed search path in the manager. */
2875
2876 _cleanup_free_ char *command = NULL;
2877 r = find_executable(arg_cmdline[0], &command);
2878 if (ERRNO_IS_NEG_PRIVILEGE(r))
2879 log_debug_errno(r, "Failed to find executable '%s' due to permission problems, leaving path as is: %m", arg_cmdline[0]);
2880 else if (r < 0)
2881 return log_error_errno(r, "Failed to find executable %s: %m", arg_cmdline[0]);
2882 else
2883 free_and_replace(arg_cmdline[0], command);
2884 }
2885
2886 if (!arg_description) {
2887 _cleanup_free_ char *t = NULL;
2888
2889 if (strv_isempty(arg_cmdline))
2890 t = strdup(arg_unit);
2891 else if (arg_via_shell) {
2892 if (arg_cmdline[1])
2893 t = quote_command_line(arg_cmdline + 1, SHELL_ESCAPE_EMPTY);
2894 else
2895 t = strjoin("LOGIN", arg_exec_user ? ": " : NULL, arg_exec_user);
2896 } else if (startswith(arg_cmdline[0], "-")) {
2897 /* Drop the login shell marker from the command line when generating the description,
2898 * in order to minimize user confusion. */
2899 _cleanup_strv_free_ char **l = strv_copy(arg_cmdline);
2900 if (!l)
2901 return log_oom();
2902
2903 r = free_and_strdup_warn(l + 0, l[0] + 1);
2904 if (r < 0)
2905 return r;
2906
2907 t = quote_command_line(l, SHELL_ESCAPE_EMPTY);
2908 } else
2909 t = quote_command_line(arg_cmdline, SHELL_ESCAPE_EMPTY);
2910 if (!t)
2911 return log_oom();
2912
2913 arg_description = strjoin("[", program_invocation_short_name, "] ", t);
2914 if (!arg_description)
2915 return log_oom();
2916 }
2917
2918 r = connect_bus(&bus);
2919 if (r < 0)
2920 return r;
2921
2922 if (arg_scope)
2923 return start_transient_scope(bus);
2924 if (arg_path_property)
2925 return start_transient_trigger(bus, ".path");
2926 if (arg_socket_property)
2927 return start_transient_trigger(bus, ".socket");
2928 if (arg_with_timer)
2929 return start_transient_trigger(bus, ".timer");
2930 return start_transient_service(bus);
2931 }
2932
2933 DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);