Line data Source code
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 4 : STATIC_DESTRUCTOR_REGISTER(arg_environment, strv_freep);
71 4 : STATIC_DESTRUCTOR_REGISTER(arg_property, strv_freep);
72 4 : STATIC_DESTRUCTOR_REGISTER(arg_path_property, strv_freep);
73 4 : STATIC_DESTRUCTOR_REGISTER(arg_socket_property, strv_freep);
74 4 : STATIC_DESTRUCTOR_REGISTER(arg_timer_property, strv_freep);
75 4 : STATIC_DESTRUCTOR_REGISTER(arg_working_directory, freep);
76 4 : STATIC_DESTRUCTOR_REGISTER(arg_cmdline, strv_freep);
77 :
78 3 : static int help(void) {
79 3 : _cleanup_free_ char *link = NULL;
80 : int r;
81 :
82 3 : r = terminal_urlify_man("systemd-run", "1", &link);
83 3 : if (r < 0)
84 0 : return log_oom();
85 :
86 3 : 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 3 : return 0;
136 : }
137 :
138 0 : static int add_timer_property(const char *name, const char *val) {
139 : char *p;
140 :
141 0 : assert(name);
142 0 : assert(val);
143 :
144 0 : p = strjoin(name, "=", val);
145 0 : if (!p)
146 0 : return log_oom();
147 :
148 0 : if (strv_consume(&arg_timer_property, p) < 0)
149 0 : return log_oom();
150 :
151 0 : return 0;
152 : }
153 :
154 4 : 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 4 : bool with_trigger = false;
232 : int r, c;
233 :
234 4 : assert(argc >= 0);
235 4 : assert(argv);
236 :
237 4 : while ((c = getopt_long(argc, argv, "+hrH:M:E:p:tPqGdS", options, NULL)) >= 0)
238 :
239 4 : switch (c) {
240 :
241 3 : case 'h':
242 3 : return help();
243 :
244 0 : case ARG_VERSION:
245 0 : return version();
246 :
247 0 : case ARG_NO_ASK_PASSWORD:
248 0 : arg_ask_password = false;
249 0 : break;
250 :
251 0 : case ARG_USER:
252 0 : arg_user = true;
253 0 : break;
254 :
255 0 : case ARG_SYSTEM:
256 0 : arg_user = false;
257 0 : break;
258 :
259 0 : case ARG_SCOPE:
260 0 : arg_scope = true;
261 0 : break;
262 :
263 0 : case ARG_UNIT:
264 0 : arg_unit = optarg;
265 0 : break;
266 :
267 0 : case ARG_DESCRIPTION:
268 0 : arg_description = optarg;
269 0 : break;
270 :
271 0 : case ARG_SLICE:
272 0 : arg_slice = optarg;
273 0 : break;
274 :
275 0 : case ARG_SEND_SIGHUP:
276 0 : arg_send_sighup = true;
277 0 : break;
278 :
279 0 : case 'r':
280 0 : arg_remain_after_exit = true;
281 0 : break;
282 :
283 0 : case 'H':
284 0 : arg_transport = BUS_TRANSPORT_REMOTE;
285 0 : arg_host = optarg;
286 0 : break;
287 :
288 0 : case 'M':
289 0 : arg_transport = BUS_TRANSPORT_MACHINE;
290 0 : arg_host = optarg;
291 0 : break;
292 :
293 0 : case ARG_SERVICE_TYPE:
294 0 : arg_service_type = optarg;
295 0 : break;
296 :
297 0 : case ARG_EXEC_USER:
298 0 : arg_exec_user = optarg;
299 0 : break;
300 :
301 0 : case ARG_EXEC_GROUP:
302 0 : arg_exec_group = optarg;
303 0 : break;
304 :
305 0 : case ARG_NICE:
306 0 : r = parse_nice(optarg, &arg_nice);
307 0 : if (r < 0)
308 0 : return log_error_errno(r, "Failed to parse nice value: %s", optarg);
309 :
310 0 : arg_nice_set = true;
311 0 : break;
312 :
313 0 : case 'E':
314 0 : if (strv_extend(&arg_environment, optarg) < 0)
315 0 : return log_oom();
316 :
317 0 : break;
318 :
319 0 : case 'p':
320 0 : if (strv_extend(&arg_property, optarg) < 0)
321 0 : return log_oom();
322 :
323 0 : break;
324 :
325 0 : case 't': /* --pty */
326 0 : if (IN_SET(arg_stdio, ARG_STDIO_DIRECT, ARG_STDIO_AUTO)) /* if --pipe is already used, upgrade to auto mode */
327 0 : arg_stdio = ARG_STDIO_AUTO;
328 : else
329 0 : arg_stdio = ARG_STDIO_PTY;
330 0 : break;
331 :
332 0 : case 'P': /* --pipe */
333 0 : if (IN_SET(arg_stdio, ARG_STDIO_PTY, ARG_STDIO_AUTO)) /* If --pty is already used, upgrade to auto mode */
334 0 : arg_stdio = ARG_STDIO_AUTO;
335 : else
336 0 : arg_stdio = ARG_STDIO_DIRECT;
337 0 : break;
338 :
339 0 : case 'q':
340 0 : arg_quiet = true;
341 0 : break;
342 :
343 0 : case ARG_ON_ACTIVE:
344 0 : r = add_timer_property("OnActiveSec", optarg);
345 0 : if (r < 0)
346 0 : return r;
347 :
348 0 : arg_with_timer = true;
349 0 : break;
350 :
351 0 : case ARG_ON_BOOT:
352 0 : r = add_timer_property("OnBootSec", optarg);
353 0 : if (r < 0)
354 0 : return r;
355 :
356 0 : arg_with_timer = true;
357 0 : break;
358 :
359 0 : case ARG_ON_STARTUP:
360 0 : r = add_timer_property("OnStartupSec", optarg);
361 0 : if (r < 0)
362 0 : return r;
363 :
364 0 : arg_with_timer = true;
365 0 : break;
366 :
367 0 : case ARG_ON_UNIT_ACTIVE:
368 0 : r = add_timer_property("OnUnitActiveSec", optarg);
369 0 : if (r < 0)
370 0 : return r;
371 :
372 0 : arg_with_timer = true;
373 0 : break;
374 :
375 0 : case ARG_ON_UNIT_INACTIVE:
376 0 : r = add_timer_property("OnUnitInactiveSec", optarg);
377 0 : if (r < 0)
378 0 : return r;
379 :
380 0 : arg_with_timer = true;
381 0 : break;
382 :
383 0 : case ARG_ON_CALENDAR: {
384 0 : _cleanup_(calendar_spec_freep) CalendarSpec *cs = NULL;
385 :
386 0 : r = calendar_spec_from_string(optarg, &cs);
387 0 : if (r < 0)
388 0 : return log_error_errno(r, "Failed to parse calendar event specification: %m");
389 :
390 : /* Let's make sure the given calendar event is not in the past */
391 0 : r = calendar_spec_next_usec(cs, now(CLOCK_REALTIME), NULL);
392 0 : if (r == -ENOENT)
393 : /* The calendar event is in the past — let's warn about this, but install it
394 : * anyway as is. The service manager will trigger the service right away.
395 : * Moreover, the server side might have a different clock or timezone than we
396 : * do, hence it should decide when or whether to run something. */
397 0 : log_warning("Specified calendar expression is in the past, proceeding anyway.");
398 0 : else if (r < 0)
399 0 : return log_error_errno(r, "Failed to calculate next time calendar expression elapses: %m");
400 :
401 0 : r = add_timer_property("OnCalendar", optarg);
402 0 : if (r < 0)
403 0 : return r;
404 :
405 0 : arg_with_timer = true;
406 0 : break;
407 : }
408 :
409 0 : case ARG_ON_TIMEZONE_CHANGE:
410 0 : r = add_timer_property("OnTimezoneChange", "yes");
411 0 : if (r < 0)
412 0 : return r;
413 :
414 0 : arg_with_timer = true;
415 0 : break;
416 :
417 0 : case ARG_ON_CLOCK_CHANGE:
418 0 : r = add_timer_property("OnClockChange", "yes");
419 0 : if (r < 0)
420 0 : return r;
421 :
422 0 : arg_with_timer = true;
423 0 : break;
424 :
425 0 : case ARG_TIMER_PROPERTY:
426 :
427 0 : if (strv_extend(&arg_timer_property, optarg) < 0)
428 0 : return log_oom();
429 :
430 0 : arg_with_timer = arg_with_timer ||
431 0 : STARTSWITH_SET(optarg,
432 : "OnActiveSec=",
433 : "OnBootSec=",
434 : "OnStartupSec=",
435 : "OnUnitActiveSec=",
436 : "OnUnitInactiveSec=",
437 : "OnCalendar=");
438 0 : break;
439 :
440 0 : case ARG_PATH_PROPERTY:
441 :
442 0 : if (strv_extend(&arg_path_property, optarg) < 0)
443 0 : return log_oom();
444 :
445 0 : break;
446 :
447 0 : case ARG_SOCKET_PROPERTY:
448 :
449 0 : if (strv_extend(&arg_socket_property, optarg) < 0)
450 0 : return log_oom();
451 :
452 0 : break;
453 :
454 0 : case ARG_NO_BLOCK:
455 0 : arg_no_block = true;
456 0 : break;
457 :
458 0 : case ARG_WAIT:
459 0 : arg_wait = true;
460 0 : break;
461 :
462 0 : case ARG_WORKING_DIRECTORY:
463 0 : r = parse_path_argument_and_warn(optarg, true, &arg_working_directory);
464 0 : if (r < 0)
465 0 : return r;
466 :
467 0 : break;
468 :
469 0 : case 'd': {
470 0 : _cleanup_free_ char *p = NULL;
471 :
472 0 : r = safe_getcwd(&p);
473 0 : if (r < 0)
474 0 : return log_error_errno(r, "Failed to get current working directory: %m");
475 :
476 0 : if (empty_or_root(p))
477 0 : arg_working_directory = mfree(arg_working_directory);
478 : else
479 0 : free_and_replace(arg_working_directory, p);
480 0 : break;
481 : }
482 :
483 0 : case 'G':
484 0 : arg_aggressive_gc = true;
485 0 : break;
486 :
487 0 : case 'S':
488 0 : arg_shell = true;
489 0 : break;
490 :
491 1 : case '?':
492 1 : return -EINVAL;
493 :
494 0 : default:
495 0 : assert_not_reached("Unhandled option");
496 : }
497 :
498 0 : 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 0 : if ((int) !!arg_path_property + (int) !!arg_socket_property + (int) arg_with_timer > 1)
502 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
503 : "Only single trigger (path, socket, timer) unit can be created.");
504 :
505 0 : if (arg_shell) {
506 : /* If --shell is imply --pty --pipe --same-dir --service-type=exec --wait --collect, unless otherwise
507 : * specified. */
508 :
509 0 : if (!arg_scope) {
510 0 : if (arg_stdio == ARG_STDIO_NONE)
511 0 : arg_stdio = ARG_STDIO_AUTO;
512 :
513 0 : if (!arg_working_directory) {
514 0 : r = safe_getcwd(&arg_working_directory);
515 0 : if (r < 0)
516 0 : return log_error_errno(r, "Failed to get current working directory: %m");
517 : }
518 :
519 0 : if (!arg_service_type) {
520 0 : arg_service_type = strdup("exec");
521 0 : if (!arg_service_type)
522 0 : return log_oom();
523 : }
524 :
525 0 : arg_wait = true;
526 : }
527 :
528 0 : arg_aggressive_gc = true;
529 : }
530 :
531 0 : 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 0 : arg_stdio = isatty(STDIN_FILENO) && isatty(STDOUT_FILENO) && isatty(STDERR_FILENO) ?
536 0 : ARG_STDIO_PTY :
537 : ARG_STDIO_DIRECT;
538 : }
539 :
540 0 : if (argc > optind) {
541 : char **l;
542 :
543 0 : if (arg_shell)
544 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "If --shell is used, no command line is expected.");
545 :
546 0 : l = strv_copy(argv + optind);
547 0 : if (!l)
548 0 : return log_oom();
549 :
550 0 : strv_free_and_replace(arg_cmdline, l);
551 :
552 0 : } else if (arg_shell) {
553 0 : _cleanup_free_ char *s = NULL;
554 : char **l;
555 :
556 0 : r = get_shell(&s);
557 0 : if (r < 0)
558 0 : return log_error_errno(r, "Failed to determine shell: %m");
559 :
560 0 : l = strv_new(s);
561 0 : if (!l)
562 0 : return log_oom();
563 :
564 0 : strv_free_and_replace(arg_cmdline, l);
565 :
566 0 : } else if (!arg_unit || !with_trigger)
567 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Command line to execute required.");
568 :
569 0 : if (arg_user && arg_transport != BUS_TRANSPORT_LOCAL)
570 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
571 : "Execution in user context is not supported on non-local systems.");
572 :
573 0 : if (arg_scope && arg_transport != BUS_TRANSPORT_LOCAL)
574 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
575 : "Scope execution is not supported on non-local systems.");
576 :
577 0 : if (arg_scope && (arg_remain_after_exit || arg_service_type))
578 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
579 : "--remain-after-exit and --service-type= are not supported in --scope mode.");
580 :
581 0 : if (arg_stdio != ARG_STDIO_NONE && (with_trigger || arg_scope))
582 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
583 : "--pty/--pipe is not compatible in timer or --scope mode.");
584 :
585 0 : if (arg_stdio != ARG_STDIO_NONE && arg_transport == BUS_TRANSPORT_REMOTE)
586 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
587 : "--pty/--pipe is only supported when connecting to the local system or containers.");
588 :
589 0 : if (arg_stdio != ARG_STDIO_NONE && arg_no_block)
590 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
591 : "--pty/--pipe is not compatible with --no-block.");
592 :
593 0 : if (arg_scope && with_trigger)
594 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
595 : "Path, socket or timer options are not supported in --scope mode.");
596 :
597 0 : if (arg_timer_property && !arg_with_timer)
598 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
599 : "--timer-property= has no effect without any other timer options.");
600 :
601 0 : if (arg_wait) {
602 0 : if (arg_no_block)
603 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
604 : "--wait may not be combined with --no-block.");
605 :
606 0 : if (with_trigger)
607 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
608 : "--wait may not be combined with path, socket or timer operations.");
609 :
610 0 : if (arg_scope)
611 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
612 : "--wait may not be combined with --scope.");
613 : }
614 :
615 0 : return 1;
616 : }
617 :
618 0 : static int transient_unit_set_properties(sd_bus_message *m, UnitType t, char **properties) {
619 : int r;
620 :
621 0 : r = sd_bus_message_append(m, "(sv)", "Description", "s", arg_description);
622 0 : if (r < 0)
623 0 : return bus_log_create_error(r);
624 :
625 0 : if (arg_aggressive_gc) {
626 0 : r = sd_bus_message_append(m, "(sv)", "CollectMode", "s", "inactive-or-failed");
627 0 : if (r < 0)
628 0 : return bus_log_create_error(r);
629 : }
630 :
631 0 : r = bus_append_unit_property_assignment_many(m, t, properties);
632 0 : if (r < 0)
633 0 : return r;
634 :
635 0 : return 0;
636 : }
637 :
638 0 : static int transient_cgroup_set_properties(sd_bus_message *m) {
639 : int r;
640 0 : assert(m);
641 :
642 0 : if (!isempty(arg_slice)) {
643 0 : _cleanup_free_ char *slice = NULL;
644 :
645 0 : r = unit_name_mangle_with_suffix(arg_slice, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".slice", &slice);
646 0 : if (r < 0)
647 0 : return log_error_errno(r, "Failed to mangle name '%s': %m", arg_slice);
648 :
649 0 : r = sd_bus_message_append(m, "(sv)", "Slice", "s", slice);
650 0 : if (r < 0)
651 0 : return bus_log_create_error(r);
652 : }
653 :
654 0 : return 0;
655 : }
656 :
657 0 : static int transient_kill_set_properties(sd_bus_message *m) {
658 : int r;
659 :
660 0 : assert(m);
661 :
662 0 : if (arg_send_sighup) {
663 0 : r = sd_bus_message_append(m, "(sv)", "SendSIGHUP", "b", arg_send_sighup);
664 0 : if (r < 0)
665 0 : return bus_log_create_error(r);
666 : }
667 :
668 0 : return 0;
669 : }
670 :
671 0 : static int transient_service_set_properties(sd_bus_message *m, const char *pty_path) {
672 0 : bool send_term = false;
673 : int r;
674 :
675 0 : assert(m);
676 :
677 0 : r = transient_unit_set_properties(m, UNIT_SERVICE, arg_property);
678 0 : if (r < 0)
679 0 : return r;
680 :
681 0 : r = transient_kill_set_properties(m);
682 0 : if (r < 0)
683 0 : return r;
684 :
685 0 : r = transient_cgroup_set_properties(m);
686 0 : if (r < 0)
687 0 : return r;
688 :
689 0 : if (arg_wait || arg_stdio != ARG_STDIO_NONE) {
690 0 : r = sd_bus_message_append(m, "(sv)", "AddRef", "b", 1);
691 0 : if (r < 0)
692 0 : return bus_log_create_error(r);
693 : }
694 :
695 0 : if (arg_remain_after_exit) {
696 0 : r = sd_bus_message_append(m, "(sv)", "RemainAfterExit", "b", arg_remain_after_exit);
697 0 : if (r < 0)
698 0 : return bus_log_create_error(r);
699 : }
700 :
701 0 : if (arg_service_type) {
702 0 : r = sd_bus_message_append(m, "(sv)", "Type", "s", arg_service_type);
703 0 : if (r < 0)
704 0 : return bus_log_create_error(r);
705 : }
706 :
707 0 : if (arg_exec_user) {
708 0 : r = sd_bus_message_append(m, "(sv)", "User", "s", arg_exec_user);
709 0 : if (r < 0)
710 0 : return bus_log_create_error(r);
711 : }
712 :
713 0 : if (arg_exec_group) {
714 0 : r = sd_bus_message_append(m, "(sv)", "Group", "s", arg_exec_group);
715 0 : if (r < 0)
716 0 : return bus_log_create_error(r);
717 : }
718 :
719 0 : if (arg_nice_set) {
720 0 : r = sd_bus_message_append(m, "(sv)", "Nice", "i", arg_nice);
721 0 : if (r < 0)
722 0 : return bus_log_create_error(r);
723 : }
724 :
725 0 : if (arg_working_directory) {
726 0 : r = sd_bus_message_append(m, "(sv)", "WorkingDirectory", "s", arg_working_directory);
727 0 : if (r < 0)
728 0 : return bus_log_create_error(r);
729 : }
730 :
731 0 : if (pty_path) {
732 0 : 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 0 : if (r < 0)
739 0 : return bus_log_create_error(r);
740 :
741 0 : send_term = true;
742 :
743 0 : } else if (arg_stdio == ARG_STDIO_DIRECT) {
744 0 : 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 0 : if (r < 0)
750 0 : return bus_log_create_error(r);
751 :
752 0 : send_term = isatty(STDIN_FILENO) || isatty(STDOUT_FILENO) || isatty(STDERR_FILENO);
753 : }
754 :
755 0 : if (send_term) {
756 : const char *e;
757 :
758 0 : e = getenv("TERM");
759 0 : if (e) {
760 : char *n;
761 :
762 0 : n = strjoina("TERM=", e);
763 0 : r = sd_bus_message_append(m,
764 : "(sv)",
765 : "Environment", "as", 1, n);
766 0 : if (r < 0)
767 0 : return bus_log_create_error(r);
768 : }
769 : }
770 :
771 0 : if (!strv_isempty(arg_environment)) {
772 0 : r = sd_bus_message_open_container(m, 'r', "sv");
773 0 : if (r < 0)
774 0 : return bus_log_create_error(r);
775 :
776 0 : r = sd_bus_message_append(m, "s", "Environment");
777 0 : if (r < 0)
778 0 : return bus_log_create_error(r);
779 :
780 0 : r = sd_bus_message_open_container(m, 'v', "as");
781 0 : if (r < 0)
782 0 : return bus_log_create_error(r);
783 :
784 0 : r = sd_bus_message_append_strv(m, arg_environment);
785 0 : if (r < 0)
786 0 : return bus_log_create_error(r);
787 :
788 0 : r = sd_bus_message_close_container(m);
789 0 : if (r < 0)
790 0 : return bus_log_create_error(r);
791 :
792 0 : r = sd_bus_message_close_container(m);
793 0 : if (r < 0)
794 0 : return bus_log_create_error(r);
795 : }
796 :
797 : /* Exec container */
798 0 : if (!strv_isempty(arg_cmdline)) {
799 0 : r = sd_bus_message_open_container(m, 'r', "sv");
800 0 : if (r < 0)
801 0 : return bus_log_create_error(r);
802 :
803 0 : r = sd_bus_message_append(m, "s", "ExecStart");
804 0 : if (r < 0)
805 0 : return bus_log_create_error(r);
806 :
807 0 : r = sd_bus_message_open_container(m, 'v', "a(sasb)");
808 0 : if (r < 0)
809 0 : return bus_log_create_error(r);
810 :
811 0 : r = sd_bus_message_open_container(m, 'a', "(sasb)");
812 0 : if (r < 0)
813 0 : return bus_log_create_error(r);
814 :
815 0 : r = sd_bus_message_open_container(m, 'r', "sasb");
816 0 : if (r < 0)
817 0 : return bus_log_create_error(r);
818 :
819 0 : r = sd_bus_message_append(m, "s", arg_cmdline[0]);
820 0 : if (r < 0)
821 0 : return bus_log_create_error(r);
822 :
823 0 : r = sd_bus_message_append_strv(m, arg_cmdline);
824 0 : if (r < 0)
825 0 : return bus_log_create_error(r);
826 :
827 0 : r = sd_bus_message_append(m, "b", false);
828 0 : if (r < 0)
829 0 : return bus_log_create_error(r);
830 :
831 0 : r = sd_bus_message_close_container(m);
832 0 : if (r < 0)
833 0 : return bus_log_create_error(r);
834 :
835 0 : r = sd_bus_message_close_container(m);
836 0 : if (r < 0)
837 0 : return bus_log_create_error(r);
838 :
839 0 : r = sd_bus_message_close_container(m);
840 0 : if (r < 0)
841 0 : return bus_log_create_error(r);
842 :
843 0 : r = sd_bus_message_close_container(m);
844 0 : if (r < 0)
845 0 : return bus_log_create_error(r);
846 : }
847 :
848 0 : return 0;
849 : }
850 :
851 0 : static int transient_scope_set_properties(sd_bus_message *m) {
852 : int r;
853 :
854 0 : assert(m);
855 :
856 0 : r = transient_unit_set_properties(m, UNIT_SCOPE, arg_property);
857 0 : if (r < 0)
858 0 : return r;
859 :
860 0 : r = transient_kill_set_properties(m);
861 0 : if (r < 0)
862 0 : return r;
863 :
864 0 : r = transient_cgroup_set_properties(m);
865 0 : if (r < 0)
866 0 : return r;
867 :
868 0 : r = sd_bus_message_append(m, "(sv)", "PIDs", "au", 1, (uint32_t) getpid_cached());
869 0 : if (r < 0)
870 0 : return bus_log_create_error(r);
871 :
872 0 : return 0;
873 : }
874 :
875 0 : static int transient_timer_set_properties(sd_bus_message *m) {
876 : int r;
877 :
878 0 : assert(m);
879 :
880 0 : r = transient_unit_set_properties(m, UNIT_TIMER, arg_timer_property);
881 0 : if (r < 0)
882 0 : return r;
883 :
884 : /* Automatically clean up our transient timers */
885 0 : r = sd_bus_message_append(m, "(sv)", "RemainAfterElapse", "b", false);
886 0 : if (r < 0)
887 0 : return bus_log_create_error(r);
888 :
889 0 : return 0;
890 : }
891 :
892 0 : 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 0 : assert(bus);
898 0 : assert(t >= 0);
899 0 : assert(t < _UNIT_TYPE_MAX);
900 :
901 0 : r = sd_bus_get_unique_name(bus, &unique);
902 0 : 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 0 : r = sd_id128_randomize(&rnd);
911 0 : if (r < 0)
912 0 : return log_error_errno(r, "Failed to generate random run unit name: %m");
913 :
914 0 : if (asprintf(ret, "run-r" SD_ID128_FORMAT_STR ".%s", SD_ID128_FORMAT_VAL(rnd), unit_type_to_string(t)) < 0)
915 0 : return log_oom();
916 :
917 0 : 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 0 : id = startswith(unique, ":1.");
924 0 : if (!id)
925 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL),
926 : "Unique name %s has unexpected format.",
927 : unique);
928 :
929 0 : p = strjoin("run-u", id, ".", unit_type_to_string(t));
930 0 : if (!p)
931 0 : return log_oom();
932 :
933 0 : *ret = p;
934 0 : 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 0 : static void run_context_free(RunContext *c) {
958 0 : assert(c);
959 :
960 0 : c->forward = pty_forward_free(c->forward);
961 0 : c->match = sd_bus_slot_unref(c->match);
962 0 : c->bus = sd_bus_unref(c->bus);
963 0 : c->event = sd_event_unref(c->event);
964 :
965 0 : free(c->active_state);
966 0 : free(c->result);
967 0 : }
968 :
969 0 : static void run_context_check_done(RunContext *c) {
970 : bool done;
971 :
972 0 : assert(c);
973 :
974 0 : if (c->match)
975 0 : done = STRPTR_IN_SET(c->active_state, "inactive", "failed");
976 : else
977 0 : done = true;
978 :
979 0 : if (c->forward && done) /* If the service is gone, it's time to drain the output */
980 0 : done = pty_forward_drain(c->forward);
981 :
982 0 : if (done)
983 0 : sd_event_exit(c->event, EXIT_SUCCESS);
984 0 : }
985 :
986 0 : 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 0 : _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1004 : int r;
1005 :
1006 0 : 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 0 : if (r < 0) {
1015 0 : sd_event_exit(c->event, EXIT_FAILURE);
1016 0 : return log_error_errno(r, "Failed to query unit state: %s", bus_error_message(&error, r));
1017 : }
1018 :
1019 0 : run_context_check_done(c);
1020 0 : return 0;
1021 : }
1022 :
1023 0 : static int on_properties_changed(sd_bus_message *m, void *userdata, sd_bus_error *error) {
1024 0 : RunContext *c = userdata;
1025 :
1026 0 : assert(m);
1027 0 : assert(c);
1028 :
1029 0 : return run_context_update(c, sd_bus_message_get_path(m));
1030 : }
1031 :
1032 0 : static int pty_forward_handler(PTYForward *f, int rcode, void *userdata) {
1033 0 : RunContext *c = userdata;
1034 :
1035 0 : assert(f);
1036 :
1037 0 : if (rcode < 0) {
1038 0 : sd_event_exit(c->event, EXIT_FAILURE);
1039 0 : return log_error_errno(rcode, "Error on PTY forwarding logic: %m");
1040 : }
1041 :
1042 0 : run_context_check_done(c);
1043 0 : return 0;
1044 : }
1045 :
1046 0 : static int start_transient_service(
1047 : sd_bus *bus,
1048 : int *retval) {
1049 :
1050 0 : _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
1051 0 : _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1052 0 : _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
1053 0 : _cleanup_free_ char *service = NULL, *pty_path = NULL;
1054 0 : _cleanup_close_ int master = -1;
1055 : int r;
1056 :
1057 0 : assert(bus);
1058 0 : assert(retval);
1059 :
1060 0 : if (arg_stdio == ARG_STDIO_PTY) {
1061 :
1062 0 : if (arg_transport == BUS_TRANSPORT_LOCAL) {
1063 0 : master = posix_openpt(O_RDWR|O_NOCTTY|O_CLOEXEC|O_NONBLOCK);
1064 0 : if (master < 0)
1065 0 : return log_error_errno(errno, "Failed to acquire pseudo tty: %m");
1066 :
1067 0 : r = ptsname_malloc(master, &pty_path);
1068 0 : if (r < 0)
1069 0 : return log_error_errno(r, "Failed to determine tty name: %m");
1070 :
1071 0 : if (unlockpt(master) < 0)
1072 0 : return log_error_errno(errno, "Failed to unlock tty: %m");
1073 :
1074 0 : } else if (arg_transport == BUS_TRANSPORT_MACHINE) {
1075 0 : _cleanup_(sd_bus_unrefp) sd_bus *system_bus = NULL;
1076 0 : _cleanup_(sd_bus_message_unrefp) sd_bus_message *pty_reply = NULL;
1077 : const char *s;
1078 :
1079 0 : r = sd_bus_default_system(&system_bus);
1080 0 : if (r < 0)
1081 0 : return log_error_errno(r, "Failed to connect to system bus: %m");
1082 :
1083 0 : 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 0 : if (r < 0)
1092 0 : return log_error_errno(r, "Failed to get machine PTY: %s", bus_error_message(&error, -r));
1093 :
1094 0 : r = sd_bus_message_read(pty_reply, "hs", &master, &s);
1095 0 : if (r < 0)
1096 0 : return bus_log_parse_error(r);
1097 :
1098 0 : master = fcntl(master, F_DUPFD_CLOEXEC, 3);
1099 0 : if (master < 0)
1100 0 : return log_error_errno(errno, "Failed to duplicate master fd: %m");
1101 :
1102 0 : pty_path = strdup(s);
1103 0 : if (!pty_path)
1104 0 : return log_oom();
1105 : } else
1106 0 : assert_not_reached("Can't allocate tty via ssh");
1107 : }
1108 :
1109 0 : if (!arg_no_block) {
1110 0 : r = bus_wait_for_jobs_new(bus, &w);
1111 0 : if (r < 0)
1112 0 : return log_error_errno(r, "Could not watch jobs: %m");
1113 : }
1114 :
1115 0 : if (arg_unit) {
1116 0 : r = unit_name_mangle_with_suffix(arg_unit, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".service", &service);
1117 0 : if (r < 0)
1118 0 : return log_error_errno(r, "Failed to mangle unit name: %m");
1119 : } else {
1120 0 : r = make_unit_name(bus, UNIT_SERVICE, &service);
1121 0 : if (r < 0)
1122 0 : return r;
1123 : }
1124 :
1125 0 : 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 0 : if (r < 0)
1133 0 : return bus_log_create_error(r);
1134 :
1135 0 : r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
1136 0 : if (r < 0)
1137 0 : return bus_log_create_error(r);
1138 :
1139 : /* Name and mode */
1140 0 : r = sd_bus_message_append(m, "ss", service, "fail");
1141 0 : if (r < 0)
1142 0 : return bus_log_create_error(r);
1143 :
1144 : /* Properties */
1145 0 : r = sd_bus_message_open_container(m, 'a', "(sv)");
1146 0 : if (r < 0)
1147 0 : return bus_log_create_error(r);
1148 :
1149 0 : r = transient_service_set_properties(m, pty_path);
1150 0 : if (r < 0)
1151 0 : return r;
1152 :
1153 0 : r = sd_bus_message_close_container(m);
1154 0 : if (r < 0)
1155 0 : return bus_log_create_error(r);
1156 :
1157 : /* Auxiliary units */
1158 0 : r = sd_bus_message_append(m, "a(sa(sv))", 0);
1159 0 : if (r < 0)
1160 0 : return bus_log_create_error(r);
1161 :
1162 0 : polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1163 :
1164 0 : r = sd_bus_call(bus, m, 0, &error, &reply);
1165 0 : if (r < 0)
1166 0 : return log_error_errno(r, "Failed to start transient service unit: %s", bus_error_message(&error, r));
1167 :
1168 0 : if (w) {
1169 : const char *object;
1170 :
1171 0 : r = sd_bus_message_read(reply, "o", &object);
1172 0 : if (r < 0)
1173 0 : return bus_log_parse_error(r);
1174 :
1175 0 : r = bus_wait_for_jobs_one(w, object, arg_quiet);
1176 0 : if (r < 0)
1177 0 : return r;
1178 : }
1179 :
1180 0 : if (!arg_quiet)
1181 0 : log_info("Running as unit: %s", service);
1182 :
1183 0 : if (arg_wait || arg_stdio != ARG_STDIO_NONE) {
1184 0 : _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 0 : _cleanup_free_ char *path = NULL;
1194 :
1195 0 : c.bus = sd_bus_ref(bus);
1196 :
1197 0 : r = sd_event_default(&c.event);
1198 0 : if (r < 0)
1199 0 : return log_error_errno(r, "Failed to get event loop: %m");
1200 :
1201 0 : if (master >= 0) {
1202 0 : assert_se(sigprocmask_many(SIG_BLOCK, NULL, SIGWINCH, SIGTERM, SIGINT, -1) >= 0);
1203 0 : (void) sd_event_add_signal(c.event, NULL, SIGINT, NULL, NULL);
1204 0 : (void) sd_event_add_signal(c.event, NULL, SIGTERM, NULL, NULL);
1205 :
1206 0 : if (!arg_quiet)
1207 0 : log_info("Press ^] three times within 1s to disconnect TTY.");
1208 :
1209 0 : r = pty_forward_new(c.event, master, PTY_FORWARD_IGNORE_INITIAL_VHANGUP, &c.forward);
1210 0 : if (r < 0)
1211 0 : return log_error_errno(r, "Failed to create PTY forwarder: %m");
1212 :
1213 0 : 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 0 : (void) pty_forward_set_priority(c.forward, SD_EVENT_PRIORITY_IMPORTANT);
1217 : }
1218 :
1219 0 : path = unit_dbus_path_from_name(service);
1220 0 : if (!path)
1221 0 : return log_oom();
1222 :
1223 0 : 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 0 : if (r < 0)
1232 0 : return log_error_errno(r, "Failed to request properties changed signal match: %m");
1233 :
1234 0 : r = sd_bus_attach_event(bus, c.event, SD_EVENT_PRIORITY_NORMAL);
1235 0 : if (r < 0)
1236 0 : return log_error_errno(r, "Failed to attach bus to event loop: %m");
1237 :
1238 0 : r = run_context_update(&c, path);
1239 0 : if (r < 0)
1240 0 : return r;
1241 :
1242 0 : r = sd_event_loop(c.event);
1243 0 : if (r < 0)
1244 0 : return log_error_errno(r, "Failed to run event loop: %m");
1245 :
1246 0 : if (c.forward) {
1247 0 : char last_char = 0;
1248 :
1249 0 : r = pty_forward_get_last_char(c.forward, &last_char);
1250 0 : if (r >= 0 && !arg_quiet && last_char != '\n')
1251 0 : fputc('\n', stdout);
1252 : }
1253 :
1254 0 : 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 0 : c.forward = pty_forward_free(c.forward);
1260 :
1261 0 : if (!isempty(c.result))
1262 0 : log_info("Finished with result: %s", strna(c.result));
1263 :
1264 0 : if (c.exit_code == CLD_EXITED)
1265 0 : log_info("Main processes terminated with: code=%s/status=%i", sigchld_code_to_string(c.exit_code), c.exit_status);
1266 0 : else if (c.exit_code > 0)
1267 0 : 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 0 : if (timestamp_is_set(c.inactive_enter_usec) &&
1270 0 : timestamp_is_set(c.inactive_exit_usec) &&
1271 0 : c.inactive_enter_usec > c.inactive_exit_usec) {
1272 : char ts[FORMAT_TIMESPAN_MAX];
1273 0 : log_info("Service runtime: %s", format_timespan(ts, sizeof(ts), c.inactive_enter_usec - c.inactive_exit_usec, USEC_PER_MSEC));
1274 : }
1275 :
1276 0 : if (c.cpu_usage_nsec != NSEC_INFINITY) {
1277 : char ts[FORMAT_TIMESPAN_MAX];
1278 0 : 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 0 : if (c.ip_ingress_bytes != UINT64_MAX) {
1282 : char bytes[FORMAT_BYTES_MAX];
1283 0 : log_info("IP traffic received: %s", format_bytes(bytes, sizeof(bytes), c.ip_ingress_bytes));
1284 : }
1285 0 : if (c.ip_egress_bytes != UINT64_MAX) {
1286 : char bytes[FORMAT_BYTES_MAX];
1287 0 : log_info("IP traffic sent: %s", format_bytes(bytes, sizeof(bytes), c.ip_egress_bytes));
1288 : }
1289 0 : if (c.io_read_bytes != UINT64_MAX) {
1290 : char bytes[FORMAT_BYTES_MAX];
1291 0 : log_info("IO bytes read: %s", format_bytes(bytes, sizeof(bytes), c.io_read_bytes));
1292 : }
1293 0 : if (c.io_write_bytes != UINT64_MAX) {
1294 : char bytes[FORMAT_BYTES_MAX];
1295 0 : 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 0 : if (c.result && STR_IN_SET(c.result, "success", "exit-code") && c.exit_code == CLD_EXITED)
1301 0 : *retval = c.exit_status;
1302 : else
1303 0 : *retval = EXIT_FAILURE;
1304 : }
1305 :
1306 0 : return 0;
1307 : }
1308 :
1309 0 : static int acquire_invocation_id(sd_bus *bus, sd_id128_t *ret) {
1310 0 : _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1311 0 : _cleanup_(sd_bus_message_unrefp) sd_bus_message *reply = NULL;
1312 : const void *p;
1313 : size_t l;
1314 : int r;
1315 :
1316 0 : assert(bus);
1317 0 : assert(ret);
1318 :
1319 0 : 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 0 : if (r < 0)
1328 0 : return log_error_errno(r, "Failed to request invocation ID for scope: %s", bus_error_message(&error, r));
1329 :
1330 0 : r = sd_bus_message_read_array(reply, 'y', &p, &l);
1331 0 : if (r < 0)
1332 0 : return bus_log_parse_error(r);
1333 :
1334 0 : if (l != sizeof(sd_id128_t))
1335 0 : return log_error_errno(SYNTHETIC_ERRNO(EINVAL), "Invalid UUID size, %zu != %zu.", l, sizeof(sd_id128_t));
1336 :
1337 0 : memcpy(ret, p, l);
1338 0 : return 0;
1339 : }
1340 :
1341 0 : static int start_transient_scope(sd_bus *bus) {
1342 0 : _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1343 0 : _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
1344 0 : _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
1345 0 : _cleanup_strv_free_ char **env = NULL, **user_env = NULL;
1346 0 : _cleanup_free_ char *scope = NULL;
1347 0 : const char *object = NULL;
1348 : sd_id128_t invocation_id;
1349 : int r;
1350 :
1351 0 : assert(bus);
1352 0 : assert(!strv_isempty(arg_cmdline));
1353 :
1354 0 : r = bus_wait_for_jobs_new(bus, &w);
1355 0 : if (r < 0)
1356 0 : return log_oom();
1357 :
1358 0 : if (arg_unit) {
1359 0 : r = unit_name_mangle_with_suffix(arg_unit, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".scope", &scope);
1360 0 : if (r < 0)
1361 0 : return log_error_errno(r, "Failed to mangle scope name: %m");
1362 : } else {
1363 0 : r = make_unit_name(bus, UNIT_SCOPE, &scope);
1364 0 : if (r < 0)
1365 0 : return r;
1366 : }
1367 :
1368 0 : 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 0 : if (r < 0)
1376 0 : return bus_log_create_error(r);
1377 :
1378 0 : r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
1379 0 : if (r < 0)
1380 0 : return bus_log_create_error(r);
1381 :
1382 : /* Name and Mode */
1383 0 : r = sd_bus_message_append(m, "ss", scope, "fail");
1384 0 : if (r < 0)
1385 0 : return bus_log_create_error(r);
1386 :
1387 : /* Properties */
1388 0 : r = sd_bus_message_open_container(m, 'a', "(sv)");
1389 0 : if (r < 0)
1390 0 : return bus_log_create_error(r);
1391 :
1392 0 : r = transient_scope_set_properties(m);
1393 0 : if (r < 0)
1394 0 : return r;
1395 :
1396 0 : r = sd_bus_message_close_container(m);
1397 0 : if (r < 0)
1398 0 : return bus_log_create_error(r);
1399 :
1400 : /* Auxiliary units */
1401 0 : r = sd_bus_message_append(m, "a(sa(sv))", 0);
1402 0 : if (r < 0)
1403 0 : return bus_log_create_error(r);
1404 :
1405 0 : polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1406 :
1407 0 : r = sd_bus_call(bus, m, 0, &error, &reply);
1408 0 : if (r < 0)
1409 0 : return log_error_errno(r, "Failed to start transient scope unit: %s", bus_error_message(&error, -r));
1410 :
1411 0 : r = sd_bus_message_read(reply, "o", &object);
1412 0 : if (r < 0)
1413 0 : return bus_log_parse_error(r);
1414 :
1415 0 : r = bus_wait_for_jobs_one(w, object, arg_quiet);
1416 0 : if (r < 0)
1417 0 : return r;
1418 :
1419 0 : r = acquire_invocation_id(bus, &invocation_id);
1420 0 : if (r < 0)
1421 0 : return r;
1422 :
1423 0 : r = strv_extendf(&user_env, "INVOCATION_ID=" SD_ID128_FORMAT_STR, SD_ID128_FORMAT_VAL(invocation_id));
1424 0 : if (r < 0)
1425 0 : return log_oom();
1426 :
1427 0 : if (arg_nice_set) {
1428 0 : if (setpriority(PRIO_PROCESS, 0, arg_nice) < 0)
1429 0 : return log_error_errno(errno, "Failed to set nice level: %m");
1430 : }
1431 :
1432 0 : if (arg_exec_group) {
1433 : gid_t gid;
1434 :
1435 0 : r = get_group_creds(&arg_exec_group, &gid, 0);
1436 0 : if (r < 0)
1437 0 : return log_error_errno(r, "Failed to resolve group %s: %m", arg_exec_group);
1438 :
1439 0 : if (setresgid(gid, gid, gid) < 0)
1440 0 : return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
1441 : }
1442 :
1443 0 : if (arg_exec_user) {
1444 : const char *home, *shell;
1445 : uid_t uid;
1446 : gid_t gid;
1447 :
1448 0 : r = get_user_creds(&arg_exec_user, &uid, &gid, &home, &shell, USER_CREDS_CLEAN|USER_CREDS_PREFER_NSS);
1449 0 : if (r < 0)
1450 0 : return log_error_errno(r, "Failed to resolve user %s: %m", arg_exec_user);
1451 :
1452 0 : if (home) {
1453 0 : r = strv_extendf(&user_env, "HOME=%s", home);
1454 0 : if (r < 0)
1455 0 : return log_oom();
1456 : }
1457 :
1458 0 : if (shell) {
1459 0 : r = strv_extendf(&user_env, "SHELL=%s", shell);
1460 0 : if (r < 0)
1461 0 : return log_oom();
1462 : }
1463 :
1464 0 : r = strv_extendf(&user_env, "USER=%s", arg_exec_user);
1465 0 : if (r < 0)
1466 0 : return log_oom();
1467 :
1468 0 : r = strv_extendf(&user_env, "LOGNAME=%s", arg_exec_user);
1469 0 : if (r < 0)
1470 0 : return log_oom();
1471 :
1472 0 : if (!arg_exec_group) {
1473 0 : if (setresgid(gid, gid, gid) < 0)
1474 0 : return log_error_errno(errno, "Failed to change GID to " GID_FMT ": %m", gid);
1475 : }
1476 :
1477 0 : if (setresuid(uid, uid, uid) < 0)
1478 0 : return log_error_errno(errno, "Failed to change UID to " UID_FMT ": %m", uid);
1479 : }
1480 :
1481 0 : env = strv_env_merge(3, environ, user_env, arg_environment);
1482 0 : if (!env)
1483 0 : return log_oom();
1484 :
1485 0 : if (!arg_quiet)
1486 0 : log_info("Running scope as unit: %s", scope);
1487 :
1488 0 : execvpe(arg_cmdline[0], arg_cmdline, env);
1489 :
1490 0 : return log_error_errno(errno, "Failed to execute: %m");
1491 : }
1492 :
1493 0 : static int start_transient_trigger(
1494 : sd_bus *bus,
1495 : const char *suffix) {
1496 :
1497 0 : _cleanup_(sd_bus_error_free) sd_bus_error error = SD_BUS_ERROR_NULL;
1498 0 : _cleanup_(sd_bus_message_unrefp) sd_bus_message *m = NULL, *reply = NULL;
1499 0 : _cleanup_(bus_wait_for_jobs_freep) BusWaitForJobs *w = NULL;
1500 0 : _cleanup_free_ char *trigger = NULL, *service = NULL;
1501 0 : const char *object = NULL;
1502 : int r;
1503 :
1504 0 : assert(bus);
1505 :
1506 0 : r = bus_wait_for_jobs_new(bus, &w);
1507 0 : if (r < 0)
1508 0 : return log_oom();
1509 :
1510 0 : if (arg_unit) {
1511 0 : switch (unit_name_to_type(arg_unit)) {
1512 :
1513 0 : case UNIT_SERVICE:
1514 0 : service = strdup(arg_unit);
1515 0 : if (!service)
1516 0 : return log_oom();
1517 :
1518 0 : r = unit_name_change_suffix(service, suffix, &trigger);
1519 0 : if (r < 0)
1520 0 : return log_error_errno(r, "Failed to change unit suffix: %m");
1521 0 : break;
1522 :
1523 0 : case UNIT_TIMER:
1524 0 : trigger = strdup(arg_unit);
1525 0 : if (!trigger)
1526 0 : return log_oom();
1527 :
1528 0 : r = unit_name_change_suffix(trigger, ".service", &service);
1529 0 : if (r < 0)
1530 0 : return log_error_errno(r, "Failed to change unit suffix: %m");
1531 0 : break;
1532 :
1533 0 : default:
1534 0 : r = unit_name_mangle_with_suffix(arg_unit, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, ".service", &service);
1535 0 : if (r < 0)
1536 0 : return log_error_errno(r, "Failed to mangle unit name: %m");
1537 :
1538 0 : r = unit_name_mangle_with_suffix(arg_unit, arg_quiet ? 0 : UNIT_NAME_MANGLE_WARN, suffix, &trigger);
1539 0 : if (r < 0)
1540 0 : return log_error_errno(r, "Failed to mangle unit name: %m");
1541 :
1542 0 : break;
1543 : }
1544 : } else {
1545 0 : r = make_unit_name(bus, UNIT_SERVICE, &service);
1546 0 : if (r < 0)
1547 0 : return r;
1548 :
1549 0 : r = unit_name_change_suffix(service, suffix, &trigger);
1550 0 : if (r < 0)
1551 0 : return log_error_errno(r, "Failed to change unit suffix: %m");
1552 : }
1553 :
1554 0 : 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 0 : if (r < 0)
1562 0 : return bus_log_create_error(r);
1563 :
1564 0 : r = sd_bus_message_set_allow_interactive_authorization(m, arg_ask_password);
1565 0 : if (r < 0)
1566 0 : return bus_log_create_error(r);
1567 :
1568 : /* Name and Mode */
1569 0 : r = sd_bus_message_append(m, "ss", trigger, "fail");
1570 0 : if (r < 0)
1571 0 : return bus_log_create_error(r);
1572 :
1573 : /* Properties */
1574 0 : r = sd_bus_message_open_container(m, 'a', "(sv)");
1575 0 : if (r < 0)
1576 0 : return bus_log_create_error(r);
1577 :
1578 0 : if (streq(suffix, ".path"))
1579 0 : r = transient_unit_set_properties(m, UNIT_PATH, arg_path_property);
1580 0 : else if (streq(suffix, ".socket"))
1581 0 : r = transient_unit_set_properties(m, UNIT_SOCKET, arg_socket_property);
1582 0 : else if (streq(suffix, ".timer"))
1583 0 : r = transient_timer_set_properties(m);
1584 : else
1585 0 : assert_not_reached("Invalid suffix");
1586 0 : if (r < 0)
1587 0 : return r;
1588 :
1589 0 : r = sd_bus_message_close_container(m);
1590 0 : if (r < 0)
1591 0 : return bus_log_create_error(r);
1592 :
1593 0 : r = sd_bus_message_open_container(m, 'a', "(sa(sv))");
1594 0 : if (r < 0)
1595 0 : return bus_log_create_error(r);
1596 :
1597 0 : if (!strv_isempty(arg_cmdline)) {
1598 0 : r = sd_bus_message_open_container(m, 'r', "sa(sv)");
1599 0 : if (r < 0)
1600 0 : return bus_log_create_error(r);
1601 :
1602 0 : r = sd_bus_message_append(m, "s", service);
1603 0 : if (r < 0)
1604 0 : return bus_log_create_error(r);
1605 :
1606 0 : r = sd_bus_message_open_container(m, 'a', "(sv)");
1607 0 : if (r < 0)
1608 0 : return bus_log_create_error(r);
1609 :
1610 0 : r = transient_service_set_properties(m, NULL);
1611 0 : if (r < 0)
1612 0 : return r;
1613 :
1614 0 : r = sd_bus_message_close_container(m);
1615 0 : if (r < 0)
1616 0 : return bus_log_create_error(r);
1617 :
1618 0 : r = sd_bus_message_close_container(m);
1619 0 : if (r < 0)
1620 0 : return bus_log_create_error(r);
1621 : }
1622 :
1623 0 : r = sd_bus_message_close_container(m);
1624 0 : if (r < 0)
1625 0 : return bus_log_create_error(r);
1626 :
1627 0 : polkit_agent_open_if_enabled(arg_transport, arg_ask_password);
1628 :
1629 0 : r = sd_bus_call(bus, m, 0, &error, &reply);
1630 0 : if (r < 0)
1631 0 : return log_error_errno(r, "Failed to start transient %s unit: %s", suffix + 1, bus_error_message(&error, -r));
1632 :
1633 0 : r = sd_bus_message_read(reply, "o", &object);
1634 0 : if (r < 0)
1635 0 : return bus_log_parse_error(r);
1636 :
1637 0 : r = bus_wait_for_jobs_one(w, object, arg_quiet);
1638 0 : if (r < 0)
1639 0 : return r;
1640 :
1641 0 : if (!arg_quiet) {
1642 0 : log_info("Running %s as unit: %s", suffix + 1, trigger);
1643 0 : if (!strv_isempty(arg_cmdline))
1644 0 : log_info("Will run service as unit: %s", service);
1645 : }
1646 :
1647 0 : return 0;
1648 : }
1649 :
1650 4 : static int run(int argc, char* argv[]) {
1651 4 : _cleanup_(sd_bus_flush_close_unrefp) sd_bus *bus = NULL;
1652 4 : _cleanup_free_ char *description = NULL;
1653 4 : int r, retval = EXIT_SUCCESS;
1654 :
1655 4 : log_show_color(true);
1656 4 : log_parse_environment();
1657 4 : log_open();
1658 :
1659 4 : r = parse_argv(argc, argv);
1660 4 : if (r <= 0)
1661 4 : return r;
1662 :
1663 0 : if (!strv_isempty(arg_cmdline) && arg_transport == BUS_TRANSPORT_LOCAL) {
1664 0 : _cleanup_free_ char *command = NULL;
1665 :
1666 : /* Patch in an absolute path */
1667 :
1668 0 : r = find_binary(arg_cmdline[0], &command);
1669 0 : if (r < 0)
1670 0 : return log_error_errno(r, "Failed to find executable %s: %m", arg_cmdline[0]);
1671 :
1672 0 : free_and_replace(arg_cmdline[0], command);
1673 : }
1674 :
1675 0 : if (!arg_description) {
1676 0 : description = strv_join(arg_cmdline, " ");
1677 0 : if (!description)
1678 0 : return log_oom();
1679 :
1680 0 : if (arg_unit && isempty(description)) {
1681 0 : r = free_and_strdup(&description, arg_unit);
1682 0 : if (r < 0)
1683 0 : return log_oom();
1684 : }
1685 :
1686 0 : arg_description = description;
1687 : }
1688 :
1689 : /* If --wait is used connect via the bus, unconditionally, as ref/unref is not supported via the limited direct
1690 : * connection */
1691 0 : if (arg_wait || arg_stdio != ARG_STDIO_NONE)
1692 0 : r = bus_connect_transport(arg_transport, arg_host, arg_user, &bus);
1693 : else
1694 0 : r = bus_connect_transport_systemd(arg_transport, arg_host, arg_user, &bus);
1695 0 : if (r < 0)
1696 0 : return log_error_errno(r, "Failed to create bus connection: %m");
1697 :
1698 0 : if (arg_scope)
1699 0 : r = start_transient_scope(bus);
1700 0 : else if (arg_path_property)
1701 0 : r = start_transient_trigger(bus, ".path");
1702 0 : else if (arg_socket_property)
1703 0 : r = start_transient_trigger(bus, ".socket");
1704 0 : else if (arg_with_timer)
1705 0 : r = start_transient_trigger(bus, ".timer");
1706 : else
1707 0 : r = start_transient_service(bus, &retval);
1708 0 : if (r < 0)
1709 0 : return r;
1710 :
1711 0 : return retval;
1712 : }
1713 :
1714 4 : DEFINE_MAIN_FUNCTION_WITH_POSITIVE_FAILURE(run);
|