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