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