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