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