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